Import any XML or CSV File to WordPress - Version 3.3.0

Version Description

  • added new options to taxonomies import 'Try to match terms to existing child Product Categories' & 'Only assign Products to the imported Product Category, not the entire hierarchy'
  • added support for Excel files ( .xls, .xlsx )
Download this release

Release Info

Developer soflyy
Plugin Icon 128x128 Import any XML or CSV File to WordPress
Version 3.3.0
Comparing to
See all releases

Code changes from version 3.2.9 to 3.3.0

Files changed (66) hide show
  1. actions/admin_notices.php +4 -4
  2. classes/api.php +104 -29
  3. classes/render.php +1 -1
  4. classes/upload.php +27 -7
  5. controllers/admin/import.php +14 -10
  6. controllers/admin/manage.php +12 -9
  7. controllers/admin/settings.php +3 -1
  8. helpers/functions.php +2 -5
  9. helpers/pmxi_findDuplicates.php +5 -0
  10. helpers/wp_all_import_get_parent_terms.php +22 -0
  11. helpers/wp_delete_attachments.php +34 -21
  12. libraries/PHPExcel.php +1139 -0
  13. libraries/PHPExcel/Autoloader.php +89 -0
  14. libraries/PHPExcel/CachedObjectStorage/APC.php +295 -0
  15. libraries/PHPExcel/CachedObjectStorage/CacheBase.php +376 -0
  16. libraries/PHPExcel/CachedObjectStorage/DiscISAM.php +219 -0
  17. libraries/PHPExcel/CachedObjectStorage/ICache.php +112 -0
  18. libraries/PHPExcel/CachedObjectStorage/Igbinary.php +152 -0
  19. libraries/PHPExcel/CachedObjectStorage/Memcache.php +312 -0
  20. libraries/PHPExcel/CachedObjectStorage/Memory.php +125 -0
  21. libraries/PHPExcel/CachedObjectStorage/MemoryGZip.php +137 -0
  22. libraries/PHPExcel/CachedObjectStorage/MemorySerialized.php +137 -0
  23. libraries/PHPExcel/CachedObjectStorage/PHPTemp.php +206 -0
  24. libraries/PHPExcel/CachedObjectStorage/SQLite.php +306 -0
  25. libraries/PHPExcel/CachedObjectStorage/SQLite3.php +345 -0
  26. libraries/PHPExcel/CachedObjectStorage/Wincache.php +294 -0
  27. libraries/PHPExcel/CachedObjectStorageFactory.php +251 -0
  28. libraries/PHPExcel/CalcEngine/CyclicReferenceStack.php +98 -0
  29. libraries/PHPExcel/CalcEngine/Logger.php +153 -0
  30. libraries/PHPExcel/Calculation.php +3952 -0
  31. libraries/PHPExcel/Calculation/Database.php +725 -0
  32. libraries/PHPExcel/Calculation/DateTime.php +1485 -0
  33. libraries/PHPExcel/Calculation/Engineering.php +2505 -0
  34. libraries/PHPExcel/Calculation/Exception.php +52 -0
  35. libraries/PHPExcel/Calculation/ExceptionHandler.php +49 -0
  36. libraries/PHPExcel/Calculation/Financial.php +2292 -0
  37. libraries/PHPExcel/Calculation/FormulaParser.php +614 -0
  38. libraries/PHPExcel/Calculation/FormulaToken.php +176 -0
  39. libraries/PHPExcel/Calculation/Function.php +149 -0
  40. libraries/PHPExcel/Calculation/Functions.php +725 -0
  41. libraries/PHPExcel/Calculation/Logical.php +288 -0
  42. libraries/PHPExcel/Calculation/LookupRef.php +876 -0
  43. libraries/PHPExcel/Calculation/MathTrig.php +1376 -0
  44. libraries/PHPExcel/Calculation/Statistical.php +3651 -0
  45. libraries/PHPExcel/Calculation/TextData.php +630 -0
  46. libraries/PHPExcel/Calculation/Token/Stack.php +115 -0
  47. libraries/PHPExcel/Calculation/functionlist.txt +351 -0
  48. libraries/PHPExcel/Cell.php +1022 -0
  49. libraries/PHPExcel/Cell/AdvancedValueBinder.php +192 -0
  50. libraries/PHPExcel/Cell/DataType.php +122 -0
  51. libraries/PHPExcel/Cell/DataValidation.php +472 -0
  52. libraries/PHPExcel/Cell/DefaultValueBinder.php +110 -0
  53. libraries/PHPExcel/Cell/Hyperlink.php +126 -0
  54. libraries/PHPExcel/Cell/IValueBinder.php +46 -0
  55. libraries/PHPExcel/Comment.php +327 -0
  56. libraries/PHPExcel/DocumentProperties.php +587 -0
  57. libraries/PHPExcel/DocumentSecurity.php +218 -0
  58. libraries/PHPExcel/Exception.php +52 -0
  59. libraries/PHPExcel/HashTable.php +202 -0
  60. libraries/PHPExcel/IComparable.php +43 -0
  61. libraries/PHPExcel/IOFactory.php +288 -0
  62. libraries/PHPExcel/NamedRange.php +246 -0
  63. libraries/PHPExcel/Reader/Abstract.php +255 -0
  64. libraries/PHPExcel/Reader/CSV.php +387 -0
  65. libraries/PHPExcel/Reader/DefaultReadFilter.php +58 -0
  66. libraries/PHPExcel/Reader/Excel2003XML.php +145 -0
actions/admin_notices.php CHANGED
@@ -36,7 +36,7 @@ function pmxi_admin_notices() {
36
  ?>
37
  <div class="error"><p>
38
  <?php printf(
39
- __('<b>%s Plugin</b>: Please update your WP All Import ACF add-on to the latest version</a>', 'pmwi_plugin'),
40
  PMAI_Plugin::getInstance()->getName()
41
  ) ?>
42
  </p></div>
@@ -53,7 +53,7 @@ function pmxi_admin_notices() {
53
  ?>
54
  <div class="error"><p>
55
  <?php printf(
56
- __('<b>%s Plugin</b>: Please update your WP All Import Linkcloak add-on to the latest version</a>', 'pmwi_plugin'),
57
  PMLCA_Plugin::getInstance()->getName()
58
  ) ?>
59
  </p></div>
@@ -70,7 +70,7 @@ function pmxi_admin_notices() {
70
  ?>
71
  <div class="error"><p>
72
  <?php printf(
73
- __('<b>%s Plugin</b>: Please update your WP All Import User add-on to the latest version</a>', 'pmwi_plugin'),
74
  PMUI_Plugin::getInstance()->getName()
75
  ) ?>
76
  </p></div>
@@ -87,7 +87,7 @@ function pmxi_admin_notices() {
87
  ?>
88
  <div class="error"><p>
89
  <?php printf(
90
- __('<b>%s Plugin</b>: Please update your WP All Import WPML add-on to the latest version</a>', 'pmwi_plugin'),
91
  PMLI_Plugin::getInstance()->getName()
92
  ) ?>
93
  </p></div>
36
  ?>
37
  <div class="error"><p>
38
  <?php printf(
39
+ __('<b>%s Plugin</b>: Please update your WP All Import ACF add-on to the latest version', 'pmwi_plugin'),
40
  PMAI_Plugin::getInstance()->getName()
41
  ) ?>
42
  </p></div>
53
  ?>
54
  <div class="error"><p>
55
  <?php printf(
56
+ __('<b>%s Plugin</b>: Please update your WP All Import Linkcloak add-on to the latest version', 'pmwi_plugin'),
57
  PMLCA_Plugin::getInstance()->getName()
58
  ) ?>
59
  </p></div>
70
  ?>
71
  <div class="error"><p>
72
  <?php printf(
73
+ __('<b>%s Plugin</b>: Please update your WP All Import User add-on to the latest version', 'pmwi_plugin'),
74
  PMUI_Plugin::getInstance()->getName()
75
  ) ?>
76
  </p></div>
87
  ?>
88
  <div class="error"><p>
89
  <?php printf(
90
+ __('<b>%s Plugin</b>: Please update your WP All Import WPML add-on to the latest version', 'pmwi_plugin'),
91
  PMLI_Plugin::getInstance()->getName()
92
  ) ?>
93
  </p></div>
classes/api.php CHANGED
@@ -62,7 +62,7 @@ class PMXI_API
62
  case 'enum':
63
 
64
  $is_set_with_xpath_visible = true;
65
- foreach ($params['enum_values'] as $key => $value): ?>
66
  <div class="form-field wpallimport-radio-field">
67
  <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_<?php echo $key; ?>" class="switcher" name="<?php echo $params['field_name']; ?>" value="<?php echo $key; ?>" <?php echo $key == $params['field_value'] ? 'checked="checked"': '' ?>/>
68
  <?php
@@ -109,7 +109,7 @@ class PMXI_API
109
  <?php endforeach;?>
110
  <?php if ( $is_set_with_xpath_visible ): ?>
111
  <div class="form-field wpallimport-radio-field">
112
- <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_xpath" class="switcher" name="<?php echo $params['field_name']; ?>" value="xpath" <?php echo 'xpath' == $params['field_value'] ? 'checked="checked"': '' ?>/>
113
  <label for="<?php echo sanitize_title($params['field_name']); ?>_xpath"><?php _e('Set with XPath', 'wp_all_import_plugin' )?></label>
114
  <span class="wpallimport-clear"></span>
115
  <div class="switcher-target-<?php echo sanitize_title($params['field_name']); ?>_xpath set_with_xpath">
@@ -270,6 +270,26 @@ class PMXI_API
270
  <?php
271
  break;
272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273
  case 'accordion':
274
 
275
  $is_full_width = true;
@@ -285,13 +305,13 @@ class PMXI_API
285
 
286
  $in_the_bottom = $params['in_the_bottom'];
287
 
288
- $styles = ($is_full_width) ? 'margin-left: -25px; margin-right: -25px;' : 'margin-top: -16px;';
289
 
290
- if ( ! $in_the_bottom and $is_full_width ) $styles .= 'margin-top: 25px; margin-bottom: 25px;';
291
 
292
  ?>
293
- <div class="wpallimport-collapsed closed wpallimport-section <?php echo (($in_the_bottom and $is_full_width) ? 'wpallimport-sub-options-full-width' : 'wpallimport-sub-options'); echo ((!$is_full_width) ? ' wpallimport-dependent-options' : '');?> " style="<?php echo $styles; ?>">
294
- <div class="wpallimport-content-section <?php echo (($is_full_width and !$in_the_bottom) ? 'rad0' : 'wpallimport-bottom-radius');?> ">
295
  <div class="wpallimport-collapsed-header">
296
  <h3 style="color:#40acad;"><?php echo $label; ?></h3>
297
  </div>
@@ -328,13 +348,15 @@ class PMXI_API
328
 
329
  }
330
 
331
- public static function upload_image($pid, $img_url, $download_images, $logger, $create_image = false, $image_name = ""){
 
 
332
 
333
  $url = str_replace(" ", "%20", trim($img_url));
334
  $bn = preg_replace('/[\\?|&].*/', '', basename($url));
335
 
336
  if ($image_name == ""){
337
- $img_ext = pmxi_getExtensionFromStr($url);
338
  $default_extension = pmxi_getExtension($bn);
339
  if ($img_ext == "") $img_ext = pmxi_get_remote_image_ext($url);
340
  $image_name = urldecode(sanitize_file_name(($img_ext) ? str_replace("." . $default_extension, "", $bn) : $bn)) . (("" != $img_ext) ? '.' . $img_ext : '');
@@ -345,6 +367,7 @@ class PMXI_API
345
  $targetUrl = $uploads['url'];
346
  $download_image = true;
347
  $result = false;
 
348
 
349
  global $wpdb;
350
 
@@ -371,31 +394,63 @@ class PMXI_API
371
  $logger and call_user_func($logger, sprintf(__('- Searching for existing image `%s` in `%s` folder', 'wp_all_import_plugin'), $wpai_image_path, $wpai_uploads));
372
 
373
  if ( @file_exists($wpai_image_path) and @copy( $wpai_image_path, $image_filepath )){
374
- $download_image = false;
375
- if( ! ($image_info = @getimagesize($image_filepath)) or ! in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
376
- $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
377
- @unlink($image_filepath);
378
- } else {
379
- $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
380
- $result = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  }
382
  }
383
  }
384
 
385
  if ($download_image){
386
 
387
- $logger and call_user_func($logger, sprintf(__('- Downloading image from `%s`', 'wp_all_import_plugin'), $url));
 
 
 
 
 
388
 
389
  $request = get_file_curl($url, $image_filepath);
390
 
391
  if ( (is_wp_error($request) or $request === false) and ! @file_put_contents($image_filepath, @file_get_contents($url))) {
392
  @unlink($image_filepath); // delete file since failed upload may result in empty file created
393
- } elseif( ($image_info = @getimagesize($image_filepath)) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
394
- $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
395
- $result = true;
 
 
 
 
 
 
 
 
 
 
 
 
396
  }
397
 
398
- if (!$result){
399
  $url = str_replace(" ", "%20", trim(pmxi_convert_encoding($img_url)));
400
 
401
  $request = get_file_curl($url, $image_filepath);
@@ -403,27 +458,47 @@ class PMXI_API
403
  if ( (is_wp_error($request) or $request === false) and ! @file_put_contents($image_filepath, @file_get_contents($url))) {
404
  $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s cannot be saved locally as %s', 'wp_all_import_plugin'), $url, $image_filepath));
405
  @unlink($image_filepath); // delete file since failed upload may result in empty file created
406
- } elseif( ! ($image_info = @getimagesize($image_filepath)) or ! in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
407
- $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url));
408
- @unlink($image_filepath);
409
- } else {
410
- $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
411
- $result = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  }
413
  }
414
  }
415
 
416
  if ($create_image and $result){
417
 
418
- $logger and call_user_func($logger, sprintf(__('- Creating an attachment for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
 
 
 
 
 
419
 
420
  $attachment = array(
421
- 'post_mime_type' => image_type_to_mime_type($image_info[2]),
422
  'guid' => $targetUrl . '/' . $image_filename,
423
  'post_title' => $image_filename,
424
  'post_content' => '',
425
  );
426
- if (($image_meta = wp_read_image_metadata($image_filepath))) {
427
  if (trim($image_meta['title']) && ! is_numeric(sanitize_title($image_meta['title'])))
428
  $attachment['post_title'] = $image_meta['title'];
429
  if (trim($image_meta['caption']))
62
  case 'enum':
63
 
64
  $is_set_with_xpath_visible = true;
65
+ foreach ($params['enum_values'] as $key => $value):?>
66
  <div class="form-field wpallimport-radio-field">
67
  <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_<?php echo $key; ?>" class="switcher" name="<?php echo $params['field_name']; ?>" value="<?php echo $key; ?>" <?php echo $key == $params['field_value'] ? 'checked="checked"': '' ?>/>
68
  <?php
109
  <?php endforeach;?>
110
  <?php if ( $is_set_with_xpath_visible ): ?>
111
  <div class="form-field wpallimport-radio-field">
112
+ <input type="radio" id="<?php echo sanitize_title($params['field_name']); ?>_xpath" class="switcher" name="<?php echo $params['field_name']; ?>" value="xpath" <?php echo 'xpath' === $params['field_value'] ? 'checked="checked"': '' ?>/>
113
  <label for="<?php echo sanitize_title($params['field_name']); ?>_xpath"><?php _e('Set with XPath', 'wp_all_import_plugin' )?></label>
114
  <span class="wpallimport-clear"></span>
115
  <div class="switcher-target-<?php echo sanitize_title($params['field_name']); ?>_xpath set_with_xpath">
270
  <?php
271
  break;
272
 
273
+ case 'file':
274
+ ?>
275
+ <div class="input">
276
+ <div class="input" style="margin: 0px;">
277
+ <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="yes" id="<?php echo sanitize_title($params['field_name']); ?>_yes" <?php echo ("yes" == $params['download_image']) ? 'checked="checked"' : '';?>/>
278
+ <label for="<?php echo sanitize_title($params['field_name']); ?>_yes"><?php _e('Download file hosted elsewhere'); ?></label>
279
+ <a href="#help" class="wpallimport-help" title="<?php _e('http:// or https://', 'wp_all_import_plugin') ?>" style="position: relative; top: -2px;">?</a>
280
+ </div>
281
+ <div class="input" style="margin: 0px;">
282
+ <?php $wp_uploads = wp_upload_dir(); ?>
283
+ <input type="radio" name="<?php echo $params['addon_prefix'];?>[download_image][<?php echo $params['field_key'];?>]" value="no" id="<?php echo sanitize_title($params['field_name']); ?>_no" <?php echo ("yes" != $params['download_image']) ? 'checked="checked"' : '';?>/>
284
+ <label for="<?php echo sanitize_title($params['field_name']); ?>_no"><?php printf(__('Use file(s) currently uploaded in %s', 'wp_all_import_plugin'), $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR); ?></label>
285
+ </div>
286
+ <div class="input">
287
+ <input type="text" name="<?php echo $params['field_name']; ?>" style="width:100%;" placeholder="" value="<?php echo esc_attr($params['field_value']); ?>"/>
288
+ </div>
289
+ </div>
290
+ <?php
291
+ break;
292
+
293
  case 'accordion':
294
 
295
  $is_full_width = true;
305
 
306
  $in_the_bottom = $params['in_the_bottom'];
307
 
308
+ $styles = ($is_full_width and $in_the_bottom) ? 'wpallimport-full-with-bottom' : '';
309
 
310
+ if ( ! $in_the_bottom and $is_full_width ) $styles = 'wpallimport-full-with-not-bottom';
311
 
312
  ?>
313
+ <div class="wpallimport-collapsed closed wpallimport-section <?php echo (($in_the_bottom and $is_full_width) ? 'wpallimport-sub-options-full-width' : 'wpallimport-sub-options'); echo ((!$is_full_width) ? ' wpallimport-dependent-options' : '');?> <?php echo $styles; ?>">
314
+ <div class="wpallimport-content-section <?php echo (($is_full_width and !$in_the_bottom) ? 'rad4' : 'wpallimport-bottom-radius');?>">
315
  <div class="wpallimport-collapsed-header">
316
  <h3 style="color:#40acad;"><?php echo $label; ?></h3>
317
  </div>
348
 
349
  }
350
 
351
+ public static function upload_image($pid, $img_url, $download_images, $logger, $create_image = false, $image_name = "", $file_type = 'images'){
352
+
353
+ if (empty($img_url)) return false;
354
 
355
  $url = str_replace(" ", "%20", trim($img_url));
356
  $bn = preg_replace('/[\\?|&].*/', '', basename($url));
357
 
358
  if ($image_name == ""){
359
+ $img_ext = pmxi_getExtensionFromStr($url);
360
  $default_extension = pmxi_getExtension($bn);
361
  if ($img_ext == "") $img_ext = pmxi_get_remote_image_ext($url);
362
  $image_name = urldecode(sanitize_file_name(($img_ext) ? str_replace("." . $default_extension, "", $bn) : $bn)) . (("" != $img_ext) ? '.' . $img_ext : '');
367
  $targetUrl = $uploads['url'];
368
  $download_image = true;
369
  $result = false;
370
+ $wp_filetype = false;
371
 
372
  global $wpdb;
373
 
394
  $logger and call_user_func($logger, sprintf(__('- Searching for existing image `%s` in `%s` folder', 'wp_all_import_plugin'), $wpai_image_path, $wpai_uploads));
395
 
396
  if ( @file_exists($wpai_image_path) and @copy( $wpai_image_path, $image_filepath )){
397
+ $download_image = false;
398
+ // valdate import attachments
399
+ if ($file_type == 'files'){
400
+ if( ! $wp_filetype = wp_check_filetype(basename($image_filepath), null )) {
401
+ $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($image_filepath)));
402
+ $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
403
+ @unlink($image_filepath);
404
+ }
405
+ else {
406
+ $result = true;
407
+ $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
408
+ }
409
+ }
410
+ // validate import images
411
+ elseif($file_type == 'images'){
412
+ if( ! ($image_info = @getimagesize($image_filepath)) or ! in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
413
+ $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
414
+ @unlink($image_filepath);
415
+ } else {
416
+ $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
417
+ $result = true;
418
+ }
419
  }
420
  }
421
  }
422
 
423
  if ($download_image){
424
 
425
+ if ($file_type == 'images'){
426
+ $logger and call_user_func($logger, sprintf(__('- Downloading image from `%s`', 'wp_all_import_plugin'), $url));
427
+ }
428
+ elseif ($file_type == 'files') {
429
+ $logger and call_user_func($logger, sprintf(__('- Downloading file from `%s`', 'wp_all_import_plugin'), $url));
430
+ }
431
 
432
  $request = get_file_curl($url, $image_filepath);
433
 
434
  if ( (is_wp_error($request) or $request === false) and ! @file_put_contents($image_filepath, @file_get_contents($url))) {
435
  @unlink($image_filepath); // delete file since failed upload may result in empty file created
436
+ } else{
437
+
438
+ if($file_type == 'images'){
439
+ if( ($image_info = @getimagesize($image_filepath)) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
440
+ $result = true;
441
+ $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
442
+ }
443
+ }
444
+ elseif($file_type == 'files'){
445
+ if( $wp_filetype = wp_check_filetype(basename($image_filepath), null )) {
446
+ $result = true;
447
+ $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
448
+ }
449
+ }
450
+
451
  }
452
 
453
+ if ( ! $result ){
454
  $url = str_replace(" ", "%20", trim(pmxi_convert_encoding($img_url)));
455
 
456
  $request = get_file_curl($url, $image_filepath);
458
  if ( (is_wp_error($request) or $request === false) and ! @file_put_contents($image_filepath, @file_get_contents($url))) {
459
  $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s cannot be saved locally as %s', 'wp_all_import_plugin'), $url, $image_filepath));
460
  @unlink($image_filepath); // delete file since failed upload may result in empty file created
461
+ } else{
462
+
463
+ if($file_type == 'images'){
464
+ if( ! ($image_info = @getimagesize($image_filepath)) or ! in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
465
+ $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url));
466
+ @unlink($image_filepath);
467
+ } else {
468
+ $result = true;
469
+ $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
470
+ }
471
+ }
472
+ elseif($file_type == 'files'){
473
+ if( ! $wp_filetype = wp_check_filetype(basename($image_filepath), null )) {
474
+ $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($url)));
475
+ @unlink($image_filepath);
476
+ }
477
+ else {
478
+ $result = true;
479
+ $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $url));
480
+ }
481
+ }
482
  }
483
  }
484
  }
485
 
486
  if ($create_image and $result){
487
 
488
+ if($file_type == 'images'){
489
+ $logger and call_user_func($logger, sprintf(__('- Creating an attachment for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
490
+ }
491
+ else{
492
+ $logger and call_user_func($logger, sprintf(__('- Creating an attachment for file `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
493
+ }
494
 
495
  $attachment = array(
496
+ 'post_mime_type' => ($file_type == 'images') ? image_type_to_mime_type($image_info[2]) : $wp_filetype['type'],
497
  'guid' => $targetUrl . '/' . $image_filename,
498
  'post_title' => $image_filename,
499
  'post_content' => '',
500
  );
501
+ if ($file_type == 'images' and ($image_meta = wp_read_image_metadata($image_filepath))) {
502
  if (trim($image_meta['title']) && ! is_numeric(sanitize_title($image_meta['title'])))
503
  $attachment['post_title'] = $image_meta['title'];
504
  if (trim($image_meta['caption']))
classes/render.php CHANGED
@@ -103,7 +103,7 @@ if ( ! class_exists('PMXI_Render')){
103
 
104
  if ("" != $path){
105
  if ($lvl > 1) $path .= "->" . $el->nodeName; else $path = $el->nodeName;
106
- echo '<option value="'.$path.'">' .$path . '</option>';
107
  }
108
  else $path = $el->nodeName;
109
 
103
 
104
  if ("" != $path){
105
  if ($lvl > 1) $path .= "->" . $el->nodeName; else $path = $el->nodeName;
106
+ echo '<option value="'.$path.'['. $lvl .']">' .$path . '['. $lvl .']</option>';
107
  }
108
  else $path = $el->nodeName;
109
 
classes/upload.php CHANGED
@@ -31,7 +31,7 @@ if ( ! class_exists('PMXI_Upload')){
31
  $this->errors->add('form-validation', __('Please specify a file to import.<br/><br/>If you are uploading the file from your computer, please wait for it to finish uploading (progress bar at 100%), before trying to continue.', 'wp_all_import_plugin'));
32
  } elseif (!is_file($this->file)) {
33
  $this->errors->add('form-validation', __('Uploaded file is empty', 'wp_all_import_plugin'));
34
- } elseif ( ! preg_match('%\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql)$%i', trim(basename($this->file)))) {
35
  $this->errors->add('form-validation', __('Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV', 'wp_all_import_plugin'));
36
  } elseif (preg_match('%\W(zip)$%i', trim(basename($this->file)))) {
37
 
@@ -47,7 +47,7 @@ if ( ! class_exists('PMXI_Upload')){
47
 
48
  if (!empty($v_result_list)){
49
  foreach ($v_result_list as $unzipped_file) {
50
- if ($unzipped_file['status'] == 'ok' and preg_match('%\W(xml|csv|txt|dat|psv|json)$%i', trim($unzipped_file['stored_filename']))) { $filePath = $unzipped_file['filename']; break; }
51
  }
52
  }
53
  if ( $this->uploadsPath === false ){
@@ -126,7 +126,17 @@ if ( ! class_exists('PMXI_Upload')){
126
  $sql = new PMXI_SQLParser( $localSQLPath, $this->uploadsPath );
127
  $filePath = $sql->parse();
128
  wp_all_import_remove_source($localSQLPath, false);
129
- }
 
 
 
 
 
 
 
 
 
 
130
  }
131
 
132
  } elseif ( preg_match('%\W(csv|txt|dat|psv)$%i', trim($this->file))) { // If CSV file uploaded
@@ -223,6 +233,19 @@ if ( ! class_exists('PMXI_Upload')){
223
  $filePath = $sql->parse();
224
  //@unlink($this->file);
225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  } else { // If XML file uploaded
227
 
228
  // Detect if file is very large
@@ -243,9 +266,6 @@ if ( ! class_exists('PMXI_Upload')){
243
  'root_element' => $this->root_element,
244
  'is_csv' => $this->is_csv
245
  );
246
- }
247
-
248
-
249
  }
250
-
251
  }
31
  $this->errors->add('form-validation', __('Please specify a file to import.<br/><br/>If you are uploading the file from your computer, please wait for it to finish uploading (progress bar at 100%), before trying to continue.', 'wp_all_import_plugin'));
32
  } elseif (!is_file($this->file)) {
33
  $this->errors->add('form-validation', __('Uploaded file is empty', 'wp_all_import_plugin'));
34
+ } elseif ( ! preg_match('%\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($this->file)))) {
35
  $this->errors->add('form-validation', __('Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV', 'wp_all_import_plugin'));
36
  } elseif (preg_match('%\W(zip)$%i', trim(basename($this->file)))) {
37
 
47
 
48
  if (!empty($v_result_list)){
49
  foreach ($v_result_list as $unzipped_file) {
50
+ if ($unzipped_file['status'] == 'ok' and preg_match('%\W(xml|csv|txt|dat|psv|json|xls|xlsx)$%i', trim($unzipped_file['stored_filename']))) { $filePath = $unzipped_file['filename']; break; }
51
  }
52
  }
53
  if ( $this->uploadsPath === false ){
126
  $sql = new PMXI_SQLParser( $localSQLPath, $this->uploadsPath );
127
  $filePath = $sql->parse();
128
  wp_all_import_remove_source($localSQLPath, false);
129
+ }
130
+ elseif (preg_match('%\W(xls|xlsx)$%i', trim($filePath))){
131
+
132
+ include_once( PMXI_Plugin::ROOT_DIR . '/libraries/XmlImportXLSParse.php' );
133
+
134
+ $localXLSPath = $filePath;
135
+ $xls = new PMXI_XLSParser( $localXLSPath, $this->uploadsPath );
136
+ $filePath = $xls->parse();
137
+ wp_all_import_remove_source($localXLSPath, false);
138
+
139
+ }
140
  }
141
 
142
  } elseif ( preg_match('%\W(csv|txt|dat|psv)$%i', trim($this->file))) { // If CSV file uploaded
233
  $filePath = $sql->parse();
234
  //@unlink($this->file);
235
 
236
+ } elseif (preg_match('%\W(xls|xlsx)$%i', trim($this->file))){
237
+
238
+ $source = array(
239
+ 'name' => basename($this->file),
240
+ 'type' => 'upload',
241
+ 'path' => $this->file,
242
+ );
243
+
244
+ include_once( PMXI_Plugin::ROOT_DIR . '/libraries/XmlImportXLSParse.php' );
245
+
246
+ $xls = new PMXI_XLSParser( $this->file, $this->uploadsPath );
247
+ $filePath = $xls->parse();
248
+
249
  } else { // If XML file uploaded
250
 
251
  // Detect if file is very large
266
  'root_element' => $this->root_element,
267
  'is_csv' => $this->is_csv
268
  );
269
+ }
 
 
270
  }
 
271
  }
controllers/admin/import.php CHANGED
@@ -926,7 +926,8 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
926
  $get['slug'] . 'featured_image' => '',
927
  'import_encoding' => 'UTF-8',
928
  'tagno' => 0
929
- ));
 
930
  $wp_uploads = wp_upload_dir();
931
 
932
  $this->data['tagno'] = $tagno = min(max(intval($this->input->getpost('tagno', 1)), 1), PMXI_Plugin::$session->count);
@@ -994,7 +995,7 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
994
 
995
  PMXI_Plugin::$session->set('encoding', $post['import_encoding']);
996
  PMXI_Plugin::$session->save_data();
997
-
998
  // validate
999
  try {
1000
  $featured_image = ( 'yes' == $post[$get['slug'] . 'download_images']) ? $post[$get['slug'] . 'download_featured_image'] : $post[$get['slug'] . 'featured_image'];
@@ -1440,7 +1441,7 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
1440
  // assign some defaults
1441
  '' !== $post['date'] or $post['date'] = 'now';
1442
  '' !== $post['date_start'] or $post['date_start'] = 'now';
1443
- '' !== $post['date_end'] or $post['date_end'] = 'now';
1444
 
1445
  if ( ! empty($post['name']) and !empty($post['save_template_as']) ) { // save template in database
1446
  $template->getByName($post['name'])->set(array(
@@ -1451,7 +1452,7 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
1451
  'options' => $post
1452
  ))->save();
1453
  PMXI_Plugin::$session->set('saved_template', $template->id);
1454
- }
1455
 
1456
  if ($this->isWizard) {
1457
  PMXI_Plugin::$session->set('options', $post);
@@ -2191,9 +2192,12 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
2191
 
2192
  if ( $log_storage ){
2193
  $log_file = wp_all_import_secure_file( $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id ) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
2194
- if ( PMXI_Plugin::$session->action != 'continue' and file_exists($log_file)){
2195
- wp_all_import_remove_source($log_file, false);
2196
- }
 
 
 
2197
  }
2198
 
2199
  $this->data['ajax_processing'] = ("ajax" == $import->options['import_processing']) ? true : false;
@@ -2408,9 +2412,7 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
2408
  }
2409
  }
2410
 
2411
- if ( ( PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->local_paths) ) or ! $ajax_processing or ! empty($import->canceled) ) {
2412
-
2413
- do_action( 'pmxi_after_xml_import', $import->id );
2414
 
2415
  if ("ajax" != $import->options['import_processing'] and $log_storage ){
2416
  $log_file = wp_all_import_secure_file( $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id ) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
@@ -2450,6 +2452,8 @@ class PMXI_Admin_Import extends PMXI_Controller_Admin {
2450
 
2451
  if ( $ajax_processing ) ob_start();
2452
 
 
 
2453
  $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done');
2454
 
2455
  echo <<<COMPLETE
926
  $get['slug'] . 'featured_image' => '',
927
  'import_encoding' => 'UTF-8',
928
  'tagno' => 0
929
+ ));
930
+
931
  $wp_uploads = wp_upload_dir();
932
 
933
  $this->data['tagno'] = $tagno = min(max(intval($this->input->getpost('tagno', 1)), 1), PMXI_Plugin::$session->count);
995
 
996
  PMXI_Plugin::$session->set('encoding', $post['import_encoding']);
997
  PMXI_Plugin::$session->save_data();
998
+
999
  // validate
1000
  try {
1001
  $featured_image = ( 'yes' == $post[$get['slug'] . 'download_images']) ? $post[$get['slug'] . 'download_featured_image'] : $post[$get['slug'] . 'featured_image'];
1441
  // assign some defaults
1442
  '' !== $post['date'] or $post['date'] = 'now';
1443
  '' !== $post['date_start'] or $post['date_start'] = 'now';
1444
+ '' !== $post['date_end'] or $post['date_end'] = 'now';
1445
 
1446
  if ( ! empty($post['name']) and !empty($post['save_template_as']) ) { // save template in database
1447
  $template->getByName($post['name'])->set(array(
1452
  'options' => $post
1453
  ))->save();
1454
  PMXI_Plugin::$session->set('saved_template', $template->id);
1455
+ }
1456
 
1457
  if ($this->isWizard) {
1458
  PMXI_Plugin::$session->set('options', $post);
2192
 
2193
  if ( $log_storage ){
2194
  $log_file = wp_all_import_secure_file( $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id ) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
2195
+ if ( PMXI_Plugin::$session->action != 'continue'){
2196
+ if (file_exists($log_file))
2197
+ wp_all_import_remove_source($log_file, false);
2198
+
2199
+ //@file_put_contents($log_file, sprintf(__('<p>Source path `%s`</p>', 'wp_all_import_plugin'), $import->path));
2200
+ }
2201
  }
2202
 
2203
  $this->data['ajax_processing'] = ("ajax" == $import->options['import_processing']) ? true : false;
2412
  }
2413
  }
2414
 
2415
+ if ( ( PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->local_paths) ) or ! $ajax_processing or ! empty($import->canceled) ) {
 
 
2416
 
2417
  if ("ajax" != $import->options['import_processing'] and $log_storage ){
2418
  $log_file = wp_all_import_secure_file( $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id ) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
2452
 
2453
  if ( $ajax_processing ) ob_start();
2454
 
2455
+ do_action( 'pmxi_after_xml_import', $import->id );
2456
+
2457
  $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done');
2458
 
2459
  echo <<<COMPLETE
controllers/admin/manage.php CHANGED
@@ -36,7 +36,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
36
 
37
  if ( ! in_array($order, array('DESC', 'ASC'))){
38
  $order = 'DESC';
39
- }
40
 
41
  $list = new PMXI_Import_List();
42
  $post = new PMXI_Post_Record();
@@ -62,8 +62,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
62
  'total' => ceil($list->total() / $perPage),
63
  'current' => $pagenum,
64
  ));
65
-
66
- //pmxi_session_unset();
67
  PMXI_Plugin::$session->clean_session();
68
 
69
  $this->render();
@@ -193,9 +192,9 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
193
  $filePath = '';
194
 
195
  // upload new file in case when import is not continue
196
- if ( empty(PMXI_Plugin::$session->chunk_number) ) {
197
-
198
- if ( $item->type == 'upload' ){ // retrieve already uploaded file
199
 
200
  $uploader = new PMXI_Upload(trim($item->path), $this->errors, rtrim(str_replace(basename($item->path), '', $item->path), '/'));
201
  $upload_result = $uploader->upload();
@@ -283,7 +282,8 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
283
  'count' => (isset($chunks)) ? $chunks : 0,
284
  'local_paths' => (!empty($local_paths)) ? $local_paths : array(), // ftp import local copies of remote files
285
  'action' => (!empty($action_type) and $action_type == 'continue') ? 'continue' : 'update',
286
- 'nonce' => wp_create_nonce( 'import' )
 
287
  );
288
 
289
  foreach ($sesson_data as $key => $value) {
@@ -322,7 +322,10 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
322
 
323
  do_action('pmxi_before_import_delete', $item, $this->input->post('is_delete_posts'));
324
 
325
- $item->delete( ! $this->input->post('is_delete_posts'));
 
 
 
326
  wp_redirect(add_query_arg('pmxi_nt', urlencode(__('Import deleted', 'wp_all_import_plugin')), $this->baseUrl)); die();
327
  }
328
 
@@ -351,7 +354,7 @@ class PMXI_Admin_Manage extends PMXI_Controller_Admin {
351
  $item->delete( ! $is_delete_posts);
352
  }
353
 
354
- wp_redirect(add_query_arg('pmxi_nt', urlencode(sprintf(__('<strong>%d</strong> %s deleted', 'wp_all_import_plugin'), $items->count(), _n('import', 'imports', $items->count(), 'wp_all_import_plugin'))), $this->baseUrl)); die();
355
  }
356
 
357
  $this->render();
36
 
37
  if ( ! in_array($order, array('DESC', 'ASC'))){
38
  $order = 'DESC';
39
+ }
40
 
41
  $list = new PMXI_Import_List();
42
  $post = new PMXI_Post_Record();
62
  'total' => ceil($list->total() / $perPage),
63
  'current' => $pagenum,
64
  ));
65
+
 
66
  PMXI_Plugin::$session->clean_session();
67
 
68
  $this->render();
192
  $filePath = '';
193
 
194
  // upload new file in case when import is not continue
195
+ if ( empty(PMXI_Plugin::$session->chunk_number) ) {
196
+
197
+ if ( in_array($item->type, array('upload'))){ // retrieve already uploaded file
198
 
199
  $uploader = new PMXI_Upload(trim($item->path), $this->errors, rtrim(str_replace(basename($item->path), '', $item->path), '/'));
200
  $upload_result = $uploader->upload();
282
  'count' => (isset($chunks)) ? $chunks : 0,
283
  'local_paths' => (!empty($local_paths)) ? $local_paths : array(), // ftp import local copies of remote files
284
  'action' => (!empty($action_type) and $action_type == 'continue') ? 'continue' : 'update',
285
+ 'nonce' => wp_create_nonce( 'import' ),
286
+ 'deligate' => false
287
  );
288
 
289
  foreach ($sesson_data as $key => $value) {
322
 
323
  do_action('pmxi_before_import_delete', $item, $this->input->post('is_delete_posts'));
324
 
325
+ $is_deleted_images = $this->input->post('is_delete_images');
326
+ $is_delete_attachments = $this->input->post('is_delete_attachments');
327
+
328
+ $item->delete( ! $this->input->post('is_delete_posts'), $is_deleted_images, $is_delete_attachments);
329
  wp_redirect(add_query_arg('pmxi_nt', urlencode(__('Import deleted', 'wp_all_import_plugin')), $this->baseUrl)); die();
330
  }
331
 
354
  $item->delete( ! $is_delete_posts);
355
  }
356
 
357
+ wp_redirect(add_query_arg('pmxi_nt', urlencode(sprintf(__('%d %s deleted', 'wp_all_import_plugin'), $items->count(), _n('import', 'imports', $items->count(), 'wp_all_import_plugin'))), $this->baseUrl)); die();
358
  }
359
 
360
  $this->render();
controllers/admin/settings.php CHANGED
@@ -283,7 +283,7 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
283
  // Clean the fileName for security reasons
284
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
285
 
286
- if ( ! preg_match('%\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql)$%i', trim(basename($fileName)))) {
287
  exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV", "wp_all_import_plugin")), "id" => "id")));
288
  }
289
 
@@ -448,6 +448,8 @@ class PMXI_Admin_Settings extends PMXI_Controller_Admin {
448
  }
449
 
450
  unset($file);
 
 
451
 
452
  if ( ! $is_valid )
453
  {
283
  // Clean the fileName for security reasons
284
  $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
285
 
286
+ if ( ! preg_match('%\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($fileName)))) {
287
  exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV", "wp_all_import_plugin")), "id" => "id")));
288
  }
289
 
448
  }
449
 
450
  unset($file);
451
+
452
+ if ( ! preg_match('%\W(xml)$%i', trim($upload_result['source']['path']))) @unlink($upload_result['filePath']);
453
 
454
  if ( ! $is_valid )
455
  {
helpers/functions.php CHANGED
@@ -56,11 +56,8 @@
56
  if ( ! function_exists('pmxi_getExtensionFromStr')){
57
  function pmxi_getExtensionFromStr($str)
58
  {
59
- $i = strrpos($str,".");
60
- if ($i === false) return "";
61
- $l = strlen($str) - $i;
62
- $ext = substr($str,$i+1,$l);
63
- return (preg_match('%(jpg|jpeg|gif|png)$%i', $ext) and strlen($ext) <= 4) ? $ext : "";
64
  }
65
  }
66
 
56
  if ( ! function_exists('pmxi_getExtensionFromStr')){
57
  function pmxi_getExtensionFromStr($str)
58
  {
59
+ $filetype = wp_check_filetype($str);
60
+ return $filetype['ext'];
 
 
 
61
  }
62
  }
63
 
helpers/pmxi_findDuplicates.php CHANGED
@@ -18,6 +18,11 @@ function pmxi_findDuplicates($articleData, $custom_duplicate_name = '', $custom_
18
  'post_type' => $post_types,
19
  'post_status' => array('any'),
20
  'meta_query' => array(
 
 
 
 
 
21
  array(
22
  'key' => trim($custom_duplicate_name),
23
  'value' => htmlspecialchars(trim($custom_duplicate_value)),
18
  'post_type' => $post_types,
19
  'post_status' => array('any'),
20
  'meta_query' => array(
21
+ 'relation' => 'OR',
22
+ array(
23
+ 'key' => trim($custom_duplicate_name),
24
+ 'value' => trim($custom_duplicate_value),
25
+ ),
26
  array(
27
  'key' => trim($custom_duplicate_name),
28
  'value' => htmlspecialchars(trim($custom_duplicate_value)),
helpers/wp_all_import_get_parent_terms.php ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ function wp_all_import_get_parent_terms( $term_id, $taxonomy ){
3
+
4
+ $ids = array();
5
+
6
+ // start from the current term
7
+ $parent = get_term_by( 'id', $term_id, $taxonomy );
8
+
9
+ // climb up the hierarchy until we reach a term with parent = '0'
10
+ while ( $parent->parent != '0' ){
11
+
12
+ $term_id = $parent->parent;
13
+
14
+ $parent = get_term_by( 'id', $term_id, $taxonomy);
15
+
16
+ $ids[] = $parent->term_taxonomy_id;
17
+
18
+ }
19
+
20
+ return $ids;
21
+
22
+ }
helpers/wp_delete_attachments.php CHANGED
@@ -3,37 +3,50 @@
3
  * Delete attachments linked to a specified post
4
  * @param int $parent_id Parent id of post to delete attachments for
5
  */
6
- function wp_delete_attachments($parent_id, $unlink = true, $type = '') {
7
 
8
  if ( $type == 'images' and has_post_thumbnail($parent_id) ) delete_post_thumbnail($parent_id);
9
 
10
- foreach (get_posts(array('post_parent' => $parent_id, 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null)) as $attach) {
 
 
 
 
 
11
  if ($type == 'files' and ! wp_attachment_is_image( $attach->ID ) ){
12
- wp_delete_attachment($attach->ID, true);
 
 
 
 
 
 
 
 
13
  }
14
- elseif ( ($type == 'images' and wp_attachment_is_image( $attach->ID )) or "" == $type){
15
 
16
- if ($unlink or ! wp_attachment_is_image( $attach->ID )){
 
17
  wp_delete_attachment($attach->ID, true);
18
  }
19
- else{
20
-
21
- do_action( 'delete_attachment', $attach->ID );
22
- do_action( 'delete_post', $attach->ID );
 
 
23
 
24
- global $wpdb;
25
- $sql = "delete a,b,c
26
- FROM ".$wpdb->posts." a
27
- LEFT JOIN ".$wpdb->term_relationships." b ON ( a.ID = b.object_id )
28
- LEFT JOIN ".$wpdb->postmeta." c ON ( a.ID = c.post_id )
29
- LEFT JOIN ".$wpdb->posts." d ON ( a.ID = d.post_parent )
30
- WHERE a.ID = ".$attach->ID.";";
31
 
32
- $wpdb->query(
33
- $wpdb->prepare($sql, '')
34
- );
35
 
36
- }
37
- }
 
38
  }
39
  }
3
  * Delete attachments linked to a specified post
4
  * @param int $parent_id Parent id of post to delete attachments for
5
  */
6
+ function wp_delete_attachments($parent_id, $unlink = true, $type = 'images') {
7
 
8
  if ( $type == 'images' and has_post_thumbnail($parent_id) ) delete_post_thumbnail($parent_id);
9
 
10
+ $ids = array();
11
+
12
+ $attachments = get_posts(array('post_parent' => $parent_id, 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null));
13
+
14
+ foreach ($attachments as $attach) {
15
+
16
  if ($type == 'files' and ! wp_attachment_is_image( $attach->ID ) ){
17
+
18
+ if ($unlink)
19
+ {
20
+ wp_delete_attachment($attach->ID, true);
21
+ }
22
+ else
23
+ {
24
+ $ids[] = $attach->ID;
25
+ }
26
  }
27
+ elseif ($type == 'images' and wp_attachment_is_image( $attach->ID )) {
28
 
29
+ if ($unlink)
30
+ {
31
  wp_delete_attachment($attach->ID, true);
32
  }
33
+ else
34
+ {
35
+ $ids[] = $attach->ID;
36
+ }
37
+ }
38
+ }
39
 
40
+ global $wpdb;
41
+
42
+ if ( ! empty( $ids ) ) {
 
 
 
 
43
 
44
+ $ids_string = implode( ',', $ids );
45
+ // unattach
46
+ $result = $wpdb->query( "UPDATE $wpdb->posts SET post_parent = 0 WHERE post_type = 'attachment' AND ID IN ( $ids_string )" );
47
 
48
+ foreach ( $ids as $att_id ) {
49
+ clean_attachment_cache( $att_id );
50
+ }
51
  }
52
  }
libraries/PHPExcel.php ADDED
@@ -0,0 +1,1139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/');
32
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
33
+ }
34
+
35
+
36
+ /**
37
+ * PHPExcel
38
+ *
39
+ * @category PHPExcel
40
+ * @package PHPExcel
41
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
42
+ */
43
+ class PHPExcel
44
+ {
45
+ /**
46
+ * Unique ID
47
+ *
48
+ * @var string
49
+ */
50
+ private $_uniqueID;
51
+
52
+ /**
53
+ * Document properties
54
+ *
55
+ * @var PHPExcel_DocumentProperties
56
+ */
57
+ private $_properties;
58
+
59
+ /**
60
+ * Document security
61
+ *
62
+ * @var PHPExcel_DocumentSecurity
63
+ */
64
+ private $_security;
65
+
66
+ /**
67
+ * Collection of Worksheet objects
68
+ *
69
+ * @var PHPExcel_Worksheet[]
70
+ */
71
+ private $_workSheetCollection = array();
72
+
73
+ /**
74
+ * Calculation Engine
75
+ *
76
+ * @var PHPExcel_Calculation
77
+ */
78
+ private $_calculationEngine = NULL;
79
+
80
+ /**
81
+ * Active sheet index
82
+ *
83
+ * @var int
84
+ */
85
+ private $_activeSheetIndex = 0;
86
+
87
+ /**
88
+ * Named ranges
89
+ *
90
+ * @var PHPExcel_NamedRange[]
91
+ */
92
+ private $_namedRanges = array();
93
+
94
+ /**
95
+ * CellXf supervisor
96
+ *
97
+ * @var PHPExcel_Style
98
+ */
99
+ private $_cellXfSupervisor;
100
+
101
+ /**
102
+ * CellXf collection
103
+ *
104
+ * @var PHPExcel_Style[]
105
+ */
106
+ private $_cellXfCollection = array();
107
+
108
+ /**
109
+ * CellStyleXf collection
110
+ *
111
+ * @var PHPExcel_Style[]
112
+ */
113
+ private $_cellStyleXfCollection = array();
114
+
115
+ /**
116
+ * _hasMacros : this workbook have macros ?
117
+ *
118
+ * @var bool
119
+ */
120
+ private $_hasMacros = FALSE;
121
+
122
+ /**
123
+ * _macrosCode : all macros code (the vbaProject.bin file, this include form, code, etc.), NULL if no macro
124
+ *
125
+ * @var binary
126
+ */
127
+ private $_macrosCode=NULL;
128
+ /**
129
+ * _macrosCertificate : if macros are signed, contains vbaProjectSignature.bin file, NULL if not signed
130
+ *
131
+ * @var binary
132
+ */
133
+ private $_macrosCertificate=NULL;
134
+
135
+ /**
136
+ * _ribbonXMLData : NULL if workbook is'nt Excel 2007 or not contain a customized UI
137
+ *
138
+ * @var NULL|string
139
+ */
140
+ private $_ribbonXMLData=NULL;
141
+
142
+ /**
143
+ * _ribbonBinObjects : NULL if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
144
+ * ignored if $_ribbonXMLData is null
145
+ *
146
+ * @var NULL|array
147
+ */
148
+ private $_ribbonBinObjects=NULL;
149
+
150
+ /**
151
+ * The workbook has macros ?
152
+ *
153
+ * @return true if workbook has macros, false if not
154
+ */
155
+ public function hasMacros(){
156
+ return $this->_hasMacros;
157
+ }
158
+
159
+ /**
160
+ * Define if a workbook has macros
161
+ *
162
+ * @param true|false
163
+ */
164
+ public function setHasMacros($hasMacros=false){
165
+ $this->_hasMacros=(bool)$hasMacros;
166
+ }
167
+
168
+ /**
169
+ * Set the macros code
170
+ *
171
+ * @param binary string|null
172
+ */
173
+ public function setMacrosCode($MacrosCode){
174
+ $this->_macrosCode=$MacrosCode;
175
+ $this->setHasMacros(!is_null($MacrosCode));
176
+ }
177
+
178
+ /**
179
+ * Return the macros code
180
+ *
181
+ * @return binary|null
182
+ */
183
+ public function getMacrosCode(){
184
+ return $this->_macrosCode;
185
+ }
186
+
187
+ /**
188
+ * Set the macros certificate
189
+ *
190
+ * @param binary|null
191
+ */
192
+ public function setMacrosCertificate($Certificate=NULL){
193
+ $this->_macrosCertificate=$Certificate;
194
+ }
195
+
196
+ /**
197
+ * Is the project signed ?
198
+ *
199
+ * @return true|false
200
+ */
201
+ public function hasMacrosCertificate(){
202
+ return !is_null($this->_macrosCertificate);
203
+ }
204
+
205
+ /**
206
+ * Return the macros certificate
207
+ *
208
+ * @return binary|null
209
+ */
210
+ public function getMacrosCertificate(){
211
+ return $this->_macrosCertificate;
212
+ }
213
+
214
+ /**
215
+ * Remove all macros, certificate from spreadsheet
216
+ *
217
+ * @param none
218
+ * @return void
219
+ */
220
+ public function discardMacros(){
221
+ $this->_hasMacros=false;
222
+ $this->_macrosCode=NULL;
223
+ $this->_macrosCertificate=NULL;
224
+ }
225
+
226
+ /**
227
+ * set ribbon XML data
228
+ *
229
+ */
230
+ public function setRibbonXMLData($Target=NULL, $XMLData=NULL){
231
+ if(!is_null($Target) && !is_null($XMLData)){
232
+ $this->_ribbonXMLData=array('target'=>$Target, 'data'=>$XMLData);
233
+ }else{
234
+ $this->_ribbonXMLData=NULL;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * retrieve ribbon XML Data
240
+ *
241
+ * return string|null|array
242
+ */
243
+ public function getRibbonXMLData($What='all'){//we need some constants here...
244
+ $ReturnData=NULL;
245
+ $What=strtolower($What);
246
+ switch($What){
247
+ case 'all':
248
+ $ReturnData=$this->_ribbonXMLData;
249
+ break;
250
+ case 'target':
251
+ case 'data':
252
+ if(is_array($this->_ribbonXMLData) && array_key_exists($What,$this->_ribbonXMLData)){
253
+ $ReturnData=$this->_ribbonXMLData[$What];
254
+ }//else $ReturnData stay at null
255
+ break;
256
+ }//default: $ReturnData at null
257
+ return $ReturnData;
258
+ }
259
+
260
+ /**
261
+ * store binaries ribbon objects (pictures)
262
+ *
263
+ */
264
+ public function setRibbonBinObjects($BinObjectsNames=NULL, $BinObjectsData=NULL){
265
+ if(!is_null($BinObjectsNames) && !is_null($BinObjectsData)){
266
+ $this->_ribbonBinObjects=array('names'=>$BinObjectsNames, 'data'=>$BinObjectsData);
267
+ }else{
268
+ $this->_ribbonBinObjects=NULL;
269
+ }
270
+ }
271
+ /**
272
+ * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function)
273
+ *
274
+ */
275
+ private function _getExtensionOnly($ThePath){
276
+ return pathinfo($ThePath, PATHINFO_EXTENSION);
277
+ }
278
+
279
+ /**
280
+ * retrieve Binaries Ribbon Objects
281
+ *
282
+ */
283
+ public function getRibbonBinObjects($What='all'){
284
+ $ReturnData=NULL;
285
+ $What=strtolower($What);
286
+ switch($What){
287
+ case 'all':
288
+ return $this->_ribbonBinObjects;
289
+ break;
290
+ case 'names':
291
+ case 'data':
292
+ if(is_array($this->_ribbonBinObjects) && array_key_exists($What, $this->_ribbonBinObjects)){
293
+ $ReturnData=$this->_ribbonBinObjects[$What];
294
+ }
295
+ break;
296
+ case 'types':
297
+ if(is_array($this->_ribbonBinObjects) && array_key_exists('data', $this->_ribbonBinObjects) && is_array($this->_ribbonBinObjects['data'])){
298
+ $tmpTypes=array_keys($this->_ribbonBinObjects['data']);
299
+ $ReturnData=array_unique(array_map(array($this,'_getExtensionOnly'), $tmpTypes));
300
+ }else
301
+ $ReturnData=array();//the caller want an array... not null if empty
302
+ break;
303
+ }
304
+ return $ReturnData;
305
+ }
306
+
307
+ /**
308
+ * This workbook have a custom UI ?
309
+ *
310
+ * @return true|false
311
+ */
312
+ public function hasRibbon(){
313
+ return !is_null($this->_ribbonXMLData);
314
+ }
315
+
316
+ /**
317
+ * This workbook have additionnal object for the ribbon ?
318
+ *
319
+ * @return true|false
320
+ */
321
+ public function hasRibbonBinObjects(){
322
+ return !is_null($this->_ribbonBinObjects);
323
+ }
324
+
325
+ /**
326
+ * Check if a sheet with a specified code name already exists
327
+ *
328
+ * @param string $pSheetCodeName Name of the worksheet to check
329
+ * @return boolean
330
+ */
331
+ public function sheetCodeNameExists($pSheetCodeName)
332
+ {
333
+ return ($this->getSheetByCodeName($pSheetCodeName) !== NULL);
334
+ }
335
+
336
+ /**
337
+ * Get sheet by code name. Warning : sheet don't have always a code name !
338
+ *
339
+ * @param string $pName Sheet name
340
+ * @return PHPExcel_Worksheet
341
+ */
342
+ public function getSheetByCodeName($pName = '')
343
+ {
344
+ $worksheetCount = count($this->_workSheetCollection);
345
+ for ($i = 0; $i < $worksheetCount; ++$i) {
346
+ if ($this->_workSheetCollection[$i]->getCodeName() == $pName) {
347
+ return $this->_workSheetCollection[$i];
348
+ }
349
+ }
350
+
351
+ return null;
352
+ }
353
+
354
+ /**
355
+ * Create a new PHPExcel with one Worksheet
356
+ */
357
+ public function __construct()
358
+ {
359
+ $this->_uniqueID = uniqid();
360
+ $this->_calculationEngine = PHPExcel_Calculation::getInstance($this);
361
+
362
+ // Initialise worksheet collection and add one worksheet
363
+ $this->_workSheetCollection = array();
364
+ $this->_workSheetCollection[] = new PHPExcel_Worksheet($this);
365
+ $this->_activeSheetIndex = 0;
366
+
367
+ // Create document properties
368
+ $this->_properties = new PHPExcel_DocumentProperties();
369
+
370
+ // Create document security
371
+ $this->_security = new PHPExcel_DocumentSecurity();
372
+
373
+ // Set named ranges
374
+ $this->_namedRanges = array();
375
+
376
+ // Create the cellXf supervisor
377
+ $this->_cellXfSupervisor = new PHPExcel_Style(true);
378
+ $this->_cellXfSupervisor->bindParent($this);
379
+
380
+ // Create the default style
381
+ $this->addCellXf(new PHPExcel_Style);
382
+ $this->addCellStyleXf(new PHPExcel_Style);
383
+ }
384
+
385
+ /**
386
+ * Code to execute when this worksheet is unset()
387
+ *
388
+ */
389
+ public function __destruct() {
390
+ PHPExcel_Calculation::unsetInstance($this);
391
+ $this->disconnectWorksheets();
392
+ } // function __destruct()
393
+
394
+ /**
395
+ * Disconnect all worksheets from this PHPExcel workbook object,
396
+ * typically so that the PHPExcel object can be unset
397
+ *
398
+ */
399
+ public function disconnectWorksheets()
400
+ {
401
+ $worksheet = NULL;
402
+ foreach($this->_workSheetCollection as $k => &$worksheet) {
403
+ $worksheet->disconnectCells();
404
+ $this->_workSheetCollection[$k] = null;
405
+ }
406
+ unset($worksheet);
407
+ $this->_workSheetCollection = array();
408
+ }
409
+
410
+ /**
411
+ * Return the calculation engine for this worksheet
412
+ *
413
+ * @return PHPExcel_Calculation
414
+ */
415
+ public function getCalculationEngine()
416
+ {
417
+ return $this->_calculationEngine;
418
+ } // function getCellCacheController()
419
+
420
+ /**
421
+ * Get properties
422
+ *
423
+ * @return PHPExcel_DocumentProperties
424
+ */
425
+ public function getProperties()
426
+ {
427
+ return $this->_properties;
428
+ }
429
+
430
+ /**
431
+ * Set properties
432
+ *
433
+ * @param PHPExcel_DocumentProperties $pValue
434
+ */
435
+ public function setProperties(PHPExcel_DocumentProperties $pValue)
436
+ {
437
+ $this->_properties = $pValue;
438
+ }
439
+
440
+ /**
441
+ * Get security
442
+ *
443
+ * @return PHPExcel_DocumentSecurity
444
+ */
445
+ public function getSecurity()
446
+ {
447
+ return $this->_security;
448
+ }
449
+
450
+ /**
451
+ * Set security
452
+ *
453
+ * @param PHPExcel_DocumentSecurity $pValue
454
+ */
455
+ public function setSecurity(PHPExcel_DocumentSecurity $pValue)
456
+ {
457
+ $this->_security = $pValue;
458
+ }
459
+
460
+ /**
461
+ * Get active sheet
462
+ *
463
+ * @return PHPExcel_Worksheet
464
+ *
465
+ * @throws PHPExcel_Exception
466
+ */
467
+ public function getActiveSheet()
468
+ {
469
+ return $this->getSheet($this->_activeSheetIndex);
470
+ }
471
+
472
+ /**
473
+ * Create sheet and add it to this workbook
474
+ *
475
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
476
+ * @return PHPExcel_Worksheet
477
+ * @throws PHPExcel_Exception
478
+ */
479
+ public function createSheet($iSheetIndex = NULL)
480
+ {
481
+ $newSheet = new PHPExcel_Worksheet($this);
482
+ $this->addSheet($newSheet, $iSheetIndex);
483
+ return $newSheet;
484
+ }
485
+
486
+ /**
487
+ * Check if a sheet with a specified name already exists
488
+ *
489
+ * @param string $pSheetName Name of the worksheet to check
490
+ * @return boolean
491
+ */
492
+ public function sheetNameExists($pSheetName)
493
+ {
494
+ return ($this->getSheetByName($pSheetName) !== NULL);
495
+ }
496
+
497
+ /**
498
+ * Add sheet
499
+ *
500
+ * @param PHPExcel_Worksheet $pSheet
501
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
502
+ * @return PHPExcel_Worksheet
503
+ * @throws PHPExcel_Exception
504
+ */
505
+ public function addSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = NULL)
506
+ {
507
+ if ($this->sheetNameExists($pSheet->getTitle())) {
508
+ throw new PHPExcel_Exception(
509
+ "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first."
510
+ );
511
+ }
512
+
513
+ if($iSheetIndex === NULL) {
514
+ if ($this->_activeSheetIndex < 0) {
515
+ $this->_activeSheetIndex = 0;
516
+ }
517
+ $this->_workSheetCollection[] = $pSheet;
518
+ } else {
519
+ // Insert the sheet at the requested index
520
+ array_splice(
521
+ $this->_workSheetCollection,
522
+ $iSheetIndex,
523
+ 0,
524
+ array($pSheet)
525
+ );
526
+
527
+ // Adjust active sheet index if necessary
528
+ if ($this->_activeSheetIndex >= $iSheetIndex) {
529
+ ++$this->_activeSheetIndex;
530
+ }
531
+ }
532
+
533
+ if ($pSheet->getParent() === null) {
534
+ $pSheet->rebindParent($this);
535
+ }
536
+
537
+ return $pSheet;
538
+ }
539
+
540
+ /**
541
+ * Remove sheet by index
542
+ *
543
+ * @param int $pIndex Active sheet index
544
+ * @throws PHPExcel_Exception
545
+ */
546
+ public function removeSheetByIndex($pIndex = 0)
547
+ {
548
+
549
+ $numSheets = count($this->_workSheetCollection);
550
+
551
+ if ($pIndex > $numSheets - 1) {
552
+ throw new PHPExcel_Exception(
553
+ "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
554
+ );
555
+ } else {
556
+ array_splice($this->_workSheetCollection, $pIndex, 1);
557
+ }
558
+ // Adjust active sheet index if necessary
559
+ if (($this->_activeSheetIndex >= $pIndex) &&
560
+ ($pIndex > count($this->_workSheetCollection) - 1)) {
561
+ --$this->_activeSheetIndex;
562
+ }
563
+
564
+ }
565
+
566
+ /**
567
+ * Get sheet by index
568
+ *
569
+ * @param int $pIndex Sheet index
570
+ * @return PHPExcel_Worksheet
571
+ * @throws PHPExcel_Exception
572
+ */
573
+ public function getSheet($pIndex = 0)
574
+ {
575
+ if (!isset($this->_workSheetCollection[$pIndex])) {
576
+ $numSheets = $this->getSheetCount();
577
+ throw new PHPExcel_Exception(
578
+ "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}."
579
+ );
580
+ }
581
+
582
+ return $this->_workSheetCollection[$pIndex];
583
+ }
584
+
585
+ /**
586
+ * Get all sheets
587
+ *
588
+ * @return PHPExcel_Worksheet[]
589
+ */
590
+ public function getAllSheets()
591
+ {
592
+ return $this->_workSheetCollection;
593
+ }
594
+
595
+ /**
596
+ * Get sheet by name
597
+ *
598
+ * @param string $pName Sheet name
599
+ * @return PHPExcel_Worksheet
600
+ */
601
+ public function getSheetByName($pName = '')
602
+ {
603
+ $worksheetCount = count($this->_workSheetCollection);
604
+ for ($i = 0; $i < $worksheetCount; ++$i) {
605
+ if ($this->_workSheetCollection[$i]->getTitle() === $pName) {
606
+ return $this->_workSheetCollection[$i];
607
+ }
608
+ }
609
+
610
+ return NULL;
611
+ }
612
+
613
+ /**
614
+ * Get index for sheet
615
+ *
616
+ * @param PHPExcel_Worksheet $pSheet
617
+ * @return Sheet index
618
+ * @throws PHPExcel_Exception
619
+ */
620
+ public function getIndex(PHPExcel_Worksheet $pSheet)
621
+ {
622
+ foreach ($this->_workSheetCollection as $key => $value) {
623
+ if ($value->getHashCode() == $pSheet->getHashCode()) {
624
+ return $key;
625
+ }
626
+ }
627
+
628
+ throw new PHPExcel_Exception("Sheet does not exist.");
629
+ }
630
+
631
+ /**
632
+ * Set index for sheet by sheet name.
633
+ *
634
+ * @param string $sheetName Sheet name to modify index for
635
+ * @param int $newIndex New index for the sheet
636
+ * @return New sheet index
637
+ * @throws PHPExcel_Exception
638
+ */
639
+ public function setIndexByName($sheetName, $newIndex)
640
+ {
641
+ $oldIndex = $this->getIndex($this->getSheetByName($sheetName));
642
+ $pSheet = array_splice(
643
+ $this->_workSheetCollection,
644
+ $oldIndex,
645
+ 1
646
+ );
647
+ array_splice(
648
+ $this->_workSheetCollection,
649
+ $newIndex,
650
+ 0,
651
+ $pSheet
652
+ );
653
+ return $newIndex;
654
+ }
655
+
656
+ /**
657
+ * Get sheet count
658
+ *
659
+ * @return int
660
+ */
661
+ public function getSheetCount()
662
+ {
663
+ return count($this->_workSheetCollection);
664
+ }
665
+
666
+ /**
667
+ * Get active sheet index
668
+ *
669
+ * @return int Active sheet index
670
+ */
671
+ public function getActiveSheetIndex()
672
+ {
673
+ return $this->_activeSheetIndex;
674
+ }
675
+
676
+ /**
677
+ * Set active sheet index
678
+ *
679
+ * @param int $pIndex Active sheet index
680
+ * @throws PHPExcel_Exception
681
+ * @return PHPExcel_Worksheet
682
+ */
683
+ public function setActiveSheetIndex($pIndex = 0)
684
+ {
685
+ $numSheets = count($this->_workSheetCollection);
686
+
687
+ if ($pIndex > $numSheets - 1) {
688
+ throw new PHPExcel_Exception(
689
+ "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
690
+ );
691
+ } else {
692
+ $this->_activeSheetIndex = $pIndex;
693
+ }
694
+ return $this->getActiveSheet();
695
+ }
696
+
697
+ /**
698
+ * Set active sheet index by name
699
+ *
700
+ * @param string $pValue Sheet title
701
+ * @return PHPExcel_Worksheet
702
+ * @throws PHPExcel_Exception
703
+ */
704
+ public function setActiveSheetIndexByName($pValue = '')
705
+ {
706
+ if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) {
707
+ $this->setActiveSheetIndex($this->getIndex($worksheet));
708
+ return $worksheet;
709
+ }
710
+
711
+ throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue);
712
+ }
713
+
714
+ /**
715
+ * Get sheet names
716
+ *
717
+ * @return string[]
718
+ */
719
+ public function getSheetNames()
720
+ {
721
+ $returnValue = array();
722
+ $worksheetCount = $this->getSheetCount();
723
+ for ($i = 0; $i < $worksheetCount; ++$i) {
724
+ $returnValue[] = $this->getSheet($i)->getTitle();
725
+ }
726
+
727
+ return $returnValue;
728
+ }
729
+
730
+ /**
731
+ * Add external sheet
732
+ *
733
+ * @param PHPExcel_Worksheet $pSheet External sheet to add
734
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
735
+ * @throws PHPExcel_Exception
736
+ * @return PHPExcel_Worksheet
737
+ */
738
+ public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) {
739
+ if ($this->sheetNameExists($pSheet->getTitle())) {
740
+ throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.");
741
+ }
742
+
743
+ // count how many cellXfs there are in this workbook currently, we will need this below
744
+ $countCellXfs = count($this->_cellXfCollection);
745
+
746
+ // copy all the shared cellXfs from the external workbook and append them to the current
747
+ foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) {
748
+ $this->addCellXf(clone $cellXf);
749
+ }
750
+
751
+ // move sheet to this workbook
752
+ $pSheet->rebindParent($this);
753
+
754
+ // update the cellXfs
755
+ foreach ($pSheet->getCellCollection(false) as $cellID) {
756
+ $cell = $pSheet->getCell($cellID);
757
+ $cell->setXfIndex( $cell->getXfIndex() + $countCellXfs );
758
+ }
759
+
760
+ return $this->addSheet($pSheet, $iSheetIndex);
761
+ }
762
+
763
+ /**
764
+ * Get named ranges
765
+ *
766
+ * @return PHPExcel_NamedRange[]
767
+ */
768
+ public function getNamedRanges() {
769
+ return $this->_namedRanges;
770
+ }
771
+
772
+ /**
773
+ * Add named range
774
+ *
775
+ * @param PHPExcel_NamedRange $namedRange
776
+ * @return PHPExcel
777
+ */
778
+ public function addNamedRange(PHPExcel_NamedRange $namedRange) {
779
+ if ($namedRange->getScope() == null) {
780
+ // global scope
781
+ $this->_namedRanges[$namedRange->getName()] = $namedRange;
782
+ } else {
783
+ // local scope
784
+ $this->_namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange;
785
+ }
786
+ return true;
787
+ }
788
+
789
+ /**
790
+ * Get named range
791
+ *
792
+ * @param string $namedRange
793
+ * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope
794
+ * @return PHPExcel_NamedRange|null
795
+ */
796
+ public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) {
797
+ $returnValue = null;
798
+
799
+ if ($namedRange != '' && ($namedRange !== NULL)) {
800
+ // first look for global defined name
801
+ if (isset($this->_namedRanges[$namedRange])) {
802
+ $returnValue = $this->_namedRanges[$namedRange];
803
+ }
804
+
805
+ // then look for local defined name (has priority over global defined name if both names exist)
806
+ if (($pSheet !== NULL) && isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
807
+ $returnValue = $this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange];
808
+ }
809
+ }
810
+
811
+ return $returnValue;
812
+ }
813
+
814
+ /**
815
+ * Remove named range
816
+ *
817
+ * @param string $namedRange
818
+ * @param PHPExcel_Worksheet|null $pSheet Scope: use null for global scope.
819
+ * @return PHPExcel
820
+ */
821
+ public function removeNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) {
822
+ if ($pSheet === NULL) {
823
+ if (isset($this->_namedRanges[$namedRange])) {
824
+ unset($this->_namedRanges[$namedRange]);
825
+ }
826
+ } else {
827
+ if (isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
828
+ unset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange]);
829
+ }
830
+ }
831
+ return $this;
832
+ }
833
+
834
+ /**
835
+ * Get worksheet iterator
836
+ *
837
+ * @return PHPExcel_WorksheetIterator
838
+ */
839
+ public function getWorksheetIterator() {
840
+ return new PHPExcel_WorksheetIterator($this);
841
+ }
842
+
843
+ /**
844
+ * Copy workbook (!= clone!)
845
+ *
846
+ * @return PHPExcel
847
+ */
848
+ public function copy() {
849
+ $copied = clone $this;
850
+
851
+ $worksheetCount = count($this->_workSheetCollection);
852
+ for ($i = 0; $i < $worksheetCount; ++$i) {
853
+ $this->_workSheetCollection[$i] = $this->_workSheetCollection[$i]->copy();
854
+ $this->_workSheetCollection[$i]->rebindParent($this);
855
+ }
856
+
857
+ return $copied;
858
+ }
859
+
860
+ /**
861
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
862
+ */
863
+ public function __clone() {
864
+ foreach($this as $key => $val) {
865
+ if (is_object($val) || (is_array($val))) {
866
+ $this->{$key} = unserialize(serialize($val));
867
+ }
868
+ }
869
+ }
870
+
871
+ /**
872
+ * Get the workbook collection of cellXfs
873
+ *
874
+ * @return PHPExcel_Style[]
875
+ */
876
+ public function getCellXfCollection()
877
+ {
878
+ return $this->_cellXfCollection;
879
+ }
880
+
881
+ /**
882
+ * Get cellXf by index
883
+ *
884
+ * @param int $pIndex
885
+ * @return PHPExcel_Style
886
+ */
887
+ public function getCellXfByIndex($pIndex = 0)
888
+ {
889
+ return $this->_cellXfCollection[$pIndex];
890
+ }
891
+
892
+ /**
893
+ * Get cellXf by hash code
894
+ *
895
+ * @param string $pValue
896
+ * @return PHPExcel_Style|false
897
+ */
898
+ public function getCellXfByHashCode($pValue = '')
899
+ {
900
+ foreach ($this->_cellXfCollection as $cellXf) {
901
+ if ($cellXf->getHashCode() == $pValue) {
902
+ return $cellXf;
903
+ }
904
+ }
905
+ return false;
906
+ }
907
+
908
+ /**
909
+ * Check if style exists in style collection
910
+ *
911
+ * @param PHPExcel_Style $pCellStyle
912
+ * @return boolean
913
+ */
914
+ public function cellXfExists($pCellStyle = null)
915
+ {
916
+ return in_array($pCellStyle, $this->_cellXfCollection, true);
917
+ }
918
+
919
+ /**
920
+ * Get default style
921
+ *
922
+ * @return PHPExcel_Style
923
+ * @throws PHPExcel_Exception
924
+ */
925
+ public function getDefaultStyle()
926
+ {
927
+ if (isset($this->_cellXfCollection[0])) {
928
+ return $this->_cellXfCollection[0];
929
+ }
930
+ throw new PHPExcel_Exception('No default style found for this workbook');
931
+ }
932
+
933
+ /**
934
+ * Add a cellXf to the workbook
935
+ *
936
+ * @param PHPExcel_Style $style
937
+ */
938
+ public function addCellXf(PHPExcel_Style $style)
939
+ {
940
+ $this->_cellXfCollection[] = $style;
941
+ $style->setIndex(count($this->_cellXfCollection) - 1);
942
+ }
943
+
944
+ /**
945
+ * Remove cellXf by index. It is ensured that all cells get their xf index updated.
946
+ *
947
+ * @param int $pIndex Index to cellXf
948
+ * @throws PHPExcel_Exception
949
+ */
950
+ public function removeCellXfByIndex($pIndex = 0)
951
+ {
952
+ if ($pIndex > count($this->_cellXfCollection) - 1) {
953
+ throw new PHPExcel_Exception("CellXf index is out of bounds.");
954
+ } else {
955
+ // first remove the cellXf
956
+ array_splice($this->_cellXfCollection, $pIndex, 1);
957
+
958
+ // then update cellXf indexes for cells
959
+ foreach ($this->_workSheetCollection as $worksheet) {
960
+ foreach ($worksheet->getCellCollection(false) as $cellID) {
961
+ $cell = $worksheet->getCell($cellID);
962
+ $xfIndex = $cell->getXfIndex();
963
+ if ($xfIndex > $pIndex ) {
964
+ // decrease xf index by 1
965
+ $cell->setXfIndex($xfIndex - 1);
966
+ } else if ($xfIndex == $pIndex) {
967
+ // set to default xf index 0
968
+ $cell->setXfIndex(0);
969
+ }
970
+ }
971
+ }
972
+ }
973
+ }
974
+
975
+ /**
976
+ * Get the cellXf supervisor
977
+ *
978
+ * @return PHPExcel_Style
979
+ */
980
+ public function getCellXfSupervisor()
981
+ {
982
+ return $this->_cellXfSupervisor;
983
+ }
984
+
985
+ /**
986
+ * Get the workbook collection of cellStyleXfs
987
+ *
988
+ * @return PHPExcel_Style[]
989
+ */
990
+ public function getCellStyleXfCollection()
991
+ {
992
+ return $this->_cellStyleXfCollection;
993
+ }
994
+
995
+ /**
996
+ * Get cellStyleXf by index
997
+ *
998
+ * @param int $pIndex
999
+ * @return PHPExcel_Style
1000
+ */
1001
+ public function getCellStyleXfByIndex($pIndex = 0)
1002
+ {
1003
+ return $this->_cellStyleXfCollection[$pIndex];
1004
+ }
1005
+
1006
+ /**
1007
+ * Get cellStyleXf by hash code
1008
+ *
1009
+ * @param string $pValue
1010
+ * @return PHPExcel_Style|false
1011
+ */
1012
+ public function getCellStyleXfByHashCode($pValue = '')
1013
+ {
1014
+ foreach ($this->_cellStyleXfCollection as $cellStyleXf) {
1015
+ if ($cellStyleXf->getHashCode() == $pValue) {
1016
+ return $cellStyleXf;
1017
+ }
1018
+ }
1019
+ return false;
1020
+ }
1021
+
1022
+ /**
1023
+ * Add a cellStyleXf to the workbook
1024
+ *
1025
+ * @param PHPExcel_Style $pStyle
1026
+ */
1027
+ public function addCellStyleXf(PHPExcel_Style $pStyle)
1028
+ {
1029
+ $this->_cellStyleXfCollection[] = $pStyle;
1030
+ $pStyle->setIndex(count($this->_cellStyleXfCollection) - 1);
1031
+ }
1032
+
1033
+ /**
1034
+ * Remove cellStyleXf by index
1035
+ *
1036
+ * @param int $pIndex
1037
+ * @throws PHPExcel_Exception
1038
+ */
1039
+ public function removeCellStyleXfByIndex($pIndex = 0)
1040
+ {
1041
+ if ($pIndex > count($this->_cellStyleXfCollection) - 1) {
1042
+ throw new PHPExcel_Exception("CellStyleXf index is out of bounds.");
1043
+ } else {
1044
+ array_splice($this->_cellStyleXfCollection, $pIndex, 1);
1045
+ }
1046
+ }
1047
+
1048
+ /**
1049
+ * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1050
+ * and columns in the workbook
1051
+ */
1052
+ public function garbageCollect()
1053
+ {
1054
+ // how many references are there to each cellXf ?
1055
+ $countReferencesCellXf = array();
1056
+ foreach ($this->_cellXfCollection as $index => $cellXf) {
1057
+ $countReferencesCellXf[$index] = 0;
1058
+ }
1059
+
1060
+ foreach ($this->getWorksheetIterator() as $sheet) {
1061
+
1062
+ // from cells
1063
+ foreach ($sheet->getCellCollection(false) as $cellID) {
1064
+ $cell = $sheet->getCell($cellID);
1065
+ ++$countReferencesCellXf[$cell->getXfIndex()];
1066
+ }
1067
+
1068
+ // from row dimensions
1069
+ foreach ($sheet->getRowDimensions() as $rowDimension) {
1070
+ if ($rowDimension->getXfIndex() !== null) {
1071
+ ++$countReferencesCellXf[$rowDimension->getXfIndex()];
1072
+ }
1073
+ }
1074
+
1075
+ // from column dimensions
1076
+ foreach ($sheet->getColumnDimensions() as $columnDimension) {
1077
+ ++$countReferencesCellXf[$columnDimension->getXfIndex()];
1078
+ }
1079
+ }
1080
+
1081
+ // remove cellXfs without references and create mapping so we can update xfIndex
1082
+ // for all cells and columns
1083
+ $countNeededCellXfs = 0;
1084
+ foreach ($this->_cellXfCollection as $index => $cellXf) {
1085
+ if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1086
+ ++$countNeededCellXfs;
1087
+ } else {
1088
+ unset($this->_cellXfCollection[$index]);
1089
+ }
1090
+ $map[$index] = $countNeededCellXfs - 1;
1091
+ }
1092
+ $this->_cellXfCollection = array_values($this->_cellXfCollection);
1093
+
1094
+ // update the index for all cellXfs
1095
+ foreach ($this->_cellXfCollection as $i => $cellXf) {
1096
+ $cellXf->setIndex($i);
1097
+ }
1098
+
1099
+ // make sure there is always at least one cellXf (there should be)
1100
+ if (empty($this->_cellXfCollection)) {
1101
+ $this->_cellXfCollection[] = new PHPExcel_Style();
1102
+ }
1103
+
1104
+ // update the xfIndex for all cells, row dimensions, column dimensions
1105
+ foreach ($this->getWorksheetIterator() as $sheet) {
1106
+
1107
+ // for all cells
1108
+ foreach ($sheet->getCellCollection(false) as $cellID) {
1109
+ $cell = $sheet->getCell($cellID);
1110
+ $cell->setXfIndex( $map[$cell->getXfIndex()] );
1111
+ }
1112
+
1113
+ // for all row dimensions
1114
+ foreach ($sheet->getRowDimensions() as $rowDimension) {
1115
+ if ($rowDimension->getXfIndex() !== null) {
1116
+ $rowDimension->setXfIndex( $map[$rowDimension->getXfIndex()] );
1117
+ }
1118
+ }
1119
+
1120
+ // for all column dimensions
1121
+ foreach ($sheet->getColumnDimensions() as $columnDimension) {
1122
+ $columnDimension->setXfIndex( $map[$columnDimension->getXfIndex()] );
1123
+ }
1124
+
1125
+ // also do garbage collection for all the sheets
1126
+ $sheet->garbageCollect();
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * Return the unique ID value assigned to this spreadsheet workbook
1132
+ *
1133
+ * @return string
1134
+ */
1135
+ public function getID() {
1136
+ return $this->_uniqueID;
1137
+ }
1138
+
1139
+ }
libraries/PHPExcel/Autoloader.php ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+ PHPExcel_Autoloader::Register();
29
+ // As we always try to run the autoloader before anything else, we can use it to do a few
30
+ // simple checks and initialisations
31
+ //PHPExcel_Shared_ZipStreamWrapper::register();
32
+ // check mbstring.func_overload
33
+ if (ini_get('mbstring.func_overload') & 2) {
34
+ throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
35
+ }
36
+ PHPExcel_Shared_String::buildCharacterSets();
37
+
38
+
39
+ /**
40
+ * PHPExcel_Autoloader
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Autoloader
47
+ {
48
+ /**
49
+ * Register the Autoloader with SPL
50
+ *
51
+ */
52
+ public static function Register() {
53
+ if (function_exists('__autoload')) {
54
+ // Register any existing autoloader function with SPL, so we don't get any clashes
55
+ spl_autoload_register('__autoload');
56
+ }
57
+ // Register ourselves with SPL
58
+ if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
59
+ return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'), true, true);
60
+ } else {
61
+ return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));
62
+ }
63
+ } // function Register()
64
+
65
+
66
+ /**
67
+ * Autoload a class identified by name
68
+ *
69
+ * @param string $pClassName Name of the object to load
70
+ */
71
+ public static function Load($pClassName){
72
+ if ((class_exists($pClassName,FALSE)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
73
+ // Either already loaded, or not a PHPExcel class request
74
+ return FALSE;
75
+ }
76
+
77
+ $pClassFilePath = PHPEXCEL_ROOT .
78
+ str_replace('_',DIRECTORY_SEPARATOR,$pClassName) .
79
+ '.php';
80
+
81
+ if ((file_exists($pClassFilePath) === FALSE) || (is_readable($pClassFilePath) === FALSE)) {
82
+ // Can't load
83
+ return FALSE;
84
+ }
85
+
86
+ require($pClassFilePath);
87
+ } // function Load()
88
+
89
+ }
libraries/PHPExcel/CachedObjectStorage/APC.php ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_APC
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_APC extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Prefix used to uniquely identify cache data for this worksheet
40
+ *
41
+ * @access private
42
+ * @var string
43
+ */
44
+ private $_cachePrefix = null;
45
+
46
+ /**
47
+ * Cache timeout
48
+ *
49
+ * @access private
50
+ * @var integer
51
+ */
52
+ private $_cacheTime = 600;
53
+
54
+
55
+ /**
56
+ * Store cell data in cache for the current cell object if it's "dirty",
57
+ * and the 'nullify' the current cell object
58
+ *
59
+ * @access private
60
+ * @return void
61
+ * @throws PHPExcel_Exception
62
+ */
63
+ protected function _storeData() {
64
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
65
+ $this->_currentObject->detach();
66
+
67
+ if (!apc_store($this->_cachePrefix.$this->_currentObjectID.'.cache',serialize($this->_currentObject),$this->_cacheTime)) {
68
+ $this->__destruct();
69
+ throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in APC');
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
+ * @access public
81
+ * @param string $pCoord Coordinate address of the cell to update
82
+ * @param PHPExcel_Cell $cell Cell to update
83
+ * @return PHPExcel_Cell
84
+ * @throws PHPExcel_Exception
85
+ */
86
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
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
+ * @access public
104
+ * @param string $pCoord Coordinate address of the cell to check
105
+ * @throws PHPExcel_Exception
106
+ * @return boolean
107
+ */
108
+ public function isDataSet($pCoord) {
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 apc
115
+ $success = apc_fetch($this->_cachePrefix.$pCoord.'.cache');
116
+ if ($success === FALSE) {
117
+ // Entry no longer exists in APC, so clear it from the cache array
118
+ parent::deleteCacheData($pCoord);
119
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
120
+ }
121
+ return true;
122
+ }
123
+ return false;
124
+ } // function isDataSet()
125
+
126
+
127
+ /**
128
+ * Get cell at a specific coordinate
129
+ *
130
+ * @access public
131
+ * @param string $pCoord Coordinate of the cell
132
+ * @throws PHPExcel_Exception
133
+ * @return PHPExcel_Cell Cell that was found, or null if not found
134
+ */
135
+ public function getCacheData($pCoord) {
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 = apc_fetch($this->_cachePrefix.$pCoord.'.cache');
144
+ if ($obj === FALSE) {
145
+ // Entry no longer exists in APC, so clear it from the cache array
146
+ parent::deleteCacheData($pCoord);
147
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
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
+ } // function getCacheData()
163
+
164
+
165
+ /**
166
+ * Get a list of all cell addresses currently held in cache
167
+ *
168
+ * @return string[]
169
+ */
170
+ public function getCellList() {
171
+ if ($this->_currentObjectID !== null) {
172
+ $this->_storeData();
173
+ }
174
+
175
+ return parent::getCellList();
176
+ }
177
+
178
+
179
+ /**
180
+ * Delete a cell in cache identified by coordinate address
181
+ *
182
+ * @access public
183
+ * @param string $pCoord Coordinate address of the cell to delete
184
+ * @throws PHPExcel_Exception
185
+ */
186
+ public function deleteCacheData($pCoord) {
187
+ // Delete the entry from APC
188
+ apc_delete($this->_cachePrefix.$pCoord.'.cache');
189
+
190
+ // Delete the entry from our cell address array
191
+ parent::deleteCacheData($pCoord);
192
+ } // function deleteCacheData()
193
+
194
+
195
+ /**
196
+ * Clone the cell collection
197
+ *
198
+ * @access public
199
+ * @param PHPExcel_Worksheet $parent The new worksheet
200
+ * @throws PHPExcel_Exception
201
+ * @return void
202
+ */
203
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
204
+ parent::copyCellCollection($parent);
205
+ // Get a new id for the new file name
206
+ $baseUnique = $this->_getUniqueID();
207
+ $newCachePrefix = substr(md5($baseUnique),0,8).'.';
208
+ $cacheList = $this->getCellList();
209
+ foreach($cacheList as $cellID) {
210
+ if ($cellID != $this->_currentObjectID) {
211
+ $obj = apc_fetch($this->_cachePrefix.$cellID.'.cache');
212
+ if ($obj === FALSE) {
213
+ // Entry no longer exists in APC, so clear it from the cache array
214
+ parent::deleteCacheData($cellID);
215
+ throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in APC');
216
+ }
217
+ if (!apc_store($newCachePrefix.$cellID.'.cache',$obj,$this->_cacheTime)) {
218
+ $this->__destruct();
219
+ throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in APC');
220
+ }
221
+ }
222
+ }
223
+ $this->_cachePrefix = $newCachePrefix;
224
+ } // function copyCellCollection()
225
+
226
+
227
+ /**
228
+ * Clear the cell collection and disconnect from our parent
229
+ *
230
+ * @return void
231
+ */
232
+ public function unsetWorksheetCells() {
233
+ if ($this->_currentObject !== NULL) {
234
+ $this->_currentObject->detach();
235
+ $this->_currentObject = $this->_currentObjectID = null;
236
+ }
237
+
238
+ // Flush the APC cache
239
+ $this->__destruct();
240
+
241
+ $this->_cellCache = array();
242
+
243
+ // detach ourself from the worksheet, so that it can then delete this object successfully
244
+ $this->_parent = null;
245
+ } // function unsetWorksheetCells()
246
+
247
+
248
+ /**
249
+ * Initialise this new cell collection
250
+ *
251
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
252
+ * @param array of mixed $arguments Additional initialisation arguments
253
+ */
254
+ public function __construct(PHPExcel_Worksheet $parent, $arguments) {
255
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
256
+
257
+ if ($this->_cachePrefix === NULL) {
258
+ $baseUnique = $this->_getUniqueID();
259
+ $this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
260
+ $this->_cacheTime = $cacheTime;
261
+
262
+ parent::__construct($parent);
263
+ }
264
+ } // function __construct()
265
+
266
+
267
+ /**
268
+ * Destroy this cell collection
269
+ */
270
+ public function __destruct() {
271
+ $cacheList = $this->getCellList();
272
+ foreach($cacheList as $cellID) {
273
+ apc_delete($this->_cachePrefix.$cellID.'.cache');
274
+ }
275
+ } // function __destruct()
276
+
277
+
278
+ /**
279
+ * Identify whether the caching method is currently available
280
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
281
+ *
282
+ * @return boolean
283
+ */
284
+ public static function cacheMethodIsAvailable() {
285
+ if (!function_exists('apc_store')) {
286
+ return FALSE;
287
+ }
288
+ if (apc_sma_info() === FALSE) {
289
+ return FALSE;
290
+ }
291
+
292
+ return TRUE;
293
+ }
294
+
295
+ }
libraries/PHPExcel/CachedObjectStorage/CacheBase.php ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_CacheBase
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ abstract class PHPExcel_CachedObjectStorage_CacheBase {
37
+
38
+ /**
39
+ * Parent worksheet
40
+ *
41
+ * @var PHPExcel_Worksheet
42
+ */
43
+ protected $_parent;
44
+
45
+ /**
46
+ * The currently active Cell
47
+ *
48
+ * @var PHPExcel_Cell
49
+ */
50
+ protected $_currentObject = null;
51
+
52
+ /**
53
+ * Coordinate address of the currently active Cell
54
+ *
55
+ * @var string
56
+ */
57
+ protected $_currentObjectID = null;
58
+
59
+
60
+ /**
61
+ * Flag indicating whether the currently active Cell requires saving
62
+ *
63
+ * @var boolean
64
+ */
65
+ protected $_currentCellIsDirty = true;
66
+
67
+ /**
68
+ * An array of cells or cell pointers for the worksheet cells held in this cache,
69
+ * and indexed by their coordinate address within the worksheet
70
+ *
71
+ * @var array of mixed
72
+ */
73
+ protected $_cellCache = array();
74
+
75
+
76
+ /**
77
+ * Initialise this new cell collection
78
+ *
79
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
80
+ */
81
+ public function __construct(PHPExcel_Worksheet $parent) {
82
+ // Set our parent worksheet.
83
+ // This is maintained within the cache controller to facilitate re-attaching it to PHPExcel_Cell objects when
84
+ // they are woken from a serialized state
85
+ $this->_parent = $parent;
86
+ } // function __construct()
87
+
88
+
89
+ /**
90
+ * Return the parent worksheet for this cell collection
91
+ *
92
+ * @return PHPExcel_Worksheet
93
+ */
94
+ public function getParent()
95
+ {
96
+ return $this->_parent;
97
+ }
98
+
99
+ /**
100
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
101
+ *
102
+ * @param string $pCoord Coordinate address of the cell to check
103
+ * @return boolean
104
+ */
105
+ public function isDataSet($pCoord) {
106
+ if ($pCoord === $this->_currentObjectID) {
107
+ return true;
108
+ }
109
+ // Check if the requested entry exists in the cache
110
+ return isset($this->_cellCache[$pCoord]);
111
+ } // function isDataSet()
112
+
113
+
114
+ /**
115
+ * Move a cell object from one address to another
116
+ *
117
+ * @param string $fromAddress Current address of the cell to move
118
+ * @param string $toAddress Destination address of the cell to move
119
+ * @return boolean
120
+ */
121
+ public function moveCell($fromAddress, $toAddress) {
122
+ if ($fromAddress === $this->_currentObjectID) {
123
+ $this->_currentObjectID = $toAddress;
124
+ }
125
+ $this->_currentCellIsDirty = true;
126
+ if (isset($this->_cellCache[$fromAddress])) {
127
+ $this->_cellCache[$toAddress] = &$this->_cellCache[$fromAddress];
128
+ unset($this->_cellCache[$fromAddress]);
129
+ }
130
+
131
+ return TRUE;
132
+ } // function moveCell()
133
+
134
+
135
+ /**
136
+ * Add or Update a cell in cache
137
+ *
138
+ * @param PHPExcel_Cell $cell Cell to update
139
+ * @return PHPExcel_Cell
140
+ * @throws PHPExcel_Exception
141
+ */
142
+ public function updateCacheData(PHPExcel_Cell $cell) {
143
+ return $this->addCacheData($cell->getCoordinate(),$cell);
144
+ } // function updateCacheData()
145
+
146
+
147
+ /**
148
+ * Delete a cell in cache identified by coordinate address
149
+ *
150
+ * @param string $pCoord Coordinate address of the cell to delete
151
+ * @throws PHPExcel_Exception
152
+ */
153
+ public function deleteCacheData($pCoord) {
154
+ if ($pCoord === $this->_currentObjectID && !is_null($this->_currentObject)) {
155
+ $this->_currentObject->detach();
156
+ $this->_currentObjectID = $this->_currentObject = null;
157
+ }
158
+
159
+ if (is_object($this->_cellCache[$pCoord])) {
160
+ $this->_cellCache[$pCoord]->detach();
161
+ unset($this->_cellCache[$pCoord]);
162
+ }
163
+ $this->_currentCellIsDirty = false;
164
+ } // function deleteCacheData()
165
+
166
+
167
+ /**
168
+ * Get a list of all cell addresses currently held in cache
169
+ *
170
+ * @return string[]
171
+ */
172
+ public function getCellList() {
173
+ return array_keys($this->_cellCache);
174
+ } // function getCellList()
175
+
176
+
177
+ /**
178
+ * Sort the list of all cell addresses currently held in cache by row and column
179
+ *
180
+ * @return string[]
181
+ */
182
+ public function getSortedCellList() {
183
+ $sortKeys = array();
184
+ foreach ($this->getCellList() as $coord) {
185
+ sscanf($coord,'%[A-Z]%d', $column, $row);
186
+ $sortKeys[sprintf('%09d%3s',$row,$column)] = $coord;
187
+ }
188
+ ksort($sortKeys);
189
+
190
+ return array_values($sortKeys);
191
+ } // function sortCellList()
192
+
193
+
194
+
195
+ /**
196
+ * Get highest worksheet column and highest row that have cell records
197
+ *
198
+ * @return array Highest column name and highest row number
199
+ */
200
+ public function getHighestRowAndColumn()
201
+ {
202
+ // Lookup highest column and highest row
203
+ $col = array('A' => '1A');
204
+ $row = array(1);
205
+ foreach ($this->getCellList() as $coord) {
206
+ sscanf($coord,'%[A-Z]%d', $c, $r);
207
+ $row[$r] = $r;
208
+ $col[$c] = strlen($c).$c;
209
+ }
210
+ if (!empty($row)) {
211
+ // Determine highest column and row
212
+ $highestRow = max($row);
213
+ $highestColumn = substr(max($col),1);
214
+ }
215
+
216
+ return array( 'row' => $highestRow,
217
+ 'column' => $highestColumn
218
+ );
219
+ }
220
+
221
+
222
+ /**
223
+ * Return the cell address of the currently active cell object
224
+ *
225
+ * @return string
226
+ */
227
+ public function getCurrentAddress()
228
+ {
229
+ return $this->_currentObjectID;
230
+ }
231
+
232
+ /**
233
+ * Return the column address of the currently active cell object
234
+ *
235
+ * @return string
236
+ */
237
+ public function getCurrentColumn()
238
+ {
239
+ sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
240
+ return $column;
241
+ }
242
+
243
+ /**
244
+ * Return the row address of the currently active cell object
245
+ *
246
+ * @return integer
247
+ */
248
+ public function getCurrentRow()
249
+ {
250
+ sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row);
251
+ return (integer) $row;
252
+ }
253
+
254
+ /**
255
+ * Get highest worksheet column
256
+ *
257
+ * @param string $row Return the highest column for the specified row,
258
+ * or the highest column of any row if no row number is passed
259
+ * @return string Highest column name
260
+ */
261
+ public function getHighestColumn($row = null)
262
+ {
263
+ if ($row == null) {
264
+ $colRow = $this->getHighestRowAndColumn();
265
+ return $colRow['column'];
266
+ }
267
+
268
+ $columnList = array(1);
269
+ foreach ($this->getCellList() as $coord) {
270
+ sscanf($coord,'%[A-Z]%d', $c, $r);
271
+ if ($r != $row) {
272
+ continue;
273
+ }
274
+ $columnList[] = PHPExcel_Cell::columnIndexFromString($c);
275
+ }
276
+ return PHPExcel_Cell::stringFromColumnIndex(max($columnList) - 1);
277
+ }
278
+
279
+ /**
280
+ * Get highest worksheet row
281
+ *
282
+ * @param string $column Return the highest row for the specified column,
283
+ * or the highest row of any column if no column letter is passed
284
+ * @return int Highest row number
285
+ */
286
+ public function getHighestRow($column = null)
287
+ {
288
+ if ($column == null) {
289
+ $colRow = $this->getHighestRowAndColumn();
290
+ return $colRow['row'];
291
+ }
292
+
293
+ $rowList = array(0);
294
+ foreach ($this->getCellList() as $coord) {
295
+ sscanf($coord,'%[A-Z]%d', $c, $r);
296
+ if ($c != $column) {
297
+ continue;
298
+ }
299
+ $rowList[] = $r;
300
+ }
301
+
302
+ return max($rowList);
303
+ }
304
+
305
+
306
+ /**
307
+ * Generate a unique ID for cache referencing
308
+ *
309
+ * @return string Unique Reference
310
+ */
311
+ protected function _getUniqueID() {
312
+ if (function_exists('posix_getpid')) {
313
+ $baseUnique = posix_getpid();
314
+ } else {
315
+ $baseUnique = mt_rand();
316
+ }
317
+ return uniqid($baseUnique,true);
318
+ }
319
+
320
+ /**
321
+ * Clone the cell collection
322
+ *
323
+ * @param PHPExcel_Worksheet $parent The new worksheet
324
+ * @return void
325
+ */
326
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
327
+ $this->_currentCellIsDirty;
328
+ $this->_storeData();
329
+
330
+ $this->_parent = $parent;
331
+ if (($this->_currentObject !== NULL) && (is_object($this->_currentObject))) {
332
+ $this->_currentObject->attach($this);
333
+ }
334
+ } // function copyCellCollection()
335
+
336
+ /**
337
+ * Remove a row, deleting all cells in that row
338
+ *
339
+ * @param string $row Row number to remove
340
+ * @return void
341
+ */
342
+ public function removeRow($row) {
343
+ foreach ($this->getCellList() as $coord) {
344
+ sscanf($coord,'%[A-Z]%d', $c, $r);
345
+ if ($r == $row) {
346
+ $this->deleteCacheData($coord);
347
+ }
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Remove a column, deleting all cells in that column
353
+ *
354
+ * @param string $column Column ID to remove
355
+ * @return void
356
+ */
357
+ public function removeColumn($column) {
358
+ foreach ($this->getCellList() as $coord) {
359
+ sscanf($coord,'%[A-Z]%d', $c, $r);
360
+ if ($c == $column) {
361
+ $this->deleteCacheData($coord);
362
+ }
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Identify whether the caching method is currently available
368
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
369
+ *
370
+ * @return boolean
371
+ */
372
+ public static function cacheMethodIsAvailable() {
373
+ return true;
374
+ }
375
+
376
+ }
libraries/PHPExcel/CachedObjectStorage/DiscISAM.php ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_DiscISAM
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_DiscISAM extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Name of the file for this cache
40
+ *
41
+ * @var string
42
+ */
43
+ private $_fileName = NULL;
44
+
45
+ /**
46
+ * File handle for this cache file
47
+ *
48
+ * @var resource
49
+ */
50
+ private $_fileHandle = NULL;
51
+
52
+ /**
53
+ * Directory/Folder where the cache file is located
54
+ *
55
+ * @var string
56
+ */
57
+ private $_cacheDirectory = NULL;
58
+
59
+
60
+ /**
61
+ * Store cell data in cache for the current cell object if it's "dirty",
62
+ * and the 'nullify' the current cell object
63
+ *
64
+ * @return void
65
+ * @throws PHPExcel_Exception
66
+ */
67
+ protected function _storeData() {
68
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
69
+ $this->_currentObject->detach();
70
+
71
+ fseek($this->_fileHandle,0,SEEK_END);
72
+
73
+ $this->_cellCache[$this->_currentObjectID] = array(
74
+ 'ptr' => ftell($this->_fileHandle),
75
+ 'sz' => fwrite($this->_fileHandle, serialize($this->_currentObject))
76
+ );
77
+ $this->_currentCellIsDirty = false;
78
+ }
79
+ $this->_currentObjectID = $this->_currentObject = null;
80
+ } // function _storeData()
81
+
82
+
83
+ /**
84
+ * Add or Update a cell in cache identified by coordinate address
85
+ *
86
+ * @param string $pCoord Coordinate address of the cell to update
87
+ * @param PHPExcel_Cell $cell Cell to update
88
+ * @return PHPExcel_Cell
89
+ * @throws PHPExcel_Exception
90
+ */
91
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
92
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
93
+ $this->_storeData();
94
+ }
95
+
96
+ $this->_currentObjectID = $pCoord;
97
+ $this->_currentObject = $cell;
98
+ $this->_currentCellIsDirty = true;
99
+
100
+ return $cell;
101
+ } // function addCacheData()
102
+
103
+
104
+ /**
105
+ * Get cell at a specific coordinate
106
+ *
107
+ * @param string $pCoord Coordinate of the cell
108
+ * @throws PHPExcel_Exception
109
+ * @return PHPExcel_Cell Cell that was found, or null if not found
110
+ */
111
+ public function getCacheData($pCoord) {
112
+ if ($pCoord === $this->_currentObjectID) {
113
+ return $this->_currentObject;
114
+ }
115
+ $this->_storeData();
116
+
117
+ // Check if the entry that has been requested actually exists
118
+ if (!isset($this->_cellCache[$pCoord])) {
119
+ // Return null if requested entry doesn't exist in cache
120
+ return null;
121
+ }
122
+
123
+ // Set current entry to the requested entry
124
+ $this->_currentObjectID = $pCoord;
125
+ fseek($this->_fileHandle, $this->_cellCache[$pCoord]['ptr']);
126
+ $this->_currentObject = unserialize(fread($this->_fileHandle, $this->_cellCache[$pCoord]['sz']));
127
+ // Re-attach this as the cell's parent
128
+ $this->_currentObject->attach($this);
129
+
130
+ // Return requested entry
131
+ return $this->_currentObject;
132
+ } // function getCacheData()
133
+
134
+
135
+ /**
136
+ * Get a list of all cell addresses currently held in cache
137
+ *
138
+ * @return string[]
139
+ */
140
+ public function getCellList() {
141
+ if ($this->_currentObjectID !== null) {
142
+ $this->_storeData();
143
+ }
144
+
145
+ return parent::getCellList();
146
+ }
147
+
148
+
149
+ /**
150
+ * Clone the cell collection
151
+ *
152
+ * @param PHPExcel_Worksheet $parent The new worksheet
153
+ * @return void
154
+ */
155
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
156
+ parent::copyCellCollection($parent);
157
+ // Get a new id for the new file name
158
+ $baseUnique = $this->_getUniqueID();
159
+ $newFileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
160
+ // Copy the existing cell cache file
161
+ copy ($this->_fileName,$newFileName);
162
+ $this->_fileName = $newFileName;
163
+ // Open the copied cell cache file
164
+ $this->_fileHandle = fopen($this->_fileName,'a+');
165
+ } // function copyCellCollection()
166
+
167
+
168
+ /**
169
+ * Clear the cell collection and disconnect from our parent
170
+ *
171
+ * @return void
172
+ */
173
+ public function unsetWorksheetCells() {
174
+ if(!is_null($this->_currentObject)) {
175
+ $this->_currentObject->detach();
176
+ $this->_currentObject = $this->_currentObjectID = null;
177
+ }
178
+ $this->_cellCache = array();
179
+
180
+ // detach ourself from the worksheet, so that it can then delete this object successfully
181
+ $this->_parent = null;
182
+
183
+ // Close down the temporary cache file
184
+ $this->__destruct();
185
+ } // function unsetWorksheetCells()
186
+
187
+
188
+ /**
189
+ * Initialise this new cell collection
190
+ *
191
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
192
+ * @param array of mixed $arguments Additional initialisation arguments
193
+ */
194
+ public function __construct(PHPExcel_Worksheet $parent, $arguments) {
195
+ $this->_cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== NULL))
196
+ ? $arguments['dir']
197
+ : PHPExcel_Shared_File::sys_get_temp_dir();
198
+
199
+ parent::__construct($parent);
200
+ if (is_null($this->_fileHandle)) {
201
+ $baseUnique = $this->_getUniqueID();
202
+ $this->_fileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
203
+ $this->_fileHandle = fopen($this->_fileName,'a+');
204
+ }
205
+ } // function __construct()
206
+
207
+
208
+ /**
209
+ * Destroy this cell collection
210
+ */
211
+ public function __destruct() {
212
+ if (!is_null($this->_fileHandle)) {
213
+ fclose($this->_fileHandle);
214
+ unlink($this->_fileName);
215
+ }
216
+ $this->_fileHandle = null;
217
+ } // function __destruct()
218
+
219
+ }
libraries/PHPExcel/CachedObjectStorage/ICache.php ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_ICache
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ interface PHPExcel_CachedObjectStorage_ICache
37
+ {
38
+ /**
39
+ * Add or Update a cell in cache identified by coordinate address
40
+ *
41
+ * @param string $pCoord Coordinate address of the cell to update
42
+ * @param PHPExcel_Cell $cell Cell to update
43
+ * @return PHPExcel_Cell
44
+ * @throws PHPExcel_Exception
45
+ */
46
+ public function addCacheData($pCoord, PHPExcel_Cell $cell);
47
+
48
+ /**
49
+ * Add or Update a cell in cache
50
+ *
51
+ * @param PHPExcel_Cell $cell Cell to update
52
+ * @return PHPExcel_Cell
53
+ * @throws PHPExcel_Exception
54
+ */
55
+ public function updateCacheData(PHPExcel_Cell $cell);
56
+
57
+ /**
58
+ * Fetch a cell from cache identified by coordinate address
59
+ *
60
+ * @param string $pCoord Coordinate address of the cell to retrieve
61
+ * @return PHPExcel_Cell Cell that was found, or null if not found
62
+ * @throws PHPExcel_Exception
63
+ */
64
+ public function getCacheData($pCoord);
65
+
66
+ /**
67
+ * Delete a cell in cache identified by coordinate address
68
+ *
69
+ * @param string $pCoord Coordinate address of the cell to delete
70
+ * @throws PHPExcel_Exception
71
+ */
72
+ public function deleteCacheData($pCoord);
73
+
74
+ /**
75
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
76
+ *
77
+ * @param string $pCoord Coordinate address of the cell to check
78
+ * @return boolean
79
+ */
80
+ public function isDataSet($pCoord);
81
+
82
+ /**
83
+ * Get a list of all cell addresses currently held in cache
84
+ *
85
+ * @return string[]
86
+ */
87
+ public function getCellList();
88
+
89
+ /**
90
+ * Get the list of all cell addresses currently held in cache sorted by column and row
91
+ *
92
+ * @return string[]
93
+ */
94
+ public function getSortedCellList();
95
+
96
+ /**
97
+ * Clone the cell collection
98
+ *
99
+ * @param PHPExcel_Worksheet $parent The new worksheet
100
+ * @return void
101
+ */
102
+ public function copyCellCollection(PHPExcel_Worksheet $parent);
103
+
104
+ /**
105
+ * Identify whether the caching method is currently available
106
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
107
+ *
108
+ * @return boolean
109
+ */
110
+ public static function cacheMethodIsAvailable();
111
+
112
+ }
libraries/PHPExcel/CachedObjectStorage/Igbinary.php ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_Igbinary
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_Igbinary extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Store cell data in cache for the current cell object if it's "dirty",
40
+ * and the 'nullify' the current cell object
41
+ *
42
+ * @return void
43
+ * @throws PHPExcel_Exception
44
+ */
45
+ protected function _storeData() {
46
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
47
+ $this->_currentObject->detach();
48
+
49
+ $this->_cellCache[$this->_currentObjectID] = igbinary_serialize($this->_currentObject);
50
+ $this->_currentCellIsDirty = false;
51
+ }
52
+ $this->_currentObjectID = $this->_currentObject = null;
53
+ } // function _storeData()
54
+
55
+
56
+ /**
57
+ * Add or Update a cell in cache identified by coordinate address
58
+ *
59
+ * @param string $pCoord Coordinate address of the cell to update
60
+ * @param PHPExcel_Cell $cell Cell to update
61
+ * @return PHPExcel_Cell
62
+ * @throws PHPExcel_Exception
63
+ */
64
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
65
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
66
+ $this->_storeData();
67
+ }
68
+
69
+ $this->_currentObjectID = $pCoord;
70
+ $this->_currentObject = $cell;
71
+ $this->_currentCellIsDirty = true;
72
+
73
+ return $cell;
74
+ } // function addCacheData()
75
+
76
+
77
+ /**
78
+ * Get cell at a specific coordinate
79
+ *
80
+ * @param string $pCoord Coordinate of the cell
81
+ * @throws PHPExcel_Exception
82
+ * @return PHPExcel_Cell Cell that was found, or null if not found
83
+ */
84
+ public function getCacheData($pCoord) {
85
+ if ($pCoord === $this->_currentObjectID) {
86
+ return $this->_currentObject;
87
+ }
88
+ $this->_storeData();
89
+
90
+ // Check if the entry that has been requested actually exists
91
+ if (!isset($this->_cellCache[$pCoord])) {
92
+ // Return null if requested entry doesn't exist in cache
93
+ return null;
94
+ }
95
+
96
+ // Set current entry to the requested entry
97
+ $this->_currentObjectID = $pCoord;
98
+ $this->_currentObject = igbinary_unserialize($this->_cellCache[$pCoord]);
99
+ // Re-attach this as the cell's parent
100
+ $this->_currentObject->attach($this);
101
+
102
+ // Return requested entry
103
+ return $this->_currentObject;
104
+ } // function getCacheData()
105
+
106
+
107
+ /**
108
+ * Get a list of all cell addresses currently held in cache
109
+ *
110
+ * @return string[]
111
+ */
112
+ public function getCellList() {
113
+ if ($this->_currentObjectID !== null) {
114
+ $this->_storeData();
115
+ }
116
+
117
+ return parent::getCellList();
118
+ }
119
+
120
+
121
+ /**
122
+ * Clear the cell collection and disconnect from our parent
123
+ *
124
+ * @return void
125
+ */
126
+ public function unsetWorksheetCells() {
127
+ if(!is_null($this->_currentObject)) {
128
+ $this->_currentObject->detach();
129
+ $this->_currentObject = $this->_currentObjectID = null;
130
+ }
131
+ $this->_cellCache = array();
132
+
133
+ // detach ourself from the worksheet, so that it can then delete this object successfully
134
+ $this->_parent = null;
135
+ } // function unsetWorksheetCells()
136
+
137
+
138
+ /**
139
+ * Identify whether the caching method is currently available
140
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
141
+ *
142
+ * @return boolean
143
+ */
144
+ public static function cacheMethodIsAvailable() {
145
+ if (!function_exists('igbinary_serialize')) {
146
+ return false;
147
+ }
148
+
149
+ return true;
150
+ }
151
+
152
+ }
libraries/PHPExcel/CachedObjectStorage/Memcache.php ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_Memcache
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_Memcache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Prefix used to uniquely identify cache data for this worksheet
40
+ *
41
+ * @var string
42
+ */
43
+ private $_cachePrefix = null;
44
+
45
+ /**
46
+ * Cache timeout
47
+ *
48
+ * @var integer
49
+ */
50
+ private $_cacheTime = 600;
51
+
52
+ /**
53
+ * Memcache interface
54
+ *
55
+ * @var resource
56
+ */
57
+ private $_memcache = null;
58
+
59
+
60
+ /**
61
+ * Store cell data in cache for the current cell object if it's "dirty",
62
+ * and the 'nullify' the current cell object
63
+ *
64
+ * @return void
65
+ * @throws PHPExcel_Exception
66
+ */
67
+ protected function _storeData() {
68
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
69
+ $this->_currentObject->detach();
70
+
71
+ $obj = serialize($this->_currentObject);
72
+ if (!$this->_memcache->replace($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) {
73
+ if (!$this->_memcache->add($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) {
74
+ $this->__destruct();
75
+ throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in MemCache');
76
+ }
77
+ }
78
+ $this->_currentCellIsDirty = false;
79
+ }
80
+ $this->_currentObjectID = $this->_currentObject = null;
81
+ } // function _storeData()
82
+
83
+
84
+ /**
85
+ * Add or Update a cell in cache identified by coordinate address
86
+ *
87
+ * @param string $pCoord Coordinate address of the cell to update
88
+ * @param PHPExcel_Cell $cell Cell to update
89
+ * @return PHPExcel_Cell
90
+ * @throws PHPExcel_Exception
91
+ */
92
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
93
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
94
+ $this->_storeData();
95
+ }
96
+ $this->_cellCache[$pCoord] = true;
97
+
98
+ $this->_currentObjectID = $pCoord;
99
+ $this->_currentObject = $cell;
100
+ $this->_currentCellIsDirty = true;
101
+
102
+ return $cell;
103
+ } // function addCacheData()
104
+
105
+
106
+ /**
107
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
108
+ *
109
+ * @param string $pCoord Coordinate address of the cell to check
110
+ * @return boolean
111
+ * @return boolean
112
+ */
113
+ public function isDataSet($pCoord) {
114
+ // Check if the requested entry is the current object, or exists in the cache
115
+ if (parent::isDataSet($pCoord)) {
116
+ if ($this->_currentObjectID == $pCoord) {
117
+ return true;
118
+ }
119
+ // Check if the requested entry still exists in Memcache
120
+ $success = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
121
+ if ($success === false) {
122
+ // Entry no longer exists in Memcache, so clear it from the cache array
123
+ parent::deleteCacheData($pCoord);
124
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
125
+ }
126
+ return true;
127
+ }
128
+ return false;
129
+ } // function isDataSet()
130
+
131
+
132
+ /**
133
+ * Get cell at a specific coordinate
134
+ *
135
+ * @param string $pCoord Coordinate of the cell
136
+ * @throws PHPExcel_Exception
137
+ * @return PHPExcel_Cell Cell that was found, or null if not found
138
+ */
139
+ public function getCacheData($pCoord) {
140
+ if ($pCoord === $this->_currentObjectID) {
141
+ return $this->_currentObject;
142
+ }
143
+ $this->_storeData();
144
+
145
+ // Check if the entry that has been requested actually exists
146
+ if (parent::isDataSet($pCoord)) {
147
+ $obj = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache');
148
+ if ($obj === false) {
149
+ // Entry no longer exists in Memcache, so clear it from the cache array
150
+ parent::deleteCacheData($pCoord);
151
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
152
+ }
153
+ } else {
154
+ // Return null if requested entry doesn't exist in cache
155
+ return null;
156
+ }
157
+
158
+ // Set current entry to the requested entry
159
+ $this->_currentObjectID = $pCoord;
160
+ $this->_currentObject = unserialize($obj);
161
+ // Re-attach this as the cell's parent
162
+ $this->_currentObject->attach($this);
163
+
164
+ // Return requested entry
165
+ return $this->_currentObject;
166
+ } // function getCacheData()
167
+
168
+
169
+ /**
170
+ * Get a list of all cell addresses currently held in cache
171
+ *
172
+ * @return string[]
173
+ */
174
+ public function getCellList() {
175
+ if ($this->_currentObjectID !== null) {
176
+ $this->_storeData();
177
+ }
178
+
179
+ return parent::getCellList();
180
+ }
181
+
182
+
183
+ /**
184
+ * Delete a cell in cache identified by coordinate address
185
+ *
186
+ * @param string $pCoord Coordinate address of the cell to delete
187
+ * @throws PHPExcel_Exception
188
+ */
189
+ public function deleteCacheData($pCoord) {
190
+ // Delete the entry from Memcache
191
+ $this->_memcache->delete($this->_cachePrefix.$pCoord.'.cache');
192
+
193
+ // Delete the entry from our cell address array
194
+ parent::deleteCacheData($pCoord);
195
+ } // function deleteCacheData()
196
+
197
+
198
+ /**
199
+ * Clone the cell collection
200
+ *
201
+ * @param PHPExcel_Worksheet $parent The new worksheet
202
+ * @return void
203
+ */
204
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
205
+ parent::copyCellCollection($parent);
206
+ // Get a new id for the new file name
207
+ $baseUnique = $this->_getUniqueID();
208
+ $newCachePrefix = substr(md5($baseUnique),0,8).'.';
209
+ $cacheList = $this->getCellList();
210
+ foreach($cacheList as $cellID) {
211
+ if ($cellID != $this->_currentObjectID) {
212
+ $obj = $this->_memcache->get($this->_cachePrefix.$cellID.'.cache');
213
+ if ($obj === false) {
214
+ // Entry no longer exists in Memcache, so clear it from the cache array
215
+ parent::deleteCacheData($cellID);
216
+ throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in MemCache');
217
+ }
218
+ if (!$this->_memcache->add($newCachePrefix.$cellID.'.cache',$obj,NULL,$this->_cacheTime)) {
219
+ $this->__destruct();
220
+ throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in MemCache');
221
+ }
222
+ }
223
+ }
224
+ $this->_cachePrefix = $newCachePrefix;
225
+ } // function copyCellCollection()
226
+
227
+
228
+ /**
229
+ * Clear the cell collection and disconnect from our parent
230
+ *
231
+ * @return void
232
+ */
233
+ public function unsetWorksheetCells() {
234
+ if(!is_null($this->_currentObject)) {
235
+ $this->_currentObject->detach();
236
+ $this->_currentObject = $this->_currentObjectID = null;
237
+ }
238
+
239
+ // Flush the Memcache cache
240
+ $this->__destruct();
241
+
242
+ $this->_cellCache = array();
243
+
244
+ // detach ourself from the worksheet, so that it can then delete this object successfully
245
+ $this->_parent = null;
246
+ } // function unsetWorksheetCells()
247
+
248
+
249
+ /**
250
+ * Initialise this new cell collection
251
+ *
252
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
253
+ * @param array of mixed $arguments Additional initialisation arguments
254
+ */
255
+ public function __construct(PHPExcel_Worksheet $parent, $arguments) {
256
+ $memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost';
257
+ $memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211;
258
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
259
+
260
+ if (is_null($this->_cachePrefix)) {
261
+ $baseUnique = $this->_getUniqueID();
262
+ $this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
263
+
264
+ // Set a new Memcache object and connect to the Memcache server
265
+ $this->_memcache = new Memcache();
266
+ if (!$this->_memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) {
267
+ throw new PHPExcel_Exception('Could not connect to MemCache server at '.$memcacheServer.':'.$memcachePort);
268
+ }
269
+ $this->_cacheTime = $cacheTime;
270
+
271
+ parent::__construct($parent);
272
+ }
273
+ } // function __construct()
274
+
275
+
276
+ /**
277
+ * Memcache error handler
278
+ *
279
+ * @param string $host Memcache server
280
+ * @param integer $port Memcache port
281
+ * @throws PHPExcel_Exception
282
+ */
283
+ public function failureCallback($host, $port) {
284
+ throw new PHPExcel_Exception('memcache '.$host.':'.$port.' failed');
285
+ }
286
+
287
+
288
+ /**
289
+ * Destroy this cell collection
290
+ */
291
+ public function __destruct() {
292
+ $cacheList = $this->getCellList();
293
+ foreach($cacheList as $cellID) {
294
+ $this->_memcache->delete($this->_cachePrefix.$cellID.'.cache');
295
+ }
296
+ } // function __destruct()
297
+
298
+ /**
299
+ * Identify whether the caching method is currently available
300
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
301
+ *
302
+ * @return boolean
303
+ */
304
+ public static function cacheMethodIsAvailable() {
305
+ if (!function_exists('memcache_add')) {
306
+ return false;
307
+ }
308
+
309
+ return true;
310
+ }
311
+
312
+ }
libraries/PHPExcel/CachedObjectStorage/Memory.php ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_Memory
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_Memory extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Dummy method callable from CacheBase, but unused by Memory cache
40
+ *
41
+ * @return void
42
+ */
43
+ protected function _storeData() {
44
+ } // function _storeData()
45
+
46
+ /**
47
+ * Add or Update a cell in cache identified by coordinate address
48
+ *
49
+ * @param string $pCoord Coordinate address of the cell to update
50
+ * @param PHPExcel_Cell $cell Cell to update
51
+ * @return PHPExcel_Cell
52
+ * @throws PHPExcel_Exception
53
+ */
54
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
55
+ $this->_cellCache[$pCoord] = $cell;
56
+
57
+ // Set current entry to the new/updated entry
58
+ $this->_currentObjectID = $pCoord;
59
+
60
+ return $cell;
61
+ } // function addCacheData()
62
+
63
+
64
+ /**
65
+ * Get cell at a specific coordinate
66
+ *
67
+ * @param string $pCoord Coordinate of the cell
68
+ * @throws PHPExcel_Exception
69
+ * @return PHPExcel_Cell Cell that was found, or null if not found
70
+ */
71
+ public function getCacheData($pCoord) {
72
+ // Check if the entry that has been requested actually exists
73
+ if (!isset($this->_cellCache[$pCoord])) {
74
+ $this->_currentObjectID = NULL;
75
+ // Return null if requested entry doesn't exist in cache
76
+ return null;
77
+ }
78
+
79
+ // Set current entry to the requested entry
80
+ $this->_currentObjectID = $pCoord;
81
+
82
+ // Return requested entry
83
+ return $this->_cellCache[$pCoord];
84
+ } // function getCacheData()
85
+
86
+
87
+ /**
88
+ * Clone the cell collection
89
+ *
90
+ * @param PHPExcel_Worksheet $parent The new worksheet
91
+ * @return void
92
+ */
93
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
94
+ parent::copyCellCollection($parent);
95
+
96
+ $newCollection = array();
97
+ foreach($this->_cellCache as $k => &$cell) {
98
+ $newCollection[$k] = clone $cell;
99
+ $newCollection[$k]->attach($this);
100
+ }
101
+
102
+ $this->_cellCache = $newCollection;
103
+ }
104
+
105
+
106
+ /**
107
+ * Clear the cell collection and disconnect from our parent
108
+ *
109
+ * @return void
110
+ */
111
+ public function unsetWorksheetCells() {
112
+ // Because cells are all stored as intact objects in memory, we need to detach each one from the parent
113
+ foreach($this->_cellCache as $k => &$cell) {
114
+ $cell->detach();
115
+ $this->_cellCache[$k] = null;
116
+ }
117
+ unset($cell);
118
+
119
+ $this->_cellCache = array();
120
+
121
+ // detach ourself from the worksheet, so that it can then delete this object successfully
122
+ $this->_parent = null;
123
+ } // function unsetWorksheetCells()
124
+
125
+ }
libraries/PHPExcel/CachedObjectStorage/MemoryGZip.php ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_MemoryGZip
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_MemoryGZip extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Store cell data in cache for the current cell object if it's "dirty",
40
+ * and the 'nullify' the current cell object
41
+ *
42
+ * @return void
43
+ * @throws PHPExcel_Exception
44
+ */
45
+ protected function _storeData() {
46
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
47
+ $this->_currentObject->detach();
48
+
49
+ $this->_cellCache[$this->_currentObjectID] = gzdeflate(serialize($this->_currentObject));
50
+ $this->_currentCellIsDirty = false;
51
+ }
52
+ $this->_currentObjectID = $this->_currentObject = null;
53
+ } // function _storeData()
54
+
55
+
56
+ /**
57
+ * Add or Update a cell in cache identified by coordinate address
58
+ *
59
+ * @param string $pCoord Coordinate address of the cell to update
60
+ * @param PHPExcel_Cell $cell Cell to update
61
+ * @return PHPExcel_Cell
62
+ * @throws PHPExcel_Exception
63
+ */
64
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
65
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
66
+ $this->_storeData();
67
+ }
68
+
69
+ $this->_currentObjectID = $pCoord;
70
+ $this->_currentObject = $cell;
71
+ $this->_currentCellIsDirty = true;
72
+
73
+ return $cell;
74
+ } // function addCacheData()
75
+
76
+
77
+ /**
78
+ * Get cell at a specific coordinate
79
+ *
80
+ * @param string $pCoord Coordinate of the cell
81
+ * @throws PHPExcel_Exception
82
+ * @return PHPExcel_Cell Cell that was found, or null if not found
83
+ */
84
+ public function getCacheData($pCoord) {
85
+ if ($pCoord === $this->_currentObjectID) {
86
+ return $this->_currentObject;
87
+ }
88
+ $this->_storeData();
89
+
90
+ // Check if the entry that has been requested actually exists
91
+ if (!isset($this->_cellCache[$pCoord])) {
92
+ // Return null if requested entry doesn't exist in cache
93
+ return null;
94
+ }
95
+
96
+ // Set current entry to the requested entry
97
+ $this->_currentObjectID = $pCoord;
98
+ $this->_currentObject = unserialize(gzinflate($this->_cellCache[$pCoord]));
99
+ // Re-attach this as the cell's parent
100
+ $this->_currentObject->attach($this);
101
+
102
+ // Return requested entry
103
+ return $this->_currentObject;
104
+ } // function getCacheData()
105
+
106
+
107
+ /**
108
+ * Get a list of all cell addresses currently held in cache
109
+ *
110
+ * @return string[]
111
+ */
112
+ public function getCellList() {
113
+ if ($this->_currentObjectID !== null) {
114
+ $this->_storeData();
115
+ }
116
+
117
+ return parent::getCellList();
118
+ }
119
+
120
+
121
+ /**
122
+ * Clear the cell collection and disconnect from our parent
123
+ *
124
+ * @return void
125
+ */
126
+ public function unsetWorksheetCells() {
127
+ if(!is_null($this->_currentObject)) {
128
+ $this->_currentObject->detach();
129
+ $this->_currentObject = $this->_currentObjectID = null;
130
+ }
131
+ $this->_cellCache = array();
132
+
133
+ // detach ourself from the worksheet, so that it can then delete this object successfully
134
+ $this->_parent = null;
135
+ } // function unsetWorksheetCells()
136
+
137
+ }
libraries/PHPExcel/CachedObjectStorage/MemorySerialized.php ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_MemorySerialized
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_MemorySerialized extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Store cell data in cache for the current cell object if it's "dirty",
40
+ * and the 'nullify' the current cell object
41
+ *
42
+ * @return void
43
+ * @throws PHPExcel_Exception
44
+ */
45
+ protected function _storeData() {
46
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
47
+ $this->_currentObject->detach();
48
+
49
+ $this->_cellCache[$this->_currentObjectID] = serialize($this->_currentObject);
50
+ $this->_currentCellIsDirty = false;
51
+ }
52
+ $this->_currentObjectID = $this->_currentObject = null;
53
+ } // function _storeData()
54
+
55
+
56
+ /**
57
+ * Add or Update a cell in cache identified by coordinate address
58
+ *
59
+ * @param string $pCoord Coordinate address of the cell to update
60
+ * @param PHPExcel_Cell $cell Cell to update
61
+ * @return PHPExcel_Cell
62
+ * @throws PHPExcel_Exception
63
+ */
64
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
65
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
66
+ $this->_storeData();
67
+ }
68
+
69
+ $this->_currentObjectID = $pCoord;
70
+ $this->_currentObject = $cell;
71
+ $this->_currentCellIsDirty = true;
72
+
73
+ return $cell;
74
+ } // function addCacheData()
75
+
76
+
77
+ /**
78
+ * Get cell at a specific coordinate
79
+ *
80
+ * @param string $pCoord Coordinate of the cell
81
+ * @throws PHPExcel_Exception
82
+ * @return PHPExcel_Cell Cell that was found, or null if not found
83
+ */
84
+ public function getCacheData($pCoord) {
85
+ if ($pCoord === $this->_currentObjectID) {
86
+ return $this->_currentObject;
87
+ }
88
+ $this->_storeData();
89
+
90
+ // Check if the entry that has been requested actually exists
91
+ if (!isset($this->_cellCache[$pCoord])) {
92
+ // Return null if requested entry doesn't exist in cache
93
+ return null;
94
+ }
95
+
96
+ // Set current entry to the requested entry
97
+ $this->_currentObjectID = $pCoord;
98
+ $this->_currentObject = unserialize($this->_cellCache[$pCoord]);
99
+ // Re-attach this as the cell's parent
100
+ $this->_currentObject->attach($this);
101
+
102
+ // Return requested entry
103
+ return $this->_currentObject;
104
+ } // function getCacheData()
105
+
106
+
107
+ /**
108
+ * Get a list of all cell addresses currently held in cache
109
+ *
110
+ * @return string[]
111
+ */
112
+ public function getCellList() {
113
+ if ($this->_currentObjectID !== null) {
114
+ $this->_storeData();
115
+ }
116
+
117
+ return parent::getCellList();
118
+ }
119
+
120
+
121
+ /**
122
+ * Clear the cell collection and disconnect from our parent
123
+ *
124
+ * @return void
125
+ */
126
+ public function unsetWorksheetCells() {
127
+ if(!is_null($this->_currentObject)) {
128
+ $this->_currentObject->detach();
129
+ $this->_currentObject = $this->_currentObjectID = null;
130
+ }
131
+ $this->_cellCache = array();
132
+
133
+ // detach ourself from the worksheet, so that it can then delete this object successfully
134
+ $this->_parent = null;
135
+ } // function unsetWorksheetCells()
136
+
137
+ }
libraries/PHPExcel/CachedObjectStorage/PHPTemp.php ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_PHPTemp
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_PHPTemp extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Name of the file for this cache
40
+ *
41
+ * @var string
42
+ */
43
+ private $_fileHandle = null;
44
+
45
+ /**
46
+ * Memory limit to use before reverting to file cache
47
+ *
48
+ * @var integer
49
+ */
50
+ private $_memoryCacheSize = null;
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
+ 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
+ } // function _storeData()
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
+ 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
+ } // function addCacheData()
94
+
95
+
96
+ /**
97
+ * Get cell at a specific coordinate
98
+ *
99
+ * @param string $pCoord Coordinate of the cell
100
+ * @throws PHPExcel_Exception
101
+ * @return PHPExcel_Cell Cell that was found, or null if not found
102
+ */
103
+ public function getCacheData($pCoord) {
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
+ } // function getCacheData()
125
+
126
+
127
+ /**
128
+ * Get a list of all cell addresses currently held in cache
129
+ *
130
+ * @return string[]
131
+ */
132
+ public function getCellList() {
133
+ if ($this->_currentObjectID !== null) {
134
+ $this->_storeData();
135
+ }
136
+
137
+ return parent::getCellList();
138
+ }
139
+
140
+
141
+ /**
142
+ * Clone the cell collection
143
+ *
144
+ * @param PHPExcel_Worksheet $parent The new worksheet
145
+ * @return void
146
+ */
147
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
148
+ parent::copyCellCollection($parent);
149
+ // Open a new stream for the cell cache data
150
+ $newFileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
151
+ // Copy the existing cell cache data to the new stream
152
+ fseek($this->_fileHandle,0);
153
+ while (!feof($this->_fileHandle)) {
154
+ fwrite($newFileHandle,fread($this->_fileHandle, 1024));
155
+ }
156
+ $this->_fileHandle = $newFileHandle;
157
+ } // function copyCellCollection()
158
+
159
+
160
+ /**
161
+ * Clear the cell collection and disconnect from our parent
162
+ *
163
+ * @return void
164
+ */
165
+ public function unsetWorksheetCells() {
166
+ if(!is_null($this->_currentObject)) {
167
+ $this->_currentObject->detach();
168
+ $this->_currentObject = $this->_currentObjectID = null;
169
+ }
170
+ $this->_cellCache = array();
171
+
172
+ // detach ourself from the worksheet, so that it can then delete this object successfully
173
+ $this->_parent = null;
174
+
175
+ // Close down the php://temp file
176
+ $this->__destruct();
177
+ } // function unsetWorksheetCells()
178
+
179
+
180
+ /**
181
+ * Initialise this new cell collection
182
+ *
183
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
184
+ * @param array of mixed $arguments Additional initialisation arguments
185
+ */
186
+ public function __construct(PHPExcel_Worksheet $parent, $arguments) {
187
+ $this->_memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB';
188
+
189
+ parent::__construct($parent);
190
+ if (is_null($this->_fileHandle)) {
191
+ $this->_fileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+');
192
+ }
193
+ } // function __construct()
194
+
195
+
196
+ /**
197
+ * Destroy this cell collection
198
+ */
199
+ public function __destruct() {
200
+ if (!is_null($this->_fileHandle)) {
201
+ fclose($this->_fileHandle);
202
+ }
203
+ $this->_fileHandle = null;
204
+ } // function __destruct()
205
+
206
+ }
libraries/PHPExcel/CachedObjectStorage/SQLite.php ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_SQLite
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_SQLite extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Database table name
40
+ *
41
+ * @var string
42
+ */
43
+ private $_TableName = null;
44
+
45
+ /**
46
+ * Database handle
47
+ *
48
+ * @var resource
49
+ */
50
+ private $_DBHandle = null;
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
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
61
+ $this->_currentObject->detach();
62
+
63
+ if (!$this->_DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES('".$this->_currentObjectID."','".sqlite_escape_string(serialize($this->_currentObject))."')"))
64
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
65
+ $this->_currentCellIsDirty = false;
66
+ }
67
+ $this->_currentObjectID = $this->_currentObject = null;
68
+ } // function _storeData()
69
+
70
+
71
+ /**
72
+ * Add or Update a cell in cache identified by coordinate address
73
+ *
74
+ * @param string $pCoord Coordinate address of the cell to update
75
+ * @param PHPExcel_Cell $cell Cell to update
76
+ * @return PHPExcel_Cell
77
+ * @throws PHPExcel_Exception
78
+ */
79
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
80
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
81
+ $this->_storeData();
82
+ }
83
+
84
+ $this->_currentObjectID = $pCoord;
85
+ $this->_currentObject = $cell;
86
+ $this->_currentCellIsDirty = true;
87
+
88
+ return $cell;
89
+ } // function addCacheData()
90
+
91
+
92
+ /**
93
+ * Get cell at a specific coordinate
94
+ *
95
+ * @param string $pCoord Coordinate of the cell
96
+ * @throws PHPExcel_Exception
97
+ * @return PHPExcel_Cell Cell that was found, or null if not found
98
+ */
99
+ public function getCacheData($pCoord) {
100
+ if ($pCoord === $this->_currentObjectID) {
101
+ return $this->_currentObject;
102
+ }
103
+ $this->_storeData();
104
+
105
+ $query = "SELECT value FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
106
+ $cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
107
+ if ($cellResultSet === false) {
108
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
109
+ } elseif ($cellResultSet->numRows() == 0) {
110
+ // Return null if requested entry doesn't exist in cache
111
+ return null;
112
+ }
113
+
114
+ // Set current entry to the requested entry
115
+ $this->_currentObjectID = $pCoord;
116
+
117
+ $cellResult = $cellResultSet->fetchSingle();
118
+ $this->_currentObject = unserialize($cellResult);
119
+ // Re-attach this as the cell's parent
120
+ $this->_currentObject->attach($this);
121
+
122
+ // Return requested entry
123
+ return $this->_currentObject;
124
+ } // function getCacheData()
125
+
126
+
127
+ /**
128
+ * Is a value set for an indexed cell?
129
+ *
130
+ * @param string $pCoord Coordinate address of the cell to check
131
+ * @return boolean
132
+ */
133
+ public function isDataSet($pCoord) {
134
+ if ($pCoord === $this->_currentObjectID) {
135
+ return true;
136
+ }
137
+
138
+ // Check if the requested entry exists in the cache
139
+ $query = "SELECT id FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
140
+ $cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC);
141
+ if ($cellResultSet === false) {
142
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
143
+ } elseif ($cellResultSet->numRows() == 0) {
144
+ // Return null if requested entry doesn't exist in cache
145
+ return false;
146
+ }
147
+ return true;
148
+ } // function isDataSet()
149
+
150
+
151
+ /**
152
+ * Delete a cell in cache identified by coordinate address
153
+ *
154
+ * @param string $pCoord Coordinate address of the cell to delete
155
+ * @throws PHPExcel_Exception
156
+ */
157
+ public function deleteCacheData($pCoord) {
158
+ if ($pCoord === $this->_currentObjectID) {
159
+ $this->_currentObject->detach();
160
+ $this->_currentObjectID = $this->_currentObject = null;
161
+ }
162
+
163
+ // Check if the requested entry exists in the cache
164
+ $query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'";
165
+ if (!$this->_DBHandle->queryExec($query))
166
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
167
+
168
+ $this->_currentCellIsDirty = false;
169
+ } // function deleteCacheData()
170
+
171
+
172
+ /**
173
+ * Move a cell object from one address to another
174
+ *
175
+ * @param string $fromAddress Current address of the cell to move
176
+ * @param string $toAddress Destination address of the cell to move
177
+ * @return boolean
178
+ */
179
+ public function moveCell($fromAddress, $toAddress) {
180
+ if ($fromAddress === $this->_currentObjectID) {
181
+ $this->_currentObjectID = $toAddress;
182
+ }
183
+
184
+ $query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$toAddress."'";
185
+ $result = $this->_DBHandle->exec($query);
186
+ if ($result === false)
187
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
188
+
189
+ $query = "UPDATE kvp_".$this->_TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'";
190
+ $result = $this->_DBHandle->exec($query);
191
+ if ($result === false)
192
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
193
+
194
+ return TRUE;
195
+ } // function moveCell()
196
+
197
+
198
+ /**
199
+ * Get a list of all cell addresses currently held in cache
200
+ *
201
+ * @return string[]
202
+ */
203
+ public function getCellList() {
204
+ if ($this->_currentObjectID !== null) {
205
+ $this->_storeData();
206
+ }
207
+
208
+ $query = "SELECT id FROM kvp_".$this->_TableName;
209
+ $cellIdsResult = $this->_DBHandle->unbufferedQuery($query,SQLITE_ASSOC);
210
+ if ($cellIdsResult === false)
211
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
212
+
213
+ $cellKeys = array();
214
+ foreach($cellIdsResult as $row) {
215
+ $cellKeys[] = $row['id'];
216
+ }
217
+
218
+ return $cellKeys;
219
+ } // function getCellList()
220
+
221
+
222
+ /**
223
+ * Clone the cell collection
224
+ *
225
+ * @param PHPExcel_Worksheet $parent The new worksheet
226
+ * @return void
227
+ */
228
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
229
+ $this->_currentCellIsDirty;
230
+ $this->_storeData();
231
+
232
+ // Get a new id for the new table name
233
+ $tableName = str_replace('.','_',$this->_getUniqueID());
234
+ if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
235
+ AS SELECT * FROM kvp_'.$this->_TableName))
236
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
237
+
238
+ // Copy the existing cell cache file
239
+ $this->_TableName = $tableName;
240
+ } // function copyCellCollection()
241
+
242
+
243
+ /**
244
+ * Clear the cell collection and disconnect from our parent
245
+ *
246
+ * @return void
247
+ */
248
+ public function unsetWorksheetCells() {
249
+ if(!is_null($this->_currentObject)) {
250
+ $this->_currentObject->detach();
251
+ $this->_currentObject = $this->_currentObjectID = null;
252
+ }
253
+ // detach ourself from the worksheet, so that it can then delete this object successfully
254
+ $this->_parent = null;
255
+
256
+ // Close down the temporary cache file
257
+ $this->__destruct();
258
+ } // function unsetWorksheetCells()
259
+
260
+
261
+ /**
262
+ * Initialise this new cell collection
263
+ *
264
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
265
+ */
266
+ public function __construct(PHPExcel_Worksheet $parent) {
267
+ parent::__construct($parent);
268
+ if (is_null($this->_DBHandle)) {
269
+ $this->_TableName = str_replace('.','_',$this->_getUniqueID());
270
+ $_DBName = ':memory:';
271
+
272
+ $this->_DBHandle = new SQLiteDatabase($_DBName);
273
+ if ($this->_DBHandle === false)
274
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
275
+ if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
276
+ throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError()));
277
+ }
278
+ } // function __construct()
279
+
280
+
281
+ /**
282
+ * Destroy this cell collection
283
+ */
284
+ public function __destruct() {
285
+ if (!is_null($this->_DBHandle)) {
286
+ $this->_DBHandle->queryExec('DROP TABLE kvp_'.$this->_TableName);
287
+ }
288
+ $this->_DBHandle = null;
289
+ } // function __destruct()
290
+
291
+
292
+ /**
293
+ * Identify whether the caching method is currently available
294
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
295
+ *
296
+ * @return boolean
297
+ */
298
+ public static function cacheMethodIsAvailable() {
299
+ if (!function_exists('sqlite_open')) {
300
+ return false;
301
+ }
302
+
303
+ return true;
304
+ }
305
+
306
+ }
libraries/PHPExcel/CachedObjectStorage/SQLite3.php ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_SQLite3
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_SQLite3 extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Database table name
40
+ *
41
+ * @var string
42
+ */
43
+ private $_TableName = null;
44
+
45
+ /**
46
+ * Database handle
47
+ *
48
+ * @var resource
49
+ */
50
+ private $_DBHandle = null;
51
+
52
+ /**
53
+ * Prepared statement for a SQLite3 select query
54
+ *
55
+ * @var SQLite3Stmt
56
+ */
57
+ private $_selectQuery;
58
+
59
+ /**
60
+ * Prepared statement for a SQLite3 insert query
61
+ *
62
+ * @var SQLite3Stmt
63
+ */
64
+ private $_insertQuery;
65
+
66
+ /**
67
+ * Prepared statement for a SQLite3 update query
68
+ *
69
+ * @var SQLite3Stmt
70
+ */
71
+ private $_updateQuery;
72
+
73
+ /**
74
+ * Prepared statement for a SQLite3 delete query
75
+ *
76
+ * @var SQLite3Stmt
77
+ */
78
+ private $_deleteQuery;
79
+
80
+ /**
81
+ * Store cell data in cache for the current cell object if it's "dirty",
82
+ * and the 'nullify' the current cell object
83
+ *
84
+ * @return void
85
+ * @throws PHPExcel_Exception
86
+ */
87
+ protected function _storeData() {
88
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
89
+ $this->_currentObject->detach();
90
+
91
+ $this->_insertQuery->bindValue('id',$this->_currentObjectID,SQLITE3_TEXT);
92
+ $this->_insertQuery->bindValue('data',serialize($this->_currentObject),SQLITE3_BLOB);
93
+ $result = $this->_insertQuery->execute();
94
+ if ($result === false)
95
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
96
+ $this->_currentCellIsDirty = false;
97
+ }
98
+ $this->_currentObjectID = $this->_currentObject = null;
99
+ } // function _storeData()
100
+
101
+
102
+ /**
103
+ * Add or Update a cell in cache identified by coordinate address
104
+ *
105
+ * @param string $pCoord Coordinate address of the cell to update
106
+ * @param PHPExcel_Cell $cell Cell to update
107
+ * @return PHPExcel_Cell
108
+ * @throws PHPExcel_Exception
109
+ */
110
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
111
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
112
+ $this->_storeData();
113
+ }
114
+
115
+ $this->_currentObjectID = $pCoord;
116
+ $this->_currentObject = $cell;
117
+ $this->_currentCellIsDirty = true;
118
+
119
+ return $cell;
120
+ } // function addCacheData()
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
+ if ($pCoord === $this->_currentObjectID) {
132
+ return $this->_currentObject;
133
+ }
134
+ $this->_storeData();
135
+
136
+ $this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
137
+ $cellResult = $this->_selectQuery->execute();
138
+ if ($cellResult === FALSE) {
139
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
140
+ }
141
+ $cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
142
+ if ($cellData === FALSE) {
143
+ // Return null if requested entry doesn't exist in cache
144
+ return NULL;
145
+ }
146
+
147
+ // Set current entry to the requested entry
148
+ $this->_currentObjectID = $pCoord;
149
+
150
+ $this->_currentObject = unserialize($cellData['value']);
151
+ // Re-attach this as the cell's parent
152
+ $this->_currentObject->attach($this);
153
+
154
+ // Return requested entry
155
+ return $this->_currentObject;
156
+ } // function getCacheData()
157
+
158
+
159
+ /**
160
+ * Is a value set for an indexed cell?
161
+ *
162
+ * @param string $pCoord Coordinate address of the cell to check
163
+ * @return boolean
164
+ */
165
+ public function isDataSet($pCoord) {
166
+ if ($pCoord === $this->_currentObjectID) {
167
+ return TRUE;
168
+ }
169
+
170
+ // Check if the requested entry exists in the cache
171
+ $this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
172
+ $cellResult = $this->_selectQuery->execute();
173
+ if ($cellResult === FALSE) {
174
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
175
+ }
176
+ $cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
177
+
178
+ return ($cellData === FALSE) ? FALSE : TRUE;
179
+ } // function isDataSet()
180
+
181
+
182
+ /**
183
+ * Delete a cell in cache identified by coordinate address
184
+ *
185
+ * @param string $pCoord Coordinate address of the cell to delete
186
+ * @throws PHPExcel_Exception
187
+ */
188
+ public function deleteCacheData($pCoord) {
189
+ if ($pCoord === $this->_currentObjectID) {
190
+ $this->_currentObject->detach();
191
+ $this->_currentObjectID = $this->_currentObject = NULL;
192
+ }
193
+
194
+ // Check if the requested entry exists in the cache
195
+ $this->_deleteQuery->bindValue('id',$pCoord,SQLITE3_TEXT);
196
+ $result = $this->_deleteQuery->execute();
197
+ if ($result === FALSE)
198
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
199
+
200
+ $this->_currentCellIsDirty = FALSE;
201
+ } // function deleteCacheData()
202
+
203
+
204
+ /**
205
+ * Move a cell object from one address to another
206
+ *
207
+ * @param string $fromAddress Current address of the cell to move
208
+ * @param string $toAddress Destination address of the cell to move
209
+ * @return boolean
210
+ */
211
+ public function moveCell($fromAddress, $toAddress) {
212
+ if ($fromAddress === $this->_currentObjectID) {
213
+ $this->_currentObjectID = $toAddress;
214
+ }
215
+
216
+ $this->_deleteQuery->bindValue('id',$toAddress,SQLITE3_TEXT);
217
+ $result = $this->_deleteQuery->execute();
218
+ if ($result === false)
219
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
220
+
221
+ $this->_updateQuery->bindValue('toid',$toAddress,SQLITE3_TEXT);
222
+ $this->_updateQuery->bindValue('fromid',$fromAddress,SQLITE3_TEXT);
223
+ $result = $this->_updateQuery->execute();
224
+ if ($result === false)
225
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
226
+
227
+ return TRUE;
228
+ } // function moveCell()
229
+
230
+
231
+ /**
232
+ * Get a list of all cell addresses currently held in cache
233
+ *
234
+ * @return string[]
235
+ */
236
+ public function getCellList() {
237
+ if ($this->_currentObjectID !== null) {
238
+ $this->_storeData();
239
+ }
240
+
241
+ $query = "SELECT id FROM kvp_".$this->_TableName;
242
+ $cellIdsResult = $this->_DBHandle->query($query);
243
+ if ($cellIdsResult === false)
244
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
245
+
246
+ $cellKeys = array();
247
+ while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) {
248
+ $cellKeys[] = $row['id'];
249
+ }
250
+
251
+ return $cellKeys;
252
+ } // function getCellList()
253
+
254
+
255
+ /**
256
+ * Clone the cell collection
257
+ *
258
+ * @param PHPExcel_Worksheet $parent The new worksheet
259
+ * @return void
260
+ */
261
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
262
+ $this->_currentCellIsDirty;
263
+ $this->_storeData();
264
+
265
+ // Get a new id for the new table name
266
+ $tableName = str_replace('.','_',$this->_getUniqueID());
267
+ if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
268
+ AS SELECT * FROM kvp_'.$this->_TableName))
269
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
270
+
271
+ // Copy the existing cell cache file
272
+ $this->_TableName = $tableName;
273
+ } // function copyCellCollection()
274
+
275
+
276
+ /**
277
+ * Clear the cell collection and disconnect from our parent
278
+ *
279
+ * @return void
280
+ */
281
+ public function unsetWorksheetCells() {
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
+ } // function unsetWorksheetCells()
292
+
293
+
294
+ /**
295
+ * Initialise this new cell collection
296
+ *
297
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
298
+ */
299
+ public function __construct(PHPExcel_Worksheet $parent) {
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
+ if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)'))
309
+ throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg());
310
+ }
311
+
312
+ $this->_selectQuery = $this->_DBHandle->prepare("SELECT value FROM kvp_".$this->_TableName." WHERE id = :id");
313
+ $this->_insertQuery = $this->_DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES(:id,:data)");
314
+ $this->_updateQuery = $this->_DBHandle->prepare("UPDATE kvp_".$this->_TableName." SET id=:toId WHERE id=:fromId");
315
+ $this->_deleteQuery = $this->_DBHandle->prepare("DELETE FROM kvp_".$this->_TableName." WHERE id = :id");
316
+ } // function __construct()
317
+
318
+
319
+ /**
320
+ * Destroy this cell collection
321
+ */
322
+ public function __destruct() {
323
+ if (!is_null($this->_DBHandle)) {
324
+ $this->_DBHandle->exec('DROP TABLE kvp_'.$this->_TableName);
325
+ $this->_DBHandle->close();
326
+ }
327
+ $this->_DBHandle = null;
328
+ } // function __destruct()
329
+
330
+
331
+ /**
332
+ * Identify whether the caching method is currently available
333
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
334
+ *
335
+ * @return boolean
336
+ */
337
+ public static function cacheMethodIsAvailable() {
338
+ if (!class_exists('SQLite3',FALSE)) {
339
+ return false;
340
+ }
341
+
342
+ return true;
343
+ }
344
+
345
+ }
libraries/PHPExcel/CachedObjectStorage/Wincache.php ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_CachedObjectStorage
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CachedObjectStorage_Wincache
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_CachedObjectStorage
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CachedObjectStorage_Wincache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache {
37
+
38
+ /**
39
+ * Prefix used to uniquely identify cache data for this worksheet
40
+ *
41
+ * @var string
42
+ */
43
+ private $_cachePrefix = null;
44
+
45
+ /**
46
+ * Cache timeout
47
+ *
48
+ * @var integer
49
+ */
50
+ private $_cacheTime = 600;
51
+
52
+
53
+ /**
54
+ * Store cell data in cache for the current cell object if it's "dirty",
55
+ * and the 'nullify' the current cell object
56
+ *
57
+ * @return void
58
+ * @throws PHPExcel_Exception
59
+ */
60
+ protected function _storeData() {
61
+ if ($this->_currentCellIsDirty && !empty($this->_currentObjectID)) {
62
+ $this->_currentObject->detach();
63
+
64
+ $obj = serialize($this->_currentObject);
65
+ if (wincache_ucache_exists($this->_cachePrefix.$this->_currentObjectID.'.cache')) {
66
+ if (!wincache_ucache_set($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
67
+ $this->__destruct();
68
+ throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
69
+ }
70
+ } else {
71
+ if (!wincache_ucache_add($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) {
72
+ $this->__destruct();
73
+ throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache');
74
+ }
75
+ }
76
+ $this->_currentCellIsDirty = false;
77
+ }
78
+
79
+ $this->_currentObjectID = $this->_currentObject = null;
80
+ } // function _storeData()
81
+
82
+
83
+ /**
84
+ * Add or Update a cell in cache identified by coordinate address
85
+ *
86
+ * @param string $pCoord Coordinate address of the cell to update
87
+ * @param PHPExcel_Cell $cell Cell to update
88
+ * @return PHPExcel_Cell
89
+ * @throws PHPExcel_Exception
90
+ */
91
+ public function addCacheData($pCoord, PHPExcel_Cell $cell) {
92
+ if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) {
93
+ $this->_storeData();
94
+ }
95
+ $this->_cellCache[$pCoord] = true;
96
+
97
+ $this->_currentObjectID = $pCoord;
98
+ $this->_currentObject = $cell;
99
+ $this->_currentCellIsDirty = true;
100
+
101
+ return $cell;
102
+ } // function addCacheData()
103
+
104
+
105
+ /**
106
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
107
+ *
108
+ * @param string $pCoord Coordinate address of the cell to check
109
+ * @return boolean
110
+ */
111
+ public function isDataSet($pCoord) {
112
+ // Check if the requested entry is the current object, or exists in the cache
113
+ if (parent::isDataSet($pCoord)) {
114
+ if ($this->_currentObjectID == $pCoord) {
115
+ return true;
116
+ }
117
+ // Check if the requested entry still exists in cache
118
+ $success = wincache_ucache_exists($this->_cachePrefix.$pCoord.'.cache');
119
+ if ($success === false) {
120
+ // Entry no longer exists in Wincache, so clear it from the cache array
121
+ parent::deleteCacheData($pCoord);
122
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
123
+ }
124
+ return true;
125
+ }
126
+ return false;
127
+ } // function isDataSet()
128
+
129
+
130
+ /**
131
+ * Get cell at a specific coordinate
132
+ *
133
+ * @param string $pCoord Coordinate of the cell
134
+ * @throws PHPExcel_Exception
135
+ * @return PHPExcel_Cell Cell that was found, or null if not found
136
+ */
137
+ public function getCacheData($pCoord) {
138
+ if ($pCoord === $this->_currentObjectID) {
139
+ return $this->_currentObject;
140
+ }
141
+ $this->_storeData();
142
+
143
+ // Check if the entry that has been requested actually exists
144
+ $obj = null;
145
+ if (parent::isDataSet($pCoord)) {
146
+ $success = false;
147
+ $obj = wincache_ucache_get($this->_cachePrefix.$pCoord.'.cache', $success);
148
+ if ($success === false) {
149
+ // Entry no longer exists in WinCache, so clear it from the cache array
150
+ parent::deleteCacheData($pCoord);
151
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
152
+ }
153
+ } else {
154
+ // Return null if requested entry doesn't exist in cache
155
+ return null;
156
+ }
157
+
158
+ // Set current entry to the requested entry
159
+ $this->_currentObjectID = $pCoord;
160
+ $this->_currentObject = unserialize($obj);
161
+ // Re-attach this as the cell's parent
162
+ $this->_currentObject->attach($this);
163
+
164
+ // Return requested entry
165
+ return $this->_currentObject;
166
+ } // function getCacheData()
167
+
168
+
169
+ /**
170
+ * Get a list of all cell addresses currently held in cache
171
+ *
172
+ * @return string[]
173
+ */
174
+ public function getCellList() {
175
+ if ($this->_currentObjectID !== null) {
176
+ $this->_storeData();
177
+ }
178
+
179
+ return parent::getCellList();
180
+ }
181
+
182
+
183
+ /**
184
+ * Delete a cell in cache identified by coordinate address
185
+ *
186
+ * @param string $pCoord Coordinate address of the cell to delete
187
+ * @throws PHPExcel_Exception
188
+ */
189
+ public function deleteCacheData($pCoord) {
190
+ // Delete the entry from Wincache
191
+ wincache_ucache_delete($this->_cachePrefix.$pCoord.'.cache');
192
+
193
+ // Delete the entry from our cell address array
194
+ parent::deleteCacheData($pCoord);
195
+ } // function deleteCacheData()
196
+
197
+
198
+ /**
199
+ * Clone the cell collection
200
+ *
201
+ * @param PHPExcel_Worksheet $parent The new worksheet
202
+ * @return void
203
+ */
204
+ public function copyCellCollection(PHPExcel_Worksheet $parent) {
205
+ parent::copyCellCollection($parent);
206
+ // Get a new id for the new file name
207
+ $baseUnique = $this->_getUniqueID();
208
+ $newCachePrefix = substr(md5($baseUnique),0,8).'.';
209
+ $cacheList = $this->getCellList();
210
+ foreach($cacheList as $cellID) {
211
+ if ($cellID != $this->_currentObjectID) {
212
+ $success = false;
213
+ $obj = wincache_ucache_get($this->_cachePrefix.$cellID.'.cache', $success);
214
+ if ($success === false) {
215
+ // Entry no longer exists in WinCache, so clear it from the cache array
216
+ parent::deleteCacheData($cellID);
217
+ throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in Wincache');
218
+ }
219
+ if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->_cacheTime)) {
220
+ $this->__destruct();
221
+ throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in Wincache');
222
+ }
223
+ }
224
+ }
225
+ $this->_cachePrefix = $newCachePrefix;
226
+ } // function copyCellCollection()
227
+
228
+
229
+ /**
230
+ * Clear the cell collection and disconnect from our parent
231
+ *
232
+ * @return void
233
+ */
234
+ public function unsetWorksheetCells() {
235
+ if(!is_null($this->_currentObject)) {
236
+ $this->_currentObject->detach();
237
+ $this->_currentObject = $this->_currentObjectID = null;
238
+ }
239
+
240
+ // Flush the WinCache cache
241
+ $this->__destruct();
242
+
243
+ $this->_cellCache = array();
244
+
245
+ // detach ourself from the worksheet, so that it can then delete this object successfully
246
+ $this->_parent = null;
247
+ } // function unsetWorksheetCells()
248
+
249
+
250
+ /**
251
+ * Initialise this new cell collection
252
+ *
253
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
254
+ * @param array of mixed $arguments Additional initialisation arguments
255
+ */
256
+ public function __construct(PHPExcel_Worksheet $parent, $arguments) {
257
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
258
+
259
+ if (is_null($this->_cachePrefix)) {
260
+ $baseUnique = $this->_getUniqueID();
261
+ $this->_cachePrefix = substr(md5($baseUnique),0,8).'.';
262
+ $this->_cacheTime = $cacheTime;
263
+
264
+ parent::__construct($parent);
265
+ }
266
+ } // function __construct()
267
+
268
+
269
+ /**
270
+ * Destroy this cell collection
271
+ */
272
+ public function __destruct() {
273
+ $cacheList = $this->getCellList();
274
+ foreach($cacheList as $cellID) {
275
+ wincache_ucache_delete($this->_cachePrefix.$cellID.'.cache');
276
+ }
277
+ } // function __destruct()
278
+
279
+
280
+ /**
281
+ * Identify whether the caching method is currently available
282
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
283
+ *
284
+ * @return boolean
285
+ */
286
+ public static function cacheMethodIsAvailable() {
287
+ if (!function_exists('wincache_ucache_add')) {
288
+ return false;
289
+ }
290
+
291
+ return true;
292
+ }
293
+
294
+ }
libraries/PHPExcel/CachedObjectStorageFactory.php ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel
5
+ *
6
+ * Copyright (c) 2006 - 2014 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 - 2014 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
+
29
+
30
+ /**
31
+ * PHPExcel_CachedObjectStorageFactory
32
+ *
33
+ * @category PHPExcel
34
+ * @package PHPExcel_CachedObjectStorage
35
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
36
+ */
37
+ class PHPExcel_CachedObjectStorageFactory
38
+ {
39
+ const cache_in_memory = 'Memory';
40
+ const cache_in_memory_gzip = 'MemoryGZip';
41
+ const cache_in_memory_serialized = 'MemorySerialized';
42
+ const cache_igbinary = 'Igbinary';
43
+ const cache_to_discISAM = 'DiscISAM';
44
+ const cache_to_apc = 'APC';
45
+ const cache_to_memcache = 'Memcache';
46
+ const cache_to_phpTemp = 'PHPTemp';
47
+ const cache_to_wincache = 'Wincache';
48
+ const cache_to_sqlite = 'SQLite';
49
+ const cache_to_sqlite3 = 'SQLite3';
50
+
51
+
52
+ /**
53
+ * Name of the method used for cell cacheing
54
+ *
55
+ * @var string
56
+ */
57
+ private static $_cacheStorageMethod = NULL;
58
+
59
+ /**
60
+ * Name of the class used for cell cacheing
61
+ *
62
+ * @var string
63
+ */
64
+ private static $_cacheStorageClass = NULL;
65
+
66
+
67
+ /**
68
+ * List of all possible cache storage methods
69
+ *
70
+ * @var string[]
71
+ */
72
+ private static $_storageMethods = array(
73
+ self::cache_in_memory,
74
+ self::cache_in_memory_gzip,
75
+ self::cache_in_memory_serialized,
76
+ self::cache_igbinary,
77
+ self::cache_to_phpTemp,
78
+ self::cache_to_discISAM,
79
+ self::cache_to_apc,
80
+ self::cache_to_memcache,
81
+ self::cache_to_wincache,
82
+ self::cache_to_sqlite,
83
+ self::cache_to_sqlite3,
84
+ );
85
+
86
+
87
+ /**
88
+ * Default arguments for each cache storage method
89
+ *
90
+ * @var array of mixed array
91
+ */
92
+ private static $_storageMethodDefaultParameters = array(
93
+ self::cache_in_memory => array(
94
+ ),
95
+ self::cache_in_memory_gzip => array(
96
+ ),
97
+ self::cache_in_memory_serialized => array(
98
+ ),
99
+ self::cache_igbinary => array(
100
+ ),
101
+ self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB'
102
+ ),
103
+ self::cache_to_discISAM => array( 'dir' => NULL
104
+ ),
105
+ self::cache_to_apc => array( 'cacheTime' => 600
106
+ ),
107
+ self::cache_to_memcache => array( 'memcacheServer' => 'localhost',
108
+ 'memcachePort' => 11211,
109
+ 'cacheTime' => 600
110
+ ),
111
+ self::cache_to_wincache => array( 'cacheTime' => 600
112
+ ),
113
+ self::cache_to_sqlite => array(
114
+ ),
115
+ self::cache_to_sqlite3 => array(
116
+ ),
117
+ );
118
+
119
+
120
+ /**
121
+ * Arguments for the active cache storage method
122
+ *
123
+ * @var array of mixed array
124
+ */
125
+ private static $_storageMethodParameters = array();
126
+
127
+
128
+ /**
129
+ * Return the current cache storage method
130
+ *
131
+ * @return string|NULL
132
+ **/
133
+ public static function getCacheStorageMethod()
134
+ {
135
+ return self::$_cacheStorageMethod;
136
+ } // function getCacheStorageMethod()
137
+
138
+
139
+ /**
140
+ * Return the current cache storage class
141
+ *
142
+ * @return PHPExcel_CachedObjectStorage_ICache|NULL
143
+ **/
144
+ public static function getCacheStorageClass()
145
+ {
146
+ return self::$_cacheStorageClass;
147
+ } // function getCacheStorageClass()
148
+
149
+
150
+ /**
151
+ * Return the list of all possible cache storage methods
152
+ *
153
+ * @return string[]
154
+ **/
155
+ public static function getAllCacheStorageMethods()
156
+ {
157
+ return self::$_storageMethods;
158
+ } // function getCacheStorageMethods()
159
+
160
+
161
+ /**
162
+ * Return the list of all available cache storage methods
163
+ *
164
+ * @return string[]
165
+ **/
166
+ public static function getCacheStorageMethods()
167
+ {
168
+ $activeMethods = array();
169
+ foreach(self::$_storageMethods as $storageMethod) {
170
+ $cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $storageMethod;
171
+ if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) {
172
+ $activeMethods[] = $storageMethod;
173
+ }
174
+ }
175
+ return $activeMethods;
176
+ } // function getCacheStorageMethods()
177
+
178
+
179
+ /**
180
+ * Identify the cache storage method to use
181
+ *
182
+ * @param string $method Name of the method to use for cell cacheing
183
+ * @param array of mixed $arguments Additional arguments to pass to the cell caching class
184
+ * when instantiating
185
+ * @return boolean
186
+ **/
187
+ public static function initialize($method = self::cache_in_memory, $arguments = array())
188
+ {
189
+ if (!in_array($method,self::$_storageMethods)) {
190
+ return FALSE;
191
+ }
192
+
193
+ $cacheStorageClass = 'PHPExcel_CachedObjectStorage_'.$method;
194
+ if (!call_user_func(array( $cacheStorageClass,
195
+ 'cacheMethodIsAvailable'))) {
196
+ return FALSE;
197
+ }
198
+
199
+ self::$_storageMethodParameters[$method] = self::$_storageMethodDefaultParameters[$method];
200
+ foreach($arguments as $k => $v) {
201
+ if (array_key_exists($k, self::$_storageMethodParameters[$method])) {
202
+ self::$_storageMethodParameters[$method][$k] = $v;
203
+ }
204
+ }
205
+
206
+ if (self::$_cacheStorageMethod === NULL) {
207
+ self::$_cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $method;
208
+ self::$_cacheStorageMethod = $method;
209
+ }
210
+ return TRUE;
211
+ } // function initialize()
212
+
213
+
214
+ /**
215
+ * Initialise the cache storage
216
+ *
217
+ * @param PHPExcel_Worksheet $parent Enable cell caching for this worksheet
218
+ * @return PHPExcel_CachedObjectStorage_ICache
219
+ **/
220
+ public static function getInstance(PHPExcel_Worksheet $parent)
221
+ {
222
+ $cacheMethodIsAvailable = TRUE;
223
+ if (self::$_cacheStorageMethod === NULL) {
224
+ $cacheMethodIsAvailable = self::initialize();
225
+ }
226
+
227
+ if ($cacheMethodIsAvailable) {
228
+ $instance = new self::$_cacheStorageClass( $parent,
229
+ self::$_storageMethodParameters[self::$_cacheStorageMethod]
230
+ );
231
+ if ($instance !== NULL) {
232
+ return $instance;
233
+ }
234
+ }
235
+
236
+ return FALSE;
237
+ } // function getInstance()
238
+
239
+
240
+ /**
241
+ * Clear the cache storage
242
+ *
243
+ **/
244
+ public static function finalize()
245
+ {
246
+ self::$_cacheStorageMethod = NULL;
247
+ self::$_cacheStorageClass = NULL;
248
+ self::$_storageMethodParameters = array();
249
+ }
250
+
251
+ }
libraries/PHPExcel/CalcEngine/CyclicReferenceStack.php ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_CalcEngine_CyclicReferenceStack
31
+ *
32
+ * @category PHPExcel_CalcEngine_CyclicReferenceStack
33
+ * @package PHPExcel_Calculation
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_CalcEngine_CyclicReferenceStack {
37
+
38
+ /**
39
+ * The call stack for calculated cells
40
+ *
41
+ * @var mixed[]
42
+ */
43
+ private $_stack = array();
44
+
45
+
46
+ /**
47
+ * Return the number of entries on the stack
48
+ *
49
+ * @return integer
50
+ */
51
+ public function count() {
52
+ return count($this->_stack);
53
+ }
54
+
55
+ /**
56
+ * Push a new entry onto the stack
57
+ *
58
+ * @param mixed $value
59
+ */
60
+ public function push($value) {
61
+ $this->_stack[$value] = $value;
62
+ }
63
+
64
+ /**
65
+ * Pop the last entry from the stack
66
+ *
67
+ * @return mixed
68
+ */
69
+ public function pop() {
70
+ return array_pop($this->_stack);
71
+ }
72
+
73
+ /**
74
+ * Test to see if a specified entry exists on the stack
75
+ *
76
+ * @param mixed $value The value to test
77
+ */
78
+ public function onStack($value) {
79
+ return isset($this->_stack[$value]);
80
+ }
81
+
82
+ /**
83
+ * Clear the stack
84
+ */
85
+ public function clear() {
86
+ $this->_stack = array();
87
+ }
88
+
89
+ /**
90
+ * Return an array of all entries on the stack
91
+ *
92
+ * @return mixed[]
93
+ */
94
+ public function showStack() {
95
+ return $this->_stack;
96
+ }
97
+
98
+ }
libraries/PHPExcel/CalcEngine/Logger.php ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+ /**
29
+ * PHPExcel_CalcEngine_Logger
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ */
35
+ class PHPExcel_CalcEngine_Logger {
36
+
37
+ /**
38
+ * Flag to determine whether a debug log should be generated by the calculation engine
39
+ * If true, then a debug log will be generated
40
+ * If false, then a debug log will not be generated
41
+ *
42
+ * @var boolean
43
+ */
44
+ private $_writeDebugLog = FALSE;
45
+
46
+ /**
47
+ * Flag to determine whether a debug log should be echoed by the calculation engine
48
+ * If true, then a debug log will be echoed
49
+ * If false, then a debug log will not be echoed
50
+ * A debug log can only be echoed if it is generated
51
+ *
52
+ * @var boolean
53
+ */
54
+ private $_echoDebugLog = FALSE;
55
+
56
+ /**
57
+ * The debug log generated by the calculation engine
58
+ *
59
+ * @var string[]
60
+ */
61
+ private $_debugLog = array();
62
+
63
+ /**
64
+ * The calculation engine cell reference stack
65
+ *
66
+ * @var PHPExcel_CalcEngine_CyclicReferenceStack
67
+ */
68
+ private $_cellStack;
69
+
70
+
71
+ /**
72
+ * Instantiate a Calculation engine logger
73
+ *
74
+ * @param PHPExcel_CalcEngine_CyclicReferenceStack $stack
75
+ */
76
+ public function __construct(PHPExcel_CalcEngine_CyclicReferenceStack $stack) {
77
+ $this->_cellStack = $stack;
78
+ }
79
+
80
+ /**
81
+ * Enable/Disable Calculation engine logging
82
+ *
83
+ * @param boolean $pValue
84
+ */
85
+ public function setWriteDebugLog($pValue = FALSE) {
86
+ $this->_writeDebugLog = $pValue;
87
+ }
88
+
89
+ /**
90
+ * Return whether calculation engine logging is enabled or disabled
91
+ *
92
+ * @return boolean
93
+ */
94
+ public function getWriteDebugLog() {
95
+ return $this->_writeDebugLog;
96
+ }
97
+
98
+ /**
99
+ * Enable/Disable echoing of debug log information
100
+ *
101
+ * @param boolean $pValue
102
+ */
103
+ public function setEchoDebugLog($pValue = FALSE) {
104
+ $this->_echoDebugLog = $pValue;
105
+ }
106
+
107
+ /**
108
+ * Return whether echoing of debug log information is enabled or disabled
109
+ *
110
+ * @return boolean
111
+ */
112
+ public function getEchoDebugLog() {
113
+ return $this->_echoDebugLog;
114
+ }
115
+
116
+ /**
117
+ * Write an entry to the calculation engine debug log
118
+ */
119
+ public function writeDebugLog() {
120
+ // Only write the debug log if logging is enabled
121
+ if ($this->_writeDebugLog) {
122
+ $message = implode(func_get_args());
123
+ $cellReference = implode(' -> ', $this->_cellStack->showStack());
124
+ if ($this->_echoDebugLog) {
125
+ echo $cellReference,
126
+ ($this->_cellStack->count() > 0 ? ' => ' : ''),
127
+ $message,
128
+ PHP_EOL;
129
+ }
130
+ $this->_debugLog[] = $cellReference .
131
+ ($this->_cellStack->count() > 0 ? ' => ' : '') .
132
+ $message;
133
+ }
134
+ } // function _writeDebug()
135
+
136
+ /**
137
+ * Clear the calculation engine debug log
138
+ */
139
+ public function clearLog() {
140
+ $this->_debugLog = array();
141
+ } // function flushLogger()
142
+
143
+ /**
144
+ * Return the calculation engine debug log
145
+ *
146
+ * @return string[]
147
+ */
148
+ public function getLog() {
149
+ return $this->_debugLog;
150
+ } // function flushLogger()
151
+
152
+ } // class PHPExcel_CalcEngine_Logger
153
+
libraries/PHPExcel/Calculation.php ADDED
@@ -0,0 +1,3952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ if (!defined('CALCULATION_REGEXP_CELLREF')) {
40
+ // Test for support of \P (multibyte options) in PCRE
41
+ if(defined('PREG_BAD_UTF8_ERROR')) {
42
+ // Cell reference (cell or range of cells, with or without a sheet reference)
43
+ define('CALCULATION_REGEXP_CELLREF','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})');
44
+ // Named Range of cells
45
+ define('CALCULATION_REGEXP_NAMEDRANGE','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)');
46
+ } else {
47
+ // Cell reference (cell or range of cells, with or without a sheet reference)
48
+ define('CALCULATION_REGEXP_CELLREF','(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)');
49
+ // Named Range of cells
50
+ define('CALCULATION_REGEXP_NAMEDRANGE','(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)');
51
+ }
52
+ }
53
+
54
+
55
+ /**
56
+ * PHPExcel_Calculation (Multiton)
57
+ *
58
+ * @category PHPExcel
59
+ * @package PHPExcel_Calculation
60
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
61
+ */
62
+ class PHPExcel_Calculation {
63
+
64
+ /** Constants */
65
+ /** Regular Expressions */
66
+ // Numeric operand
67
+ const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
68
+ // String operand
69
+ const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
70
+ // Opening bracket
71
+ const CALCULATION_REGEXP_OPENBRACE = '\(';
72
+ // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
73
+ const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\(';
74
+ // Cell reference (cell or range of cells, with or without a sheet reference)
75
+ const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF;
76
+ // Named Range of cells
77
+ const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE;
78
+ // Error
79
+ const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
80
+
81
+
82
+ /** constants */
83
+ const RETURN_ARRAY_AS_ERROR = 'error';
84
+ const RETURN_ARRAY_AS_VALUE = 'value';
85
+ const RETURN_ARRAY_AS_ARRAY = 'array';
86
+
87
+ private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
88
+
89
+
90
+ /**
91
+ * Instance of this class
92
+ *
93
+ * @access private
94
+ * @var PHPExcel_Calculation
95
+ */
96
+ private static $_instance;
97
+
98
+
99
+ /**
100
+ * Instance of the workbook this Calculation Engine is using
101
+ *
102
+ * @access private
103
+ * @var PHPExcel
104
+ */
105
+ private $_workbook;
106
+
107
+ /**
108
+ * List of instances of the calculation engine that we've instantiated for individual workbooks
109
+ *
110
+ * @access private
111
+ * @var PHPExcel_Calculation[]
112
+ */
113
+ private static $_workbookSets;
114
+
115
+ /**
116
+ * Calculation cache
117
+ *
118
+ * @access private
119
+ * @var array
120
+ */
121
+ private $_calculationCache = array ();
122
+
123
+
124
+ /**
125
+ * Calculation cache enabled
126
+ *
127
+ * @access private
128
+ * @var boolean
129
+ */
130
+ private $_calculationCacheEnabled = TRUE;
131
+
132
+
133
+ /**
134
+ * List of operators that can be used within formulae
135
+ * The true/false value indicates whether it is a binary operator or a unary operator
136
+ *
137
+ * @access private
138
+ * @var array
139
+ */
140
+ private static $_operators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
141
+ '^' => TRUE, '&' => TRUE, '%' => FALSE, '~' => FALSE,
142
+ '>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE,
143
+ '<=' => TRUE, '<>' => TRUE, '|' => TRUE, ':' => TRUE
144
+ );
145
+
146
+
147
+ /**
148
+ * List of binary operators (those that expect two operands)
149
+ *
150
+ * @access private
151
+ * @var array
152
+ */
153
+ private static $_binaryOperators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE,
154
+ '^' => TRUE, '&' => TRUE, '>' => TRUE, '<' => TRUE,
155
+ '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE,
156
+ '|' => TRUE, ':' => TRUE
157
+ );
158
+
159
+ /**
160
+ * The debug log generated by the calculation engine
161
+ *
162
+ * @access private
163
+ * @var PHPExcel_CalcEngine_Logger
164
+ *
165
+ */
166
+ private $debugLog;
167
+
168
+ /**
169
+ * Flag to determine how formula errors should be handled
170
+ * If true, then a user error will be triggered
171
+ * If false, then an exception will be thrown
172
+ *
173
+ * @access public
174
+ * @var boolean
175
+ *
176
+ */
177
+ public $suppressFormulaErrors = FALSE;
178
+
179
+ /**
180
+ * Error message for any error that was raised/thrown by the calculation engine
181
+ *
182
+ * @access public
183
+ * @var string
184
+ *
185
+ */
186
+ public $formulaError = NULL;
187
+
188
+ /**
189
+ * An array of the nested cell references accessed by the calculation engine, used for the debug log
190
+ *
191
+ * @access private
192
+ * @var array of string
193
+ *
194
+ */
195
+ private $_cyclicReferenceStack;
196
+
197
+ private $_cellStack = array();
198
+
199
+ /**
200
+ * Current iteration counter for cyclic formulae
201
+ * If the value is 0 (or less) then cyclic formulae will throw an exception,
202
+ * otherwise they will iterate to the limit defined here before returning a result
203
+ *
204
+ * @var integer
205
+ *
206
+ */
207
+ private $_cyclicFormulaCount = 1;
208
+
209
+ private $_cyclicFormulaCell = '';
210
+
211
+ /**
212
+ * Number of iterations for cyclic formulae
213
+ *
214
+ * @var integer
215
+ *
216
+ */
217
+ public $cyclicFormulaCount = 1;
218
+
219
+ /**
220
+ * Precision used for calculations
221
+ *
222
+ * @var integer
223
+ *
224
+ */
225
+ private $_savedPrecision = 14;
226
+
227
+
228
+ /**
229
+ * The current locale setting
230
+ *
231
+ * @var string
232
+ *
233
+ */
234
+ private static $_localeLanguage = 'en_us'; // US English (default locale)
235
+
236
+ /**
237
+ * List of available locale settings
238
+ * Note that this is read for the locale subdirectory only when requested
239
+ *
240
+ * @var string[]
241
+ *
242
+ */
243
+ private static $_validLocaleLanguages = array( 'en' // English (default language)
244
+ );
245
+ /**
246
+ * Locale-specific argument separator for function arguments
247
+ *
248
+ * @var string
249
+ *
250
+ */
251
+ private static $_localeArgumentSeparator = ',';
252
+ private static $_localeFunctions = array();
253
+
254
+ /**
255
+ * Locale-specific translations for Excel constants (True, False and Null)
256
+ *
257
+ * @var string[]
258
+ *
259
+ */
260
+ public static $_localeBoolean = array( 'TRUE' => 'TRUE',
261
+ 'FALSE' => 'FALSE',
262
+ 'NULL' => 'NULL'
263
+ );
264
+
265
+
266
+ /**
267
+ * Excel constant string translations to their PHP equivalents
268
+ * Constant conversion from text name/value to actual (datatyped) value
269
+ *
270
+ * @var string[]
271
+ *
272
+ */
273
+ private static $_ExcelConstants = array('TRUE' => TRUE,
274
+ 'FALSE' => FALSE,
275
+ 'NULL' => NULL
276
+ );
277
+
278
+ // PHPExcel functions
279
+ private static $_PHPExcelFunctions = array( // PHPExcel functions
280
+ 'ABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
281
+ 'functionCall' => 'abs',
282
+ 'argumentCount' => '1'
283
+ ),
284
+ 'ACCRINT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
285
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINT',
286
+ 'argumentCount' => '4-7'
287
+ ),
288
+ 'ACCRINTM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
289
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINTM',
290
+ 'argumentCount' => '3-5'
291
+ ),
292
+ 'ACOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
293
+ 'functionCall' => 'acos',
294
+ 'argumentCount' => '1'
295
+ ),
296
+ 'ACOSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
297
+ 'functionCall' => 'acosh',
298
+ 'argumentCount' => '1'
299
+ ),
300
+ 'ADDRESS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
301
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::CELL_ADDRESS',
302
+ 'argumentCount' => '2-5'
303
+ ),
304
+ 'AMORDEGRC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
305
+ 'functionCall' => 'PHPExcel_Calculation_Financial::AMORDEGRC',
306
+ 'argumentCount' => '6,7'
307
+ ),
308
+ 'AMORLINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
309
+ 'functionCall' => 'PHPExcel_Calculation_Financial::AMORLINC',
310
+ 'argumentCount' => '6,7'
311
+ ),
312
+ 'AND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
313
+ 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_AND',
314
+ 'argumentCount' => '1+'
315
+ ),
316
+ 'AREAS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
317
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
318
+ 'argumentCount' => '1'
319
+ ),
320
+ 'ASC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
321
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
322
+ 'argumentCount' => '1'
323
+ ),
324
+ 'ASIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
325
+ 'functionCall' => 'asin',
326
+ 'argumentCount' => '1'
327
+ ),
328
+ 'ASINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
329
+ 'functionCall' => 'asinh',
330
+ 'argumentCount' => '1'
331
+ ),
332
+ 'ATAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
333
+ 'functionCall' => 'atan',
334
+ 'argumentCount' => '1'
335
+ ),
336
+ 'ATAN2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
337
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ATAN2',
338
+ 'argumentCount' => '2'
339
+ ),
340
+ 'ATANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
341
+ 'functionCall' => 'atanh',
342
+ 'argumentCount' => '1'
343
+ ),
344
+ 'AVEDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
345
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVEDEV',
346
+ 'argumentCount' => '1+'
347
+ ),
348
+ 'AVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
349
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGE',
350
+ 'argumentCount' => '1+'
351
+ ),
352
+ 'AVERAGEA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
353
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEA',
354
+ 'argumentCount' => '1+'
355
+ ),
356
+ 'AVERAGEIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
357
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEIF',
358
+ 'argumentCount' => '2,3'
359
+ ),
360
+ 'AVERAGEIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
361
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
362
+ 'argumentCount' => '3+'
363
+ ),
364
+ 'BAHTTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
365
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
366
+ 'argumentCount' => '1'
367
+ ),
368
+ 'BESSELI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
369
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELI',
370
+ 'argumentCount' => '2'
371
+ ),
372
+ 'BESSELJ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
373
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELJ',
374
+ 'argumentCount' => '2'
375
+ ),
376
+ 'BESSELK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
377
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELK',
378
+ 'argumentCount' => '2'
379
+ ),
380
+ 'BESSELY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
381
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELY',
382
+ 'argumentCount' => '2'
383
+ ),
384
+ 'BETADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
385
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BETADIST',
386
+ 'argumentCount' => '3-5'
387
+ ),
388
+ 'BETAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
389
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BETAINV',
390
+ 'argumentCount' => '3-5'
391
+ ),
392
+ 'BIN2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
393
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTODEC',
394
+ 'argumentCount' => '1'
395
+ ),
396
+ 'BIN2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
397
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOHEX',
398
+ 'argumentCount' => '1,2'
399
+ ),
400
+ 'BIN2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
401
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOOCT',
402
+ 'argumentCount' => '1,2'
403
+ ),
404
+ 'BINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
405
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BINOMDIST',
406
+ 'argumentCount' => '4'
407
+ ),
408
+ 'CEILING' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
409
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::CEILING',
410
+ 'argumentCount' => '2'
411
+ ),
412
+ 'CELL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
413
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
414
+ 'argumentCount' => '1,2'
415
+ ),
416
+ 'CHAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
417
+ 'functionCall' => 'PHPExcel_Calculation_TextData::CHARACTER',
418
+ 'argumentCount' => '1'
419
+ ),
420
+ 'CHIDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
421
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIDIST',
422
+ 'argumentCount' => '2'
423
+ ),
424
+ 'CHIINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
425
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIINV',
426
+ 'argumentCount' => '2'
427
+ ),
428
+ 'CHITEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
429
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
430
+ 'argumentCount' => '2'
431
+ ),
432
+ 'CHOOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
433
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::CHOOSE',
434
+ 'argumentCount' => '2+'
435
+ ),
436
+ 'CLEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
437
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMNONPRINTABLE',
438
+ 'argumentCount' => '1'
439
+ ),
440
+ 'CODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
441
+ 'functionCall' => 'PHPExcel_Calculation_TextData::ASCIICODE',
442
+ 'argumentCount' => '1'
443
+ ),
444
+ 'COLUMN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
445
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMN',
446
+ 'argumentCount' => '-1',
447
+ 'passByReference' => array(TRUE)
448
+ ),
449
+ 'COLUMNS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
450
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMNS',
451
+ 'argumentCount' => '1'
452
+ ),
453
+ 'COMBIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
454
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::COMBIN',
455
+ 'argumentCount' => '2'
456
+ ),
457
+ 'COMPLEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
458
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::COMPLEX',
459
+ 'argumentCount' => '2,3'
460
+ ),
461
+ 'CONCATENATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
462
+ 'functionCall' => 'PHPExcel_Calculation_TextData::CONCATENATE',
463
+ 'argumentCount' => '1+'
464
+ ),
465
+ 'CONFIDENCE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
466
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CONFIDENCE',
467
+ 'argumentCount' => '3'
468
+ ),
469
+ 'CONVERT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
470
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::CONVERTUOM',
471
+ 'argumentCount' => '3'
472
+ ),
473
+ 'CORREL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
474
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
475
+ 'argumentCount' => '2'
476
+ ),
477
+ 'COS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
478
+ 'functionCall' => 'cos',
479
+ 'argumentCount' => '1'
480
+ ),
481
+ 'COSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
482
+ 'functionCall' => 'cosh',
483
+ 'argumentCount' => '1'
484
+ ),
485
+ 'COUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
486
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNT',
487
+ 'argumentCount' => '1+'
488
+ ),
489
+ 'COUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
490
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTA',
491
+ 'argumentCount' => '1+'
492
+ ),
493
+ 'COUNTBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
494
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTBLANK',
495
+ 'argumentCount' => '1'
496
+ ),
497
+ 'COUNTIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
498
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTIF',
499
+ 'argumentCount' => '2'
500
+ ),
501
+ 'COUNTIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
502
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
503
+ 'argumentCount' => '2'
504
+ ),
505
+ 'COUPDAYBS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
506
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYBS',
507
+ 'argumentCount' => '3,4'
508
+ ),
509
+ 'COUPDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
510
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYS',
511
+ 'argumentCount' => '3,4'
512
+ ),
513
+ 'COUPDAYSNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
514
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYSNC',
515
+ 'argumentCount' => '3,4'
516
+ ),
517
+ 'COUPNCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
518
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNCD',
519
+ 'argumentCount' => '3,4'
520
+ ),
521
+ 'COUPNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
522
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNUM',
523
+ 'argumentCount' => '3,4'
524
+ ),
525
+ 'COUPPCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
526
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPPCD',
527
+ 'argumentCount' => '3,4'
528
+ ),
529
+ 'COVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
530
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COVAR',
531
+ 'argumentCount' => '2'
532
+ ),
533
+ 'CRITBINOM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
534
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CRITBINOM',
535
+ 'argumentCount' => '3'
536
+ ),
537
+ 'CUBEKPIMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
538
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
539
+ 'argumentCount' => '?'
540
+ ),
541
+ 'CUBEMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
542
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
543
+ 'argumentCount' => '?'
544
+ ),
545
+ 'CUBEMEMBERPROPERTY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
546
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
547
+ 'argumentCount' => '?'
548
+ ),
549
+ 'CUBERANKEDMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
550
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
551
+ 'argumentCount' => '?'
552
+ ),
553
+ 'CUBESET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
554
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
555
+ 'argumentCount' => '?'
556
+ ),
557
+ 'CUBESETCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
558
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
559
+ 'argumentCount' => '?'
560
+ ),
561
+ 'CUBEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
562
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
563
+ 'argumentCount' => '?'
564
+ ),
565
+ 'CUMIPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
566
+ 'functionCall' => 'PHPExcel_Calculation_Financial::CUMIPMT',
567
+ 'argumentCount' => '6'
568
+ ),
569
+ 'CUMPRINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
570
+ 'functionCall' => 'PHPExcel_Calculation_Financial::CUMPRINC',
571
+ 'argumentCount' => '6'
572
+ ),
573
+ 'DATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
574
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATE',
575
+ 'argumentCount' => '3'
576
+ ),
577
+ 'DATEDIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
578
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEDIF',
579
+ 'argumentCount' => '2,3'
580
+ ),
581
+ 'DATEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
582
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEVALUE',
583
+ 'argumentCount' => '1'
584
+ ),
585
+ 'DAVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
586
+ 'functionCall' => 'PHPExcel_Calculation_Database::DAVERAGE',
587
+ 'argumentCount' => '3'
588
+ ),
589
+ 'DAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
590
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFMONTH',
591
+ 'argumentCount' => '1'
592
+ ),
593
+ 'DAYS360' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
594
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYS360',
595
+ 'argumentCount' => '2,3'
596
+ ),
597
+ 'DB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
598
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DB',
599
+ 'argumentCount' => '4,5'
600
+ ),
601
+ 'DCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
602
+ 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNT',
603
+ 'argumentCount' => '3'
604
+ ),
605
+ 'DCOUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
606
+ 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNTA',
607
+ 'argumentCount' => '3'
608
+ ),
609
+ 'DDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
610
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DDB',
611
+ 'argumentCount' => '4,5'
612
+ ),
613
+ 'DEC2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
614
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOBIN',
615
+ 'argumentCount' => '1,2'
616
+ ),
617
+ 'DEC2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
618
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOHEX',
619
+ 'argumentCount' => '1,2'
620
+ ),
621
+ 'DEC2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
622
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOOCT',
623
+ 'argumentCount' => '1,2'
624
+ ),
625
+ 'DEGREES' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
626
+ 'functionCall' => 'rad2deg',
627
+ 'argumentCount' => '1'
628
+ ),
629
+ 'DELTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
630
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DELTA',
631
+ 'argumentCount' => '1,2'
632
+ ),
633
+ 'DEVSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
634
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::DEVSQ',
635
+ 'argumentCount' => '1+'
636
+ ),
637
+ 'DGET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
638
+ 'functionCall' => 'PHPExcel_Calculation_Database::DGET',
639
+ 'argumentCount' => '3'
640
+ ),
641
+ 'DISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
642
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DISC',
643
+ 'argumentCount' => '4,5'
644
+ ),
645
+ 'DMAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
646
+ 'functionCall' => 'PHPExcel_Calculation_Database::DMAX',
647
+ 'argumentCount' => '3'
648
+ ),
649
+ 'DMIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
650
+ 'functionCall' => 'PHPExcel_Calculation_Database::DMIN',
651
+ 'argumentCount' => '3'
652
+ ),
653
+ 'DOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
654
+ 'functionCall' => 'PHPExcel_Calculation_TextData::DOLLAR',
655
+ 'argumentCount' => '1,2'
656
+ ),
657
+ 'DOLLARDE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
658
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARDE',
659
+ 'argumentCount' => '2'
660
+ ),
661
+ 'DOLLARFR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
662
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARFR',
663
+ 'argumentCount' => '2'
664
+ ),
665
+ 'DPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
666
+ 'functionCall' => 'PHPExcel_Calculation_Database::DPRODUCT',
667
+ 'argumentCount' => '3'
668
+ ),
669
+ 'DSTDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
670
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEV',
671
+ 'argumentCount' => '3'
672
+ ),
673
+ 'DSTDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
674
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEVP',
675
+ 'argumentCount' => '3'
676
+ ),
677
+ 'DSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
678
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSUM',
679
+ 'argumentCount' => '3'
680
+ ),
681
+ 'DURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
682
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
683
+ 'argumentCount' => '5,6'
684
+ ),
685
+ 'DVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
686
+ 'functionCall' => 'PHPExcel_Calculation_Database::DVAR',
687
+ 'argumentCount' => '3'
688
+ ),
689
+ 'DVARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
690
+ 'functionCall' => 'PHPExcel_Calculation_Database::DVARP',
691
+ 'argumentCount' => '3'
692
+ ),
693
+ 'EDATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
694
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::EDATE',
695
+ 'argumentCount' => '2'
696
+ ),
697
+ 'EFFECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
698
+ 'functionCall' => 'PHPExcel_Calculation_Financial::EFFECT',
699
+ 'argumentCount' => '2'
700
+ ),
701
+ 'EOMONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
702
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::EOMONTH',
703
+ 'argumentCount' => '2'
704
+ ),
705
+ 'ERF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
706
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::ERF',
707
+ 'argumentCount' => '1,2'
708
+ ),
709
+ 'ERFC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
710
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::ERFC',
711
+ 'argumentCount' => '1'
712
+ ),
713
+ 'ERROR.TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
714
+ 'functionCall' => 'PHPExcel_Calculation_Functions::ERROR_TYPE',
715
+ 'argumentCount' => '1'
716
+ ),
717
+ 'EVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
718
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::EVEN',
719
+ 'argumentCount' => '1'
720
+ ),
721
+ 'EXACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
722
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
723
+ 'argumentCount' => '2'
724
+ ),
725
+ 'EXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
726
+ 'functionCall' => 'exp',
727
+ 'argumentCount' => '1'
728
+ ),
729
+ 'EXPONDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
730
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::EXPONDIST',
731
+ 'argumentCount' => '3'
732
+ ),
733
+ 'FACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
734
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACT',
735
+ 'argumentCount' => '1'
736
+ ),
737
+ 'FACTDOUBLE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
738
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACTDOUBLE',
739
+ 'argumentCount' => '1'
740
+ ),
741
+ 'FALSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
742
+ 'functionCall' => 'PHPExcel_Calculation_Logical::FALSE',
743
+ 'argumentCount' => '0'
744
+ ),
745
+ 'FDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
746
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
747
+ 'argumentCount' => '3'
748
+ ),
749
+ 'FIND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
750
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
751
+ 'argumentCount' => '2,3'
752
+ ),
753
+ 'FINDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
754
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
755
+ 'argumentCount' => '2,3'
756
+ ),
757
+ 'FINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
758
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
759
+ 'argumentCount' => '3'
760
+ ),
761
+ 'FISHER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
762
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHER',
763
+ 'argumentCount' => '1'
764
+ ),
765
+ 'FISHERINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
766
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHERINV',
767
+ 'argumentCount' => '1'
768
+ ),
769
+ 'FIXED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
770
+ 'functionCall' => 'PHPExcel_Calculation_TextData::FIXEDFORMAT',
771
+ 'argumentCount' => '1-3'
772
+ ),
773
+ 'FLOOR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
774
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FLOOR',
775
+ 'argumentCount' => '2'
776
+ ),
777
+ 'FORECAST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
778
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FORECAST',
779
+ 'argumentCount' => '3'
780
+ ),
781
+ 'FREQUENCY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
782
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
783
+ 'argumentCount' => '2'
784
+ ),
785
+ 'FTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
786
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
787
+ 'argumentCount' => '2'
788
+ ),
789
+ 'FV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
790
+ 'functionCall' => 'PHPExcel_Calculation_Financial::FV',
791
+ 'argumentCount' => '3-5'
792
+ ),
793
+ 'FVSCHEDULE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
794
+ 'functionCall' => 'PHPExcel_Calculation_Financial::FVSCHEDULE',
795
+ 'argumentCount' => '2'
796
+ ),
797
+ 'GAMMADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
798
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMADIST',
799
+ 'argumentCount' => '4'
800
+ ),
801
+ 'GAMMAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
802
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMAINV',
803
+ 'argumentCount' => '3'
804
+ ),
805
+ 'GAMMALN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
806
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMALN',
807
+ 'argumentCount' => '1'
808
+ ),
809
+ 'GCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
810
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::GCD',
811
+ 'argumentCount' => '1+'
812
+ ),
813
+ 'GEOMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
814
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GEOMEAN',
815
+ 'argumentCount' => '1+'
816
+ ),
817
+ 'GESTEP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
818
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::GESTEP',
819
+ 'argumentCount' => '1,2'
820
+ ),
821
+ 'GETPIVOTDATA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
822
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
823
+ 'argumentCount' => '2+'
824
+ ),
825
+ 'GROWTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
826
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GROWTH',
827
+ 'argumentCount' => '1-4'
828
+ ),
829
+ 'HARMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
830
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::HARMEAN',
831
+ 'argumentCount' => '1+'
832
+ ),
833
+ 'HEX2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
834
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOBIN',
835
+ 'argumentCount' => '1,2'
836
+ ),
837
+ 'HEX2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
838
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTODEC',
839
+ 'argumentCount' => '1'
840
+ ),
841
+ 'HEX2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
842
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOOCT',
843
+ 'argumentCount' => '1,2'
844
+ ),
845
+ 'HLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
846
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::HLOOKUP',
847
+ 'argumentCount' => '3,4'
848
+ ),
849
+ 'HOUR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
850
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::HOUROFDAY',
851
+ 'argumentCount' => '1'
852
+ ),
853
+ 'HYPERLINK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
854
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::HYPERLINK',
855
+ 'argumentCount' => '1,2',
856
+ 'passCellReference'=> TRUE
857
+ ),
858
+ 'HYPGEOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
859
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::HYPGEOMDIST',
860
+ 'argumentCount' => '4'
861
+ ),
862
+ 'IF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
863
+ 'functionCall' => 'PHPExcel_Calculation_Logical::STATEMENT_IF',
864
+ 'argumentCount' => '1-3'
865
+ ),
866
+ 'IFERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
867
+ 'functionCall' => 'PHPExcel_Calculation_Logical::IFERROR',
868
+ 'argumentCount' => '2'
869
+ ),
870
+ 'IMABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
871
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMABS',
872
+ 'argumentCount' => '1'
873
+ ),
874
+ 'IMAGINARY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
875
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMAGINARY',
876
+ 'argumentCount' => '1'
877
+ ),
878
+ 'IMARGUMENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
879
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMARGUMENT',
880
+ 'argumentCount' => '1'
881
+ ),
882
+ 'IMCONJUGATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
883
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCONJUGATE',
884
+ 'argumentCount' => '1'
885
+ ),
886
+ 'IMCOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
887
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCOS',
888
+ 'argumentCount' => '1'
889
+ ),
890
+ 'IMDIV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
891
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMDIV',
892
+ 'argumentCount' => '2'
893
+ ),
894
+ 'IMEXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
895
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMEXP',
896
+ 'argumentCount' => '1'
897
+ ),
898
+ 'IMLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
899
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLN',
900
+ 'argumentCount' => '1'
901
+ ),
902
+ 'IMLOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
903
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG10',
904
+ 'argumentCount' => '1'
905
+ ),
906
+ 'IMLOG2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
907
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG2',
908
+ 'argumentCount' => '1'
909
+ ),
910
+ 'IMPOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
911
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPOWER',
912
+ 'argumentCount' => '2'
913
+ ),
914
+ 'IMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
915
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPRODUCT',
916
+ 'argumentCount' => '1+'
917
+ ),
918
+ 'IMREAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
919
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMREAL',
920
+ 'argumentCount' => '1'
921
+ ),
922
+ 'IMSIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
923
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSIN',
924
+ 'argumentCount' => '1'
925
+ ),
926
+ 'IMSQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
927
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSQRT',
928
+ 'argumentCount' => '1'
929
+ ),
930
+ 'IMSUB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
931
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUB',
932
+ 'argumentCount' => '2'
933
+ ),
934
+ 'IMSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
935
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUM',
936
+ 'argumentCount' => '1+'
937
+ ),
938
+ 'INDEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
939
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDEX',
940
+ 'argumentCount' => '1-4'
941
+ ),
942
+ 'INDIRECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
943
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDIRECT',
944
+ 'argumentCount' => '1,2',
945
+ 'passCellReference'=> TRUE
946
+ ),
947
+ 'INFO' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
948
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
949
+ 'argumentCount' => '1'
950
+ ),
951
+ 'INT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
952
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::INT',
953
+ 'argumentCount' => '1'
954
+ ),
955
+ 'INTERCEPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
956
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::INTERCEPT',
957
+ 'argumentCount' => '2'
958
+ ),
959
+ 'INTRATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
960
+ 'functionCall' => 'PHPExcel_Calculation_Financial::INTRATE',
961
+ 'argumentCount' => '4,5'
962
+ ),
963
+ 'IPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
964
+ 'functionCall' => 'PHPExcel_Calculation_Financial::IPMT',
965
+ 'argumentCount' => '4-6'
966
+ ),
967
+ 'IRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
968
+ 'functionCall' => 'PHPExcel_Calculation_Financial::IRR',
969
+ 'argumentCount' => '1,2'
970
+ ),
971
+ 'ISBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
972
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_BLANK',
973
+ 'argumentCount' => '1'
974
+ ),
975
+ 'ISERR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
976
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERR',
977
+ 'argumentCount' => '1'
978
+ ),
979
+ 'ISERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
980
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERROR',
981
+ 'argumentCount' => '1'
982
+ ),
983
+ 'ISEVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
984
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_EVEN',
985
+ 'argumentCount' => '1'
986
+ ),
987
+ 'ISLOGICAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
988
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_LOGICAL',
989
+ 'argumentCount' => '1'
990
+ ),
991
+ 'ISNA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
992
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NA',
993
+ 'argumentCount' => '1'
994
+ ),
995
+ 'ISNONTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
996
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NONTEXT',
997
+ 'argumentCount' => '1'
998
+ ),
999
+ 'ISNUMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1000
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NUMBER',
1001
+ 'argumentCount' => '1'
1002
+ ),
1003
+ 'ISODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1004
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ODD',
1005
+ 'argumentCount' => '1'
1006
+ ),
1007
+ 'ISPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1008
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ISPMT',
1009
+ 'argumentCount' => '4'
1010
+ ),
1011
+ 'ISREF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1012
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1013
+ 'argumentCount' => '1'
1014
+ ),
1015
+ 'ISTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1016
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_TEXT',
1017
+ 'argumentCount' => '1'
1018
+ ),
1019
+ 'JIS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1020
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1021
+ 'argumentCount' => '1'
1022
+ ),
1023
+ 'KURT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1024
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::KURT',
1025
+ 'argumentCount' => '1+'
1026
+ ),
1027
+ 'LARGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1028
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LARGE',
1029
+ 'argumentCount' => '2'
1030
+ ),
1031
+ 'LCM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1032
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::LCM',
1033
+ 'argumentCount' => '1+'
1034
+ ),
1035
+ 'LEFT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1036
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
1037
+ 'argumentCount' => '1,2'
1038
+ ),
1039
+ 'LEFTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1040
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
1041
+ 'argumentCount' => '1,2'
1042
+ ),
1043
+ 'LEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1044
+ 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
1045
+ 'argumentCount' => '1'
1046
+ ),
1047
+ 'LENB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1048
+ 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
1049
+ 'argumentCount' => '1'
1050
+ ),
1051
+ 'LINEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1052
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LINEST',
1053
+ 'argumentCount' => '1-4'
1054
+ ),
1055
+ 'LN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1056
+ 'functionCall' => 'log',
1057
+ 'argumentCount' => '1'
1058
+ ),
1059
+ 'LOG' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1060
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::LOG_BASE',
1061
+ 'argumentCount' => '1,2'
1062
+ ),
1063
+ 'LOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1064
+ 'functionCall' => 'log10',
1065
+ 'argumentCount' => '1'
1066
+ ),
1067
+ 'LOGEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1068
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGEST',
1069
+ 'argumentCount' => '1-4'
1070
+ ),
1071
+ 'LOGINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1072
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGINV',
1073
+ 'argumentCount' => '3'
1074
+ ),
1075
+ 'LOGNORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1076
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGNORMDIST',
1077
+ 'argumentCount' => '3'
1078
+ ),
1079
+ 'LOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1080
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::LOOKUP',
1081
+ 'argumentCount' => '2,3'
1082
+ ),
1083
+ 'LOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1084
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LOWERCASE',
1085
+ 'argumentCount' => '1'
1086
+ ),
1087
+ 'MATCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1088
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::MATCH',
1089
+ 'argumentCount' => '2,3'
1090
+ ),
1091
+ 'MAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1092
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAX',
1093
+ 'argumentCount' => '1+'
1094
+ ),
1095
+ 'MAXA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1096
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXA',
1097
+ 'argumentCount' => '1+'
1098
+ ),
1099
+ 'MAXIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1100
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXIF',
1101
+ 'argumentCount' => '2+'
1102
+ ),
1103
+ 'MDETERM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1104
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MDETERM',
1105
+ 'argumentCount' => '1'
1106
+ ),
1107
+ 'MDURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1108
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1109
+ 'argumentCount' => '5,6'
1110
+ ),
1111
+ 'MEDIAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1112
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MEDIAN',
1113
+ 'argumentCount' => '1+'
1114
+ ),
1115
+ 'MEDIANIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1116
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1117
+ 'argumentCount' => '2+'
1118
+ ),
1119
+ 'MID' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1120
+ 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
1121
+ 'argumentCount' => '3'
1122
+ ),
1123
+ 'MIDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1124
+ 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
1125
+ 'argumentCount' => '3'
1126
+ ),
1127
+ 'MIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1128
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MIN',
1129
+ 'argumentCount' => '1+'
1130
+ ),
1131
+ 'MINA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1132
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MINA',
1133
+ 'argumentCount' => '1+'
1134
+ ),
1135
+ 'MINIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1136
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MINIF',
1137
+ 'argumentCount' => '2+'
1138
+ ),
1139
+ 'MINUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1140
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::MINUTEOFHOUR',
1141
+ 'argumentCount' => '1'
1142
+ ),
1143
+ 'MINVERSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1144
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MINVERSE',
1145
+ 'argumentCount' => '1'
1146
+ ),
1147
+ 'MIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1148
+ 'functionCall' => 'PHPExcel_Calculation_Financial::MIRR',
1149
+ 'argumentCount' => '3'
1150
+ ),
1151
+ 'MMULT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1152
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MMULT',
1153
+ 'argumentCount' => '2'
1154
+ ),
1155
+ 'MOD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1156
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MOD',
1157
+ 'argumentCount' => '2'
1158
+ ),
1159
+ 'MODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1160
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MODE',
1161
+ 'argumentCount' => '1+'
1162
+ ),
1163
+ 'MONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1164
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::MONTHOFYEAR',
1165
+ 'argumentCount' => '1'
1166
+ ),
1167
+ 'MROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1168
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MROUND',
1169
+ 'argumentCount' => '2'
1170
+ ),
1171
+ 'MULTINOMIAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1172
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MULTINOMIAL',
1173
+ 'argumentCount' => '1+'
1174
+ ),
1175
+ 'N' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1176
+ 'functionCall' => 'PHPExcel_Calculation_Functions::N',
1177
+ 'argumentCount' => '1'
1178
+ ),
1179
+ 'NA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1180
+ 'functionCall' => 'PHPExcel_Calculation_Functions::NA',
1181
+ 'argumentCount' => '0'
1182
+ ),
1183
+ 'NEGBINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1184
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NEGBINOMDIST',
1185
+ 'argumentCount' => '3'
1186
+ ),
1187
+ 'NETWORKDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1188
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::NETWORKDAYS',
1189
+ 'argumentCount' => '2+'
1190
+ ),
1191
+ 'NOMINAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1192
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NOMINAL',
1193
+ 'argumentCount' => '2'
1194
+ ),
1195
+ 'NORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1196
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMDIST',
1197
+ 'argumentCount' => '4'
1198
+ ),
1199
+ 'NORMINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1200
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMINV',
1201
+ 'argumentCount' => '3'
1202
+ ),
1203
+ 'NORMSDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1204
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSDIST',
1205
+ 'argumentCount' => '1'
1206
+ ),
1207
+ 'NORMSINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1208
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSINV',
1209
+ 'argumentCount' => '1'
1210
+ ),
1211
+ 'NOT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1212
+ 'functionCall' => 'PHPExcel_Calculation_Logical::NOT',
1213
+ 'argumentCount' => '1'
1214
+ ),
1215
+ 'NOW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1216
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATETIMENOW',
1217
+ 'argumentCount' => '0'
1218
+ ),
1219
+ 'NPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1220
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NPER',
1221
+ 'argumentCount' => '3-5'
1222
+ ),
1223
+ 'NPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1224
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NPV',
1225
+ 'argumentCount' => '2+'
1226
+ ),
1227
+ 'OCT2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1228
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOBIN',
1229
+ 'argumentCount' => '1,2'
1230
+ ),
1231
+ 'OCT2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1232
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTODEC',
1233
+ 'argumentCount' => '1'
1234
+ ),
1235
+ 'OCT2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1236
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOHEX',
1237
+ 'argumentCount' => '1,2'
1238
+ ),
1239
+ 'ODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1240
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ODD',
1241
+ 'argumentCount' => '1'
1242
+ ),
1243
+ 'ODDFPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1244
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1245
+ 'argumentCount' => '8,9'
1246
+ ),
1247
+ 'ODDFYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1248
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1249
+ 'argumentCount' => '8,9'
1250
+ ),
1251
+ 'ODDLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1252
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1253
+ 'argumentCount' => '7,8'
1254
+ ),
1255
+ 'ODDLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1256
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1257
+ 'argumentCount' => '7,8'
1258
+ ),
1259
+ 'OFFSET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1260
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::OFFSET',
1261
+ 'argumentCount' => '3,5',
1262
+ 'passCellReference'=> TRUE,
1263
+ 'passByReference' => array(TRUE)
1264
+ ),
1265
+ 'OR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1266
+ 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_OR',
1267
+ 'argumentCount' => '1+'
1268
+ ),
1269
+ 'PEARSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1270
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
1271
+ 'argumentCount' => '2'
1272
+ ),
1273
+ 'PERCENTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1274
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTILE',
1275
+ 'argumentCount' => '2'
1276
+ ),
1277
+ 'PERCENTRANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1278
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTRANK',
1279
+ 'argumentCount' => '2,3'
1280
+ ),
1281
+ 'PERMUT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1282
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERMUT',
1283
+ 'argumentCount' => '2'
1284
+ ),
1285
+ 'PHONETIC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1286
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1287
+ 'argumentCount' => '1'
1288
+ ),
1289
+ 'PI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1290
+ 'functionCall' => 'pi',
1291
+ 'argumentCount' => '0'
1292
+ ),
1293
+ 'PMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1294
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PMT',
1295
+ 'argumentCount' => '3-5'
1296
+ ),
1297
+ 'POISSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1298
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::POISSON',
1299
+ 'argumentCount' => '3'
1300
+ ),
1301
+ 'POWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1302
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::POWER',
1303
+ 'argumentCount' => '2'
1304
+ ),
1305
+ 'PPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1306
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PPMT',
1307
+ 'argumentCount' => '4-6'
1308
+ ),
1309
+ 'PRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1310
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICE',
1311
+ 'argumentCount' => '6,7'
1312
+ ),
1313
+ 'PRICEDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1314
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEDISC',
1315
+ 'argumentCount' => '4,5'
1316
+ ),
1317
+ 'PRICEMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1318
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEMAT',
1319
+ 'argumentCount' => '5,6'
1320
+ ),
1321
+ 'PROB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1322
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1323
+ 'argumentCount' => '3,4'
1324
+ ),
1325
+ 'PRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1326
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::PRODUCT',
1327
+ 'argumentCount' => '1+'
1328
+ ),
1329
+ 'PROPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1330
+ 'functionCall' => 'PHPExcel_Calculation_TextData::PROPERCASE',
1331
+ 'argumentCount' => '1'
1332
+ ),
1333
+ 'PV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1334
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PV',
1335
+ 'argumentCount' => '3-5'
1336
+ ),
1337
+ 'QUARTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1338
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::QUARTILE',
1339
+ 'argumentCount' => '2'
1340
+ ),
1341
+ 'QUOTIENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1342
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::QUOTIENT',
1343
+ 'argumentCount' => '2'
1344
+ ),
1345
+ 'RADIANS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1346
+ 'functionCall' => 'deg2rad',
1347
+ 'argumentCount' => '1'
1348
+ ),
1349
+ 'RAND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1350
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
1351
+ 'argumentCount' => '0'
1352
+ ),
1353
+ 'RANDBETWEEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1354
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
1355
+ 'argumentCount' => '2'
1356
+ ),
1357
+ 'RANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1358
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::RANK',
1359
+ 'argumentCount' => '2,3'
1360
+ ),
1361
+ 'RATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1362
+ 'functionCall' => 'PHPExcel_Calculation_Financial::RATE',
1363
+ 'argumentCount' => '3-6'
1364
+ ),
1365
+ 'RECEIVED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1366
+ 'functionCall' => 'PHPExcel_Calculation_Financial::RECEIVED',
1367
+ 'argumentCount' => '4-5'
1368
+ ),
1369
+ 'REPLACE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1370
+ 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
1371
+ 'argumentCount' => '4'
1372
+ ),
1373
+ 'REPLACEB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1374
+ 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
1375
+ 'argumentCount' => '4'
1376
+ ),
1377
+ 'REPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1378
+ 'functionCall' => 'str_repeat',
1379
+ 'argumentCount' => '2'
1380
+ ),
1381
+ 'RIGHT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1382
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
1383
+ 'argumentCount' => '1,2'
1384
+ ),
1385
+ 'RIGHTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1386
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
1387
+ 'argumentCount' => '1,2'
1388
+ ),
1389
+ 'ROMAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1390
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROMAN',
1391
+ 'argumentCount' => '1,2'
1392
+ ),
1393
+ 'ROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1394
+ 'functionCall' => 'round',
1395
+ 'argumentCount' => '2'
1396
+ ),
1397
+ 'ROUNDDOWN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1398
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDDOWN',
1399
+ 'argumentCount' => '2'
1400
+ ),
1401
+ 'ROUNDUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1402
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDUP',
1403
+ 'argumentCount' => '2'
1404
+ ),
1405
+ 'ROW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1406
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROW',
1407
+ 'argumentCount' => '-1',
1408
+ 'passByReference' => array(TRUE)
1409
+ ),
1410
+ 'ROWS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1411
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROWS',
1412
+ 'argumentCount' => '1'
1413
+ ),
1414
+ 'RSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1415
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::RSQ',
1416
+ 'argumentCount' => '2'
1417
+ ),
1418
+ 'RTD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1419
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1420
+ 'argumentCount' => '1+'
1421
+ ),
1422
+ 'SEARCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1423
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
1424
+ 'argumentCount' => '2,3'
1425
+ ),
1426
+ 'SEARCHB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1427
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
1428
+ 'argumentCount' => '2,3'
1429
+ ),
1430
+ 'SECOND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1431
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::SECONDOFMINUTE',
1432
+ 'argumentCount' => '1'
1433
+ ),
1434
+ 'SERIESSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1435
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SERIESSUM',
1436
+ 'argumentCount' => '4'
1437
+ ),
1438
+ 'SIGN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1439
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SIGN',
1440
+ 'argumentCount' => '1'
1441
+ ),
1442
+ 'SIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1443
+ 'functionCall' => 'sin',
1444
+ 'argumentCount' => '1'
1445
+ ),
1446
+ 'SINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1447
+ 'functionCall' => 'sinh',
1448
+ 'argumentCount' => '1'
1449
+ ),
1450
+ 'SKEW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1451
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SKEW',
1452
+ 'argumentCount' => '1+'
1453
+ ),
1454
+ 'SLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1455
+ 'functionCall' => 'PHPExcel_Calculation_Financial::SLN',
1456
+ 'argumentCount' => '3'
1457
+ ),
1458
+ 'SLOPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1459
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SLOPE',
1460
+ 'argumentCount' => '2'
1461
+ ),
1462
+ 'SMALL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1463
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SMALL',
1464
+ 'argumentCount' => '2'
1465
+ ),
1466
+ 'SQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1467
+ 'functionCall' => 'sqrt',
1468
+ 'argumentCount' => '1'
1469
+ ),
1470
+ 'SQRTPI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1471
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SQRTPI',
1472
+ 'argumentCount' => '1'
1473
+ ),
1474
+ 'STANDARDIZE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1475
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STANDARDIZE',
1476
+ 'argumentCount' => '3'
1477
+ ),
1478
+ 'STDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1479
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEV',
1480
+ 'argumentCount' => '1+'
1481
+ ),
1482
+ 'STDEVA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1483
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVA',
1484
+ 'argumentCount' => '1+'
1485
+ ),
1486
+ 'STDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1487
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVP',
1488
+ 'argumentCount' => '1+'
1489
+ ),
1490
+ 'STDEVPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1491
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVPA',
1492
+ 'argumentCount' => '1+'
1493
+ ),
1494
+ 'STEYX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1495
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STEYX',
1496
+ 'argumentCount' => '2'
1497
+ ),
1498
+ 'SUBSTITUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1499
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SUBSTITUTE',
1500
+ 'argumentCount' => '3,4'
1501
+ ),
1502
+ 'SUBTOTAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1503
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUBTOTAL',
1504
+ 'argumentCount' => '2+'
1505
+ ),
1506
+ 'SUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1507
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUM',
1508
+ 'argumentCount' => '1+'
1509
+ ),
1510
+ 'SUMIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1511
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIF',
1512
+ 'argumentCount' => '2,3'
1513
+ ),
1514
+ 'SUMIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1515
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1516
+ 'argumentCount' => '?'
1517
+ ),
1518
+ 'SUMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1519
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMPRODUCT',
1520
+ 'argumentCount' => '1+'
1521
+ ),
1522
+ 'SUMSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1523
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMSQ',
1524
+ 'argumentCount' => '1+'
1525
+ ),
1526
+ 'SUMX2MY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1527
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2MY2',
1528
+ 'argumentCount' => '2'
1529
+ ),
1530
+ 'SUMX2PY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1531
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2PY2',
1532
+ 'argumentCount' => '2'
1533
+ ),
1534
+ 'SUMXMY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1535
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMXMY2',
1536
+ 'argumentCount' => '2'
1537
+ ),
1538
+ 'SYD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1539
+ 'functionCall' => 'PHPExcel_Calculation_Financial::SYD',
1540
+ 'argumentCount' => '4'
1541
+ ),
1542
+ 'T' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1543
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RETURNSTRING',
1544
+ 'argumentCount' => '1'
1545
+ ),
1546
+ 'TAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1547
+ 'functionCall' => 'tan',
1548
+ 'argumentCount' => '1'
1549
+ ),
1550
+ 'TANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1551
+ 'functionCall' => 'tanh',
1552
+ 'argumentCount' => '1'
1553
+ ),
1554
+ 'TBILLEQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1555
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLEQ',
1556
+ 'argumentCount' => '3'
1557
+ ),
1558
+ 'TBILLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1559
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLPRICE',
1560
+ 'argumentCount' => '3'
1561
+ ),
1562
+ 'TBILLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1563
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLYIELD',
1564
+ 'argumentCount' => '3'
1565
+ ),
1566
+ 'TDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1567
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TDIST',
1568
+ 'argumentCount' => '3'
1569
+ ),
1570
+ 'TEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1571
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TEXTFORMAT',
1572
+ 'argumentCount' => '2'
1573
+ ),
1574
+ 'TIME' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1575
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::TIME',
1576
+ 'argumentCount' => '3'
1577
+ ),
1578
+ 'TIMEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1579
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::TIMEVALUE',
1580
+ 'argumentCount' => '1'
1581
+ ),
1582
+ 'TINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1583
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TINV',
1584
+ 'argumentCount' => '2'
1585
+ ),
1586
+ 'TODAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1587
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATENOW',
1588
+ 'argumentCount' => '0'
1589
+ ),
1590
+ 'TRANSPOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1591
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::TRANSPOSE',
1592
+ 'argumentCount' => '1'
1593
+ ),
1594
+ 'TREND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1595
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TREND',
1596
+ 'argumentCount' => '1-4'
1597
+ ),
1598
+ 'TRIM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1599
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMSPACES',
1600
+ 'argumentCount' => '1'
1601
+ ),
1602
+ 'TRIMMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1603
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TRIMMEAN',
1604
+ 'argumentCount' => '2'
1605
+ ),
1606
+ 'TRUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1607
+ 'functionCall' => 'PHPExcel_Calculation_Logical::TRUE',
1608
+ 'argumentCount' => '0'
1609
+ ),
1610
+ 'TRUNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1611
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::TRUNC',
1612
+ 'argumentCount' => '1,2'
1613
+ ),
1614
+ 'TTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1615
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1616
+ 'argumentCount' => '4'
1617
+ ),
1618
+ 'TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1619
+ 'functionCall' => 'PHPExcel_Calculation_Functions::TYPE',
1620
+ 'argumentCount' => '1'
1621
+ ),
1622
+ 'UPPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1623
+ 'functionCall' => 'PHPExcel_Calculation_TextData::UPPERCASE',
1624
+ 'argumentCount' => '1'
1625
+ ),
1626
+ 'USDOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1627
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1628
+ 'argumentCount' => '2'
1629
+ ),
1630
+ 'VALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1631
+ 'functionCall' => 'PHPExcel_Calculation_TextData::VALUE',
1632
+ 'argumentCount' => '1'
1633
+ ),
1634
+ 'VAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1635
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARFunc',
1636
+ 'argumentCount' => '1+'
1637
+ ),
1638
+ 'VARA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1639
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARA',
1640
+ 'argumentCount' => '1+'
1641
+ ),
1642
+ 'VARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1643
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARP',
1644
+ 'argumentCount' => '1+'
1645
+ ),
1646
+ 'VARPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1647
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARPA',
1648
+ 'argumentCount' => '1+'
1649
+ ),
1650
+ 'VDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1651
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1652
+ 'argumentCount' => '5-7'
1653
+ ),
1654
+ 'VERSION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1655
+ 'functionCall' => 'PHPExcel_Calculation_Functions::VERSION',
1656
+ 'argumentCount' => '0'
1657
+ ),
1658
+ 'VLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1659
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::VLOOKUP',
1660
+ 'argumentCount' => '3,4'
1661
+ ),
1662
+ 'WEEKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1663
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFWEEK',
1664
+ 'argumentCount' => '1,2'
1665
+ ),
1666
+ 'WEEKNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1667
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::WEEKOFYEAR',
1668
+ 'argumentCount' => '1,2'
1669
+ ),
1670
+ 'WEIBULL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1671
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::WEIBULL',
1672
+ 'argumentCount' => '4'
1673
+ ),
1674
+ 'WORKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1675
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::WORKDAY',
1676
+ 'argumentCount' => '2+'
1677
+ ),
1678
+ 'XIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1679
+ 'functionCall' => 'PHPExcel_Calculation_Financial::XIRR',
1680
+ 'argumentCount' => '2,3'
1681
+ ),
1682
+ 'XNPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1683
+ 'functionCall' => 'PHPExcel_Calculation_Financial::XNPV',
1684
+ 'argumentCount' => '3'
1685
+ ),
1686
+ 'YEAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1687
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::YEAR',
1688
+ 'argumentCount' => '1'
1689
+ ),
1690
+ 'YEARFRAC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1691
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::YEARFRAC',
1692
+ 'argumentCount' => '2,3'
1693
+ ),
1694
+ 'YIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1695
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1696
+ 'argumentCount' => '6,7'
1697
+ ),
1698
+ 'YIELDDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1699
+ 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDDISC',
1700
+ 'argumentCount' => '4,5'
1701
+ ),
1702
+ 'YIELDMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1703
+ 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDMAT',
1704
+ 'argumentCount' => '5,6'
1705
+ ),
1706
+ 'ZTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1707
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::ZTEST',
1708
+ 'argumentCount' => '2-3'
1709
+ )
1710
+ );
1711
+
1712
+
1713
+ // Internal functions used for special control purposes
1714
+ private static $_controlFunctions = array(
1715
+ 'MKMATRIX' => array('argumentCount' => '*',
1716
+ 'functionCall' => 'self::_mkMatrix'
1717
+ )
1718
+ );
1719
+
1720
+
1721
+
1722
+
1723
+ private function __construct(PHPExcel $workbook = NULL) {
1724
+ $setPrecision = (PHP_INT_SIZE == 4) ? 14 : 16;
1725
+ $this->_savedPrecision = ini_get('precision');
1726
+ if ($this->_savedPrecision < $setPrecision) {
1727
+ ini_set('precision',$setPrecision);
1728
+ }
1729
+ $this->delta = 1 * pow(10, -$setPrecision);
1730
+
1731
+ if ($workbook !== NULL) {
1732
+ self::$_workbookSets[$workbook->getID()] = $this;
1733
+ }
1734
+
1735
+ $this->_workbook = $workbook;
1736
+ $this->_cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack();
1737
+ $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->_cyclicReferenceStack);
1738
+ } // function __construct()
1739
+
1740
+
1741
+ public function __destruct() {
1742
+ if ($this->_savedPrecision != ini_get('precision')) {
1743
+ ini_set('precision',$this->_savedPrecision);
1744
+ }
1745
+ }
1746
+
1747
+ private static function _loadLocales() {
1748
+ $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
1749
+ foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) {
1750
+ $filename = substr($filename,strlen($localeFileDirectory)+1);
1751
+ if ($filename != 'en') {
1752
+ self::$_validLocaleLanguages[] = $filename;
1753
+ }
1754
+ }
1755
+ }
1756
+
1757
+ /**
1758
+ * Get an instance of this class
1759
+ *
1760
+ * @access public
1761
+ * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object,
1762
+ * or NULL to create a standalone claculation engine
1763
+ * @return PHPExcel_Calculation
1764
+ */
1765
+ public static function getInstance(PHPExcel $workbook = NULL) {
1766
+ if ($workbook !== NULL) {
1767
+ if (isset(self::$_workbookSets[$workbook->getID()])) {
1768
+ return self::$_workbookSets[$workbook->getID()];
1769
+ }
1770
+ return new PHPExcel_Calculation($workbook);
1771
+ }
1772
+
1773
+ if (!isset(self::$_instance) || (self::$_instance === NULL)) {
1774
+ self::$_instance = new PHPExcel_Calculation();
1775
+ }
1776
+
1777
+ return self::$_instance;
1778
+ } // function getInstance()
1779
+
1780
+ /**
1781
+ * Unset an instance of this class
1782
+ *
1783
+ * @access public
1784
+ * @param PHPExcel $workbook Injected workbook identifying the instance to unset
1785
+ */
1786
+ public static function unsetInstance(PHPExcel $workbook = NULL) {
1787
+ if ($workbook !== NULL) {
1788
+ if (isset(self::$_workbookSets[$workbook->getID()])) {
1789
+ unset(self::$_workbookSets[$workbook->getID()]);
1790
+ }
1791
+ }
1792
+ }
1793
+
1794
+ /**
1795
+ * Flush the calculation cache for any existing instance of this class
1796
+ * but only if a PHPExcel_Calculation instance exists
1797
+ *
1798
+ * @access public
1799
+ * @return null
1800
+ */
1801
+ public function flushInstance() {
1802
+ $this->clearCalculationCache();
1803
+ } // function flushInstance()
1804
+
1805
+
1806
+ /**
1807
+ * Get the debuglog for this claculation engine instance
1808
+ *
1809
+ * @access public
1810
+ * @return PHPExcel_CalcEngine_Logger
1811
+ */
1812
+ public function getDebugLog() {
1813
+ return $this->_debugLog;
1814
+ }
1815
+
1816
+ /**
1817
+ * __clone implementation. Cloning should not be allowed in a Singleton!
1818
+ *
1819
+ * @access public
1820
+ * @throws PHPExcel_Calculation_Exception
1821
+ */
1822
+ public final function __clone() {
1823
+ throw new PHPExcel_Calculation_Exception ('Cloning the calculation engine is not allowed!');
1824
+ } // function __clone()
1825
+
1826
+
1827
+ /**
1828
+ * Return the locale-specific translation of TRUE
1829
+ *
1830
+ * @access public
1831
+ * @return string locale-specific translation of TRUE
1832
+ */
1833
+ public static function getTRUE() {
1834
+ return self::$_localeBoolean['TRUE'];
1835
+ }
1836
+
1837
+ /**
1838
+ * Return the locale-specific translation of FALSE
1839
+ *
1840
+ * @access public
1841
+ * @return string locale-specific translation of FALSE
1842
+ */
1843
+ public static function getFALSE() {
1844
+ return self::$_localeBoolean['FALSE'];
1845
+ }
1846
+
1847
+ /**
1848
+ * Set the Array Return Type (Array or Value of first element in the array)
1849
+ *
1850
+ * @access public
1851
+ * @param string $returnType Array return type
1852
+ * @return boolean Success or failure
1853
+ */
1854
+ public static function setArrayReturnType($returnType) {
1855
+ if (($returnType == self::RETURN_ARRAY_AS_VALUE) ||
1856
+ ($returnType == self::RETURN_ARRAY_AS_ERROR) ||
1857
+ ($returnType == self::RETURN_ARRAY_AS_ARRAY)) {
1858
+ self::$returnArrayAsType = $returnType;
1859
+ return TRUE;
1860
+ }
1861
+ return FALSE;
1862
+ } // function setArrayReturnType()
1863
+
1864
+
1865
+ /**
1866
+ * Return the Array Return Type (Array or Value of first element in the array)
1867
+ *
1868
+ * @access public
1869
+ * @return string $returnType Array return type
1870
+ */
1871
+ public static function getArrayReturnType() {
1872
+ return self::$returnArrayAsType;
1873
+ } // function getArrayReturnType()
1874
+
1875
+
1876
+ /**
1877
+ * Is calculation caching enabled?
1878
+ *
1879
+ * @access public
1880
+ * @return boolean
1881
+ */
1882
+ public function getCalculationCacheEnabled() {
1883
+ return $this->_calculationCacheEnabled;
1884
+ } // function getCalculationCacheEnabled()
1885
+
1886
+ /**
1887
+ * Enable/disable calculation cache
1888
+ *
1889
+ * @access public
1890
+ * @param boolean $pValue
1891
+ */
1892
+ public function setCalculationCacheEnabled($pValue = TRUE) {
1893
+ $this->_calculationCacheEnabled = $pValue;
1894
+ $this->clearCalculationCache();
1895
+ } // function setCalculationCacheEnabled()
1896
+
1897
+
1898
+ /**
1899
+ * Enable calculation cache
1900
+ */
1901
+ public function enableCalculationCache() {
1902
+ $this->setCalculationCacheEnabled(TRUE);
1903
+ } // function enableCalculationCache()
1904
+
1905
+
1906
+ /**
1907
+ * Disable calculation cache
1908
+ */
1909
+ public function disableCalculationCache() {
1910
+ $this->setCalculationCacheEnabled(FALSE);
1911
+ } // function disableCalculationCache()
1912
+
1913
+
1914
+ /**
1915
+ * Clear calculation cache
1916
+ */
1917
+ public function clearCalculationCache() {
1918
+ $this->_calculationCache = array();
1919
+ } // function clearCalculationCache()
1920
+
1921
+ /**
1922
+ * Clear calculation cache for a specified worksheet
1923
+ *
1924
+ * @param string $worksheetName
1925
+ */
1926
+ public function clearCalculationCacheForWorksheet($worksheetName) {
1927
+ if (isset($this->_calculationCache[$worksheetName])) {
1928
+ unset($this->_calculationCache[$worksheetName]);
1929
+ }
1930
+ } // function clearCalculationCacheForWorksheet()
1931
+
1932
+ /**
1933
+ * Rename calculation cache for a specified worksheet
1934
+ *
1935
+ * @param string $fromWorksheetName
1936
+ * @param string $toWorksheetName
1937
+ */
1938
+ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) {
1939
+ if (isset($this->_calculationCache[$fromWorksheetName])) {
1940
+ $this->_calculationCache[$toWorksheetName] = &$this->_calculationCache[$fromWorksheetName];
1941
+ unset($this->_calculationCache[$fromWorksheetName]);
1942
+ }
1943
+ } // function renameCalculationCacheForWorksheet()
1944
+
1945
+
1946
+ /**
1947
+ * Get the currently defined locale code
1948
+ *
1949
+ * @return string
1950
+ */
1951
+ public function getLocale() {
1952
+ return self::$_localeLanguage;
1953
+ } // function getLocale()
1954
+
1955
+
1956
+ /**
1957
+ * Set the locale code
1958
+ *
1959
+ * @param string $locale The locale to use for formula translation
1960
+ * @return boolean
1961
+ */
1962
+ public function setLocale($locale = 'en_us') {
1963
+ // Identify our locale and language
1964
+ $language = $locale = strtolower($locale);
1965
+ if (strpos($locale,'_') !== FALSE) {
1966
+ list($language) = explode('_',$locale);
1967
+ }
1968
+
1969
+ if (count(self::$_validLocaleLanguages) == 1)
1970
+ self::_loadLocales();
1971
+
1972
+ // Test whether we have any language data for this language (any locale)
1973
+ if (in_array($language,self::$_validLocaleLanguages)) {
1974
+ // initialise language/locale settings
1975
+ self::$_localeFunctions = array();
1976
+ self::$_localeArgumentSeparator = ',';
1977
+ self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL');
1978
+ // Default is English, if user isn't requesting english, then read the necessary data from the locale files
1979
+ if ($locale != 'en_us') {
1980
+ // Search for a file with a list of function names for locale
1981
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'functions';
1982
+ if (!file_exists($functionNamesFile)) {
1983
+ // If there isn't a locale specific function file, look for a language specific function file
1984
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions';
1985
+ if (!file_exists($functionNamesFile)) {
1986
+ return FALSE;
1987
+ }
1988
+ }
1989
+ // Retrieve the list of locale or language specific function names
1990
+ $localeFunctions = file($functionNamesFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
1991
+ foreach ($localeFunctions as $localeFunction) {
1992
+ list($localeFunction) = explode('##',$localeFunction); // Strip out comments
1993
+ if (strpos($localeFunction,'=') !== FALSE) {
1994
+ list($fName,$lfName) = explode('=',$localeFunction);
1995
+ $fName = trim($fName);
1996
+ $lfName = trim($lfName);
1997
+ if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
1998
+ self::$_localeFunctions[$fName] = $lfName;
1999
+ }
2000
+ }
2001
+ }
2002
+ // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
2003
+ if (isset(self::$_localeFunctions['TRUE'])) { self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; }
2004
+ if (isset(self::$_localeFunctions['FALSE'])) { self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; }
2005
+
2006
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'config';
2007
+ if (!file_exists($configFile)) {
2008
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config';
2009
+ }
2010
+ if (file_exists($configFile)) {
2011
+ $localeSettings = file($configFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2012
+ foreach ($localeSettings as $localeSetting) {
2013
+ list($localeSetting) = explode('##',$localeSetting); // Strip out comments
2014
+ if (strpos($localeSetting,'=') !== FALSE) {
2015
+ list($settingName,$settingValue) = explode('=',$localeSetting);
2016
+ $settingName = strtoupper(trim($settingName));
2017
+ switch ($settingName) {
2018
+ case 'ARGUMENTSEPARATOR' :
2019
+ self::$_localeArgumentSeparator = trim($settingValue);
2020
+ break;
2021
+ }
2022
+ }
2023
+ }
2024
+ }
2025
+ }
2026
+
2027
+ self::$functionReplaceFromExcel = self::$functionReplaceToExcel =
2028
+ self::$functionReplaceFromLocale = self::$functionReplaceToLocale = NULL;
2029
+ self::$_localeLanguage = $locale;
2030
+ return TRUE;
2031
+ }
2032
+ return FALSE;
2033
+ } // function setLocale()
2034
+
2035
+
2036
+
2037
+ public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) {
2038
+ $strlen = mb_strlen($formula);
2039
+ for ($i = 0; $i < $strlen; ++$i) {
2040
+ $chr = mb_substr($formula,$i,1);
2041
+ switch ($chr) {
2042
+ case '{' : $inBraces = TRUE;
2043
+ break;
2044
+ case '}' : $inBraces = FALSE;
2045
+ break;
2046
+ case $fromSeparator :
2047
+ if (!$inBraces) {
2048
+ $formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1);
2049
+ }
2050
+ }
2051
+ }
2052
+ return $formula;
2053
+ }
2054
+
2055
+ private static function _translateFormula($from,$to,$formula,$fromSeparator,$toSeparator) {
2056
+ // Convert any Excel function names to the required language
2057
+ if (self::$_localeLanguage !== 'en_us') {
2058
+ $inBraces = FALSE;
2059
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
2060
+ if (strpos($formula,'"') !== FALSE) {
2061
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
2062
+ // the formula
2063
+ $temp = explode('"',$formula);
2064
+ $i = FALSE;
2065
+ foreach($temp as &$value) {
2066
+ // Only count/replace in alternating array entries
2067
+ if ($i = !$i) {
2068
+ $value = preg_replace($from,$to,$value);
2069
+ $value = self::_translateSeparator($fromSeparator,$toSeparator,$value,$inBraces);
2070
+ }
2071
+ }
2072
+ unset($value);
2073
+ // Then rebuild the formula string
2074
+ $formula = implode('"',$temp);
2075
+ } else {
2076
+ // If there's no quoted strings, then we do a simple count/replace
2077
+ $formula = preg_replace($from,$to,$formula);
2078
+ $formula = self::_translateSeparator($fromSeparator,$toSeparator,$formula,$inBraces);
2079
+ }
2080
+ }
2081
+
2082
+ return $formula;
2083
+ }
2084
+
2085
+ private static $functionReplaceFromExcel = NULL;
2086
+ private static $functionReplaceToLocale = NULL;
2087
+
2088
+ public function _translateFormulaToLocale($formula) {
2089
+ if (self::$functionReplaceFromExcel === NULL) {
2090
+ self::$functionReplaceFromExcel = array();
2091
+ foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
2092
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui';
2093
+ }
2094
+ foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
2095
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
2096
+ }
2097
+
2098
+ }
2099
+
2100
+ if (self::$functionReplaceToLocale === NULL) {
2101
+ self::$functionReplaceToLocale = array();
2102
+ foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
2103
+ self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2';
2104
+ }
2105
+ foreach(array_values(self::$_localeBoolean) as $localeBoolean) {
2106
+ self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2';
2107
+ }
2108
+ }
2109
+
2110
+ return self::_translateFormula(self::$functionReplaceFromExcel,self::$functionReplaceToLocale,$formula,',',self::$_localeArgumentSeparator);
2111
+ } // function _translateFormulaToLocale()
2112
+
2113
+
2114
+ private static $functionReplaceFromLocale = NULL;
2115
+ private static $functionReplaceToExcel = NULL;
2116
+
2117
+ public function _translateFormulaToEnglish($formula) {
2118
+ if (self::$functionReplaceFromLocale === NULL) {
2119
+ self::$functionReplaceFromLocale = array();
2120
+ foreach(array_values(self::$_localeFunctions) as $localeFunctionName) {
2121
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui';
2122
+ }
2123
+ foreach(array_values(self::$_localeBoolean) as $excelBoolean) {
2124
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
2125
+ }
2126
+ }
2127
+
2128
+ if (self::$functionReplaceToExcel === NULL) {
2129
+ self::$functionReplaceToExcel = array();
2130
+ foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) {
2131
+ self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2';
2132
+ }
2133
+ foreach(array_keys(self::$_localeBoolean) as $excelBoolean) {
2134
+ self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2';
2135
+ }
2136
+ }
2137
+
2138
+ return self::_translateFormula(self::$functionReplaceFromLocale,self::$functionReplaceToExcel,$formula,self::$_localeArgumentSeparator,',');
2139
+ } // function _translateFormulaToEnglish()
2140
+
2141
+
2142
+ public static function _localeFunc($function) {
2143
+ if (self::$_localeLanguage !== 'en_us') {
2144
+ $functionName = trim($function,'(');
2145
+ if (isset(self::$_localeFunctions[$functionName])) {
2146
+ $brace = ($functionName != $function);
2147
+ $function = self::$_localeFunctions[$functionName];
2148
+ if ($brace) { $function .= '('; }
2149
+ }
2150
+ }
2151
+ return $function;
2152
+ }
2153
+
2154
+
2155
+
2156
+
2157
+ /**
2158
+ * Wrap string values in quotes
2159
+ *
2160
+ * @param mixed $value
2161
+ * @return mixed
2162
+ */
2163
+ public static function _wrapResult($value) {
2164
+ if (is_string($value)) {
2165
+ // Error values cannot be "wrapped"
2166
+ if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) {
2167
+ // Return Excel errors "as is"
2168
+ return $value;
2169
+ }
2170
+ // Return strings wrapped in quotes
2171
+ return '"'.$value.'"';
2172
+ // Convert numeric errors to NaN error
2173
+ } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
2174
+ return PHPExcel_Calculation_Functions::NaN();
2175
+ }
2176
+
2177
+ return $value;
2178
+ } // function _wrapResult()
2179
+
2180
+
2181
+ /**
2182
+ * Remove quotes used as a wrapper to identify string values
2183
+ *
2184
+ * @param mixed $value
2185
+ * @return mixed
2186
+ */
2187
+ public static function _unwrapResult($value) {
2188
+ if (is_string($value)) {
2189
+ if ((isset($value{0})) && ($value{0} == '"') && (substr($value,-1) == '"')) {
2190
+ return substr($value,1,-1);
2191
+ }
2192
+ // Convert numeric errors to NaN error
2193
+ } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
2194
+ return PHPExcel_Calculation_Functions::NaN();
2195
+ }
2196
+ return $value;
2197
+ } // function _unwrapResult()
2198
+
2199
+
2200
+
2201
+
2202
+ /**
2203
+ * Calculate cell value (using formula from a cell ID)
2204
+ * Retained for backward compatibility
2205
+ *
2206
+ * @access public
2207
+ * @param PHPExcel_Cell $pCell Cell to calculate
2208
+ * @return mixed
2209
+ * @throws PHPExcel_Calculation_Exception
2210
+ */
2211
+ public function calculate(PHPExcel_Cell $pCell = NULL) {
2212
+ try {
2213
+ return $this->calculateCellValue($pCell);
2214
+ } catch (PHPExcel_Exception $e) {
2215
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2216
+ }
2217
+ } // function calculate()
2218
+
2219
+
2220
+ /**
2221
+ * Calculate the value of a cell formula
2222
+ *
2223
+ * @access public
2224
+ * @param PHPExcel_Cell $pCell Cell to calculate
2225
+ * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not
2226
+ * @return mixed
2227
+ * @throws PHPExcel_Calculation_Exception
2228
+ */
2229
+ public function calculateCellValue(PHPExcel_Cell $pCell = NULL, $resetLog = TRUE) {
2230
+ if ($pCell === NULL) {
2231
+ return NULL;
2232
+ }
2233
+
2234
+ $returnArrayAsType = self::$returnArrayAsType;
2235
+ if ($resetLog) {
2236
+ // Initialise the logging settings if requested
2237
+ $this->formulaError = null;
2238
+ $this->_debugLog->clearLog();
2239
+ $this->_cyclicReferenceStack->clear();
2240
+ $this->_cyclicFormulaCount = 1;
2241
+
2242
+ self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
2243
+ }
2244
+
2245
+ // Execute the calculation for the cell formula
2246
+ $this->_cellStack[] = array(
2247
+ 'sheet' => $pCell->getWorksheet()->getTitle(),
2248
+ 'cell' => $pCell->getCoordinate(),
2249
+ );
2250
+ try {
2251
+ $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
2252
+ $cellAddress = array_pop($this->_cellStack);
2253
+ $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
2254
+ } catch (PHPExcel_Exception $e) {
2255
+ $cellAddress = array_pop($this->_cellStack);
2256
+ $this->_workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
2257
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2258
+ }
2259
+
2260
+ if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
2261
+ self::$returnArrayAsType = $returnArrayAsType;
2262
+ $testResult = PHPExcel_Calculation_Functions::flattenArray($result);
2263
+ if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) {
2264
+ return PHPExcel_Calculation_Functions::VALUE();
2265
+ }
2266
+ // If there's only a single cell in the array, then we allow it
2267
+ if (count($testResult) != 1) {
2268
+ // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it
2269
+ $r = array_keys($result);
2270
+ $r = array_shift($r);
2271
+ if (!is_numeric($r)) { return PHPExcel_Calculation_Functions::VALUE(); }
2272
+ if (is_array($result[$r])) {
2273
+ $c = array_keys($result[$r]);
2274
+ $c = array_shift($c);
2275
+ if (!is_numeric($c)) {
2276
+ return PHPExcel_Calculation_Functions::VALUE();
2277
+ }
2278
+ }
2279
+ }
2280
+ $result = array_shift($testResult);
2281
+ }
2282
+ self::$returnArrayAsType = $returnArrayAsType;
2283
+
2284
+
2285
+ if ($result === NULL) {
2286
+ return 0;
2287
+ } elseif((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
2288
+ return PHPExcel_Calculation_Functions::NaN();
2289
+ }
2290
+ return $result;
2291
+ } // function calculateCellValue(
2292
+
2293
+
2294
+ /**
2295
+ * Validate and parse a formula string
2296
+ *
2297
+ * @param string $formula Formula to parse
2298
+ * @return array
2299
+ * @throws PHPExcel_Calculation_Exception
2300
+ */
2301
+ public function parseFormula($formula) {
2302
+ // Basic validation that this is indeed a formula
2303
+ // We return an empty array if not
2304
+ $formula = trim($formula);
2305
+ if ((!isset($formula{0})) || ($formula{0} != '=')) return array();
2306
+ $formula = ltrim(substr($formula,1));
2307
+ if (!isset($formula{0})) return array();
2308
+
2309
+ // Parse the formula and return the token stack
2310
+ return $this->_parseFormula($formula);
2311
+ } // function parseFormula()
2312
+
2313
+
2314
+ /**
2315
+ * Calculate the value of a formula
2316
+ *
2317
+ * @param string $formula Formula to parse
2318
+ * @param string $cellID Address of the cell to calculate
2319
+ * @param PHPExcel_Cell $pCell Cell to calculate
2320
+ * @return mixed
2321
+ * @throws PHPExcel_Calculation_Exception
2322
+ */
2323
+ public function calculateFormula($formula, $cellID=NULL, PHPExcel_Cell $pCell = NULL) {
2324
+ // Initialise the logging settings
2325
+ $this->formulaError = null;
2326
+ $this->_debugLog->clearLog();
2327
+ $this->_cyclicReferenceStack->clear();
2328
+
2329
+ // Disable calculation cacheing because it only applies to cell calculations, not straight formulae
2330
+ // But don't actually flush any cache
2331
+ $resetCache = $this->getCalculationCacheEnabled();
2332
+ $this->_calculationCacheEnabled = FALSE;
2333
+ // Execute the calculation
2334
+ try {
2335
+ $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
2336
+ } catch (PHPExcel_Exception $e) {
2337
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2338
+ }
2339
+
2340
+ // Reset calculation cacheing to its previous state
2341
+ $this->_calculationCacheEnabled = $resetCache;
2342
+
2343
+ return $result;
2344
+ } // function calculateFormula()
2345
+
2346
+
2347
+ public function getValueFromCache($cellReference, &$cellValue) {
2348
+ // Is calculation cacheing enabled?
2349
+ // Is the value present in calculation cache?
2350
+ $this->_debugLog->writeDebugLog('Testing cache value for cell ', $cellReference);
2351
+ if (($this->_calculationCacheEnabled) && (isset($this->_calculationCache[$cellReference]))) {
2352
+ $this->_debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache');
2353
+ // Return the cached result
2354
+ $cellValue = $this->_calculationCache[$cellReference];
2355
+ return TRUE;
2356
+ }
2357
+ return FALSE;
2358
+ }
2359
+
2360
+ public function saveValueToCache($cellReference, $cellValue) {
2361
+ if ($this->_calculationCacheEnabled) {
2362
+ $this->_calculationCache[$cellReference] = $cellValue;
2363
+ }
2364
+ }
2365
+
2366
+ /**
2367
+ * Parse a cell formula and calculate its value
2368
+ *
2369
+ * @param string $formula The formula to parse and calculate
2370
+ * @param string $cellID The ID (e.g. A3) of the cell that we are calculating
2371
+ * @param PHPExcel_Cell $pCell Cell to calculate
2372
+ * @return mixed
2373
+ * @throws PHPExcel_Calculation_Exception
2374
+ */
2375
+ public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
2376
+ $cellValue = null;
2377
+
2378
+ // Basic validation that this is indeed a formula
2379
+ // We simply return the cell value if not
2380
+ $formula = trim($formula);
2381
+ if ($formula{0} != '=') return self::_wrapResult($formula);
2382
+ $formula = ltrim(substr($formula, 1));
2383
+ if (!isset($formula{0})) return self::_wrapResult($formula);
2384
+
2385
+ $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
2386
+ $wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
2387
+ $wsCellReference = $wsTitle . '!' . $cellID;
2388
+
2389
+ if (($cellID !== NULL) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
2390
+ return $cellValue;
2391
+ }
2392
+
2393
+ if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsCellReference))) {
2394
+ if ($this->cyclicFormulaCount <= 0) {
2395
+ $this->_cyclicFormulaCell = '';
2396
+ return $this->_raiseFormulaError('Cyclic Reference in Formula');
2397
+ } elseif ($this->_cyclicFormulaCell === $wsCellReference) {
2398
+ ++$this->_cyclicFormulaCount;
2399
+ if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
2400
+ $this->_cyclicFormulaCell = '';
2401
+ return $cellValue;
2402
+ }
2403
+ } elseif ($this->_cyclicFormulaCell == '') {
2404
+ if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
2405
+ return $cellValue;
2406
+ }
2407
+ $this->_cyclicFormulaCell = $wsCellReference;
2408
+ }
2409
+ }
2410
+
2411
+ // Parse the formula onto the token stack and calculate the value
2412
+ $this->_cyclicReferenceStack->push($wsCellReference);
2413
+ $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
2414
+ $this->_cyclicReferenceStack->pop();
2415
+
2416
+ // Save to calculation cache
2417
+ if ($cellID !== NULL) {
2418
+ $this->saveValueToCache($wsCellReference, $cellValue);
2419
+ }
2420
+
2421
+ // Return the calculated value
2422
+ return $cellValue;
2423
+ } // function _calculateFormulaValue()
2424
+
2425
+
2426
+ /**
2427
+ * Ensure that paired matrix operands are both matrices and of the same size
2428
+ *
2429
+ * @param mixed &$operand1 First matrix operand
2430
+ * @param mixed &$operand2 Second matrix operand
2431
+ * @param integer $resize Flag indicating whether the matrices should be resized to match
2432
+ * and (if so), whether the smaller dimension should grow or the
2433
+ * larger should shrink.
2434
+ * 0 = no resize
2435
+ * 1 = shrink to fit
2436
+ * 2 = extend to fit
2437
+ */
2438
+ private static function _checkMatrixOperands(&$operand1,&$operand2,$resize = 1) {
2439
+ // Examine each of the two operands, and turn them into an array if they aren't one already
2440
+ // Note that this function should only be called if one or both of the operand is already an array
2441
+ if (!is_array($operand1)) {
2442
+ list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand2);
2443
+ $operand1 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand1));
2444
+ $resize = 0;
2445
+ } elseif (!is_array($operand2)) {
2446
+ list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand1);
2447
+ $operand2 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand2));
2448
+ $resize = 0;
2449
+ }
2450
+
2451
+ list($matrix1Rows,$matrix1Columns) = self::_getMatrixDimensions($operand1);
2452
+ list($matrix2Rows,$matrix2Columns) = self::_getMatrixDimensions($operand2);
2453
+ if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
2454
+ $resize = 1;
2455
+ }
2456
+
2457
+ if ($resize == 2) {
2458
+ // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
2459
+ self::_resizeMatricesExtend($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
2460
+ } elseif ($resize == 1) {
2461
+ // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
2462
+ self::_resizeMatricesShrink($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
2463
+ }
2464
+ return array( $matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns);
2465
+ } // function _checkMatrixOperands()
2466
+
2467
+
2468
+ /**
2469
+ * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0
2470
+ *
2471
+ * @param mixed &$matrix matrix operand
2472
+ * @return array An array comprising the number of rows, and number of columns
2473
+ */
2474
+ public static function _getMatrixDimensions(&$matrix) {
2475
+ $matrixRows = count($matrix);
2476
+ $matrixColumns = 0;
2477
+ foreach($matrix as $rowKey => $rowValue) {
2478
+ $matrixColumns = max(count($rowValue),$matrixColumns);
2479
+ if (!is_array($rowValue)) {
2480
+ $matrix[$rowKey] = array($rowValue);
2481
+ } else {
2482
+ $matrix[$rowKey] = array_values($rowValue);
2483
+ }
2484
+ }
2485
+ $matrix = array_values($matrix);
2486
+ return array($matrixRows,$matrixColumns);
2487
+ } // function _getMatrixDimensions()
2488
+
2489
+
2490
+ /**
2491
+ * Ensure that paired matrix operands are both matrices of the same size
2492
+ *
2493
+ * @param mixed &$matrix1 First matrix operand
2494
+ * @param mixed &$matrix2 Second matrix operand
2495
+ * @param integer $matrix1Rows Row size of first matrix operand
2496
+ * @param integer $matrix1Columns Column size of first matrix operand
2497
+ * @param integer $matrix2Rows Row size of second matrix operand
2498
+ * @param integer $matrix2Columns Column size of second matrix operand
2499
+ */
2500
+ private static function _resizeMatricesShrink(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
2501
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
2502
+ if ($matrix2Rows < $matrix1Rows) {
2503
+ for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
2504
+ unset($matrix1[$i]);
2505
+ }
2506
+ }
2507
+ if ($matrix2Columns < $matrix1Columns) {
2508
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2509
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
2510
+ unset($matrix1[$i][$j]);
2511
+ }
2512
+ }
2513
+ }
2514
+ }
2515
+
2516
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
2517
+ if ($matrix1Rows < $matrix2Rows) {
2518
+ for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
2519
+ unset($matrix2[$i]);
2520
+ }
2521
+ }
2522
+ if ($matrix1Columns < $matrix2Columns) {
2523
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2524
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
2525
+ unset($matrix2[$i][$j]);
2526
+ }
2527
+ }
2528
+ }
2529
+ }
2530
+ } // function _resizeMatricesShrink()
2531
+
2532
+
2533
+ /**
2534
+ * Ensure that paired matrix operands are both matrices of the same size
2535
+ *
2536
+ * @param mixed &$matrix1 First matrix operand
2537
+ * @param mixed &$matrix2 Second matrix operand
2538
+ * @param integer $matrix1Rows Row size of first matrix operand
2539
+ * @param integer $matrix1Columns Column size of first matrix operand
2540
+ * @param integer $matrix2Rows Row size of second matrix operand
2541
+ * @param integer $matrix2Columns Column size of second matrix operand
2542
+ */
2543
+ private static function _resizeMatricesExtend(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) {
2544
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
2545
+ if ($matrix2Columns < $matrix1Columns) {
2546
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2547
+ $x = $matrix2[$i][$matrix2Columns-1];
2548
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
2549
+ $matrix2[$i][$j] = $x;
2550
+ }
2551
+ }
2552
+ }
2553
+ if ($matrix2Rows < $matrix1Rows) {
2554
+ $x = $matrix2[$matrix2Rows-1];
2555
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2556
+ $matrix2[$i] = $x;
2557
+ }
2558
+ }
2559
+ }
2560
+
2561
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
2562
+ if ($matrix1Columns < $matrix2Columns) {
2563
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2564
+ $x = $matrix1[$i][$matrix1Columns-1];
2565
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
2566
+ $matrix1[$i][$j] = $x;
2567
+ }
2568
+ }
2569
+ }
2570
+ if ($matrix1Rows < $matrix2Rows) {
2571
+ $x = $matrix1[$matrix1Rows-1];
2572
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2573
+ $matrix1[$i] = $x;
2574
+ }
2575
+ }
2576
+ }
2577
+ } // function _resizeMatricesExtend()
2578
+
2579
+
2580
+ /**
2581
+ * Format details of an operand for display in the log (based on operand type)
2582
+ *
2583
+ * @param mixed $value First matrix operand
2584
+ * @return mixed
2585
+ */
2586
+ private function _showValue($value) {
2587
+ if ($this->_debugLog->getWriteDebugLog()) {
2588
+ $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
2589
+ if (count($testArray) == 1) {
2590
+ $value = array_pop($testArray);
2591
+ }
2592
+
2593
+ if (is_array($value)) {
2594
+ $returnMatrix = array();
2595
+ $pad = $rpad = ', ';
2596
+ foreach($value as $row) {
2597
+ if (is_array($row)) {
2598
+ $returnMatrix[] = implode($pad,array_map(array($this,'_showValue'),$row));
2599
+ $rpad = '; ';
2600
+ } else {
2601
+ $returnMatrix[] = $this->_showValue($row);
2602
+ }
2603
+ }
2604
+ return '{ '.implode($rpad,$returnMatrix).' }';
2605
+ } elseif(is_string($value) && (trim($value,'"') == $value)) {
2606
+ return '"'.$value.'"';
2607
+ } elseif(is_bool($value)) {
2608
+ return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
2609
+ }
2610
+ }
2611
+ return PHPExcel_Calculation_Functions::flattenSingleValue($value);
2612
+ } // function _showValue()
2613
+
2614
+
2615
+ /**
2616
+ * Format type and details of an operand for display in the log (based on operand type)
2617
+ *
2618
+ * @param mixed $value First matrix operand
2619
+ * @return mixed
2620
+ */
2621
+ private function _showTypeDetails($value) {
2622
+ if ($this->_debugLog->getWriteDebugLog()) {
2623
+ $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
2624
+ if (count($testArray) == 1) {
2625
+ $value = array_pop($testArray);
2626
+ }
2627
+
2628
+ if ($value === NULL) {
2629
+ return 'a NULL value';
2630
+ } elseif (is_float($value)) {
2631
+ $typeString = 'a floating point number';
2632
+ } elseif(is_int($value)) {
2633
+ $typeString = 'an integer number';
2634
+ } elseif(is_bool($value)) {
2635
+ $typeString = 'a boolean';
2636
+ } elseif(is_array($value)) {
2637
+ $typeString = 'a matrix';
2638
+ } else {
2639
+ if ($value == '') {
2640
+ return 'an empty string';
2641
+ } elseif ($value{0} == '#') {
2642
+ return 'a '.$value.' error';
2643
+ } else {
2644
+ $typeString = 'a string';
2645
+ }
2646
+ }
2647
+ return $typeString.' with a value of '.$this->_showValue($value);
2648
+ }
2649
+ } // function _showTypeDetails()
2650
+
2651
+
2652
+ private function _convertMatrixReferences($formula) {
2653
+ static $matrixReplaceFrom = array('{',';','}');
2654
+ static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))');
2655
+
2656
+ // Convert any Excel matrix references to the MKMATRIX() function
2657
+ if (strpos($formula,'{') !== FALSE) {
2658
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
2659
+ if (strpos($formula,'"') !== FALSE) {
2660
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
2661
+ // the formula
2662
+ $temp = explode('"',$formula);
2663
+ // Open and Closed counts used for trapping mismatched braces in the formula
2664
+ $openCount = $closeCount = 0;
2665
+ $i = FALSE;
2666
+ foreach($temp as &$value) {
2667
+ // Only count/replace in alternating array entries
2668
+ if ($i = !$i) {
2669
+ $openCount += substr_count($value,'{');
2670
+ $closeCount += substr_count($value,'}');
2671
+ $value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value);
2672
+ }
2673
+ }
2674
+ unset($value);
2675
+ // Then rebuild the formula string
2676
+ $formula = implode('"',$temp);
2677
+ } else {
2678
+ // If there's no quoted strings, then we do a simple count/replace
2679
+ $openCount = substr_count($formula,'{');
2680
+ $closeCount = substr_count($formula,'}');
2681
+ $formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula);
2682
+ }
2683
+ // Trap for mismatched braces and trigger an appropriate error
2684
+ if ($openCount < $closeCount) {
2685
+ if ($openCount > 0) {
2686
+ return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
2687
+ } else {
2688
+ return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered");
2689
+ }
2690
+ } elseif ($openCount > $closeCount) {
2691
+ if ($closeCount > 0) {
2692
+ return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
2693
+ } else {
2694
+ return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered");
2695
+ }
2696
+ }
2697
+ }
2698
+
2699
+ return $formula;
2700
+ } // function _convertMatrixReferences()
2701
+
2702
+
2703
+ private static function _mkMatrix() {
2704
+ return func_get_args();
2705
+ } // function _mkMatrix()
2706
+
2707
+
2708
+ // Binary Operators
2709
+ // These operators always work on two values
2710
+ // Array key is the operator, the value indicates whether this is a left or right associative operator
2711
+ private static $_operatorAssociativity = array(
2712
+ '^' => 0, // Exponentiation
2713
+ '*' => 0, '/' => 0, // Multiplication and Division
2714
+ '+' => 0, '-' => 0, // Addition and Subtraction
2715
+ '&' => 0, // Concatenation
2716
+ '|' => 0, ':' => 0, // Intersect and Range
2717
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
2718
+ );
2719
+
2720
+ // Comparison (Boolean) Operators
2721
+ // These operators work on two values, but always return a boolean result
2722
+ private static $_comparisonOperators = array('>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE);
2723
+
2724
+ // Operator Precedence
2725
+ // This list includes all valid operators, whether binary (including boolean) or unary (such as %)
2726
+ // Array key is the operator, the value is its precedence
2727
+ private static $_operatorPrecedence = array(
2728
+ ':' => 8, // Range
2729
+ '|' => 7, // Intersect
2730
+ '~' => 6, // Negation
2731
+ '%' => 5, // Percentage
2732
+ '^' => 4, // Exponentiation
2733
+ '*' => 3, '/' => 3, // Multiplication and Division
2734
+ '+' => 2, '-' => 2, // Addition and Subtraction
2735
+ '&' => 1, // Concatenation
2736
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
2737
+ );
2738
+
2739
+ // Convert infix to postfix notation
2740
+ private function _parseFormula($formula, PHPExcel_Cell $pCell = NULL) {
2741
+ if (($formula = $this->_convertMatrixReferences(trim($formula))) === FALSE) {
2742
+ return FALSE;
2743
+ }
2744
+
2745
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
2746
+ // so we store the parent worksheet so that we can re-attach it when necessary
2747
+ $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
2748
+
2749
+ $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION.
2750
+ '|'.self::CALCULATION_REGEXP_CELLREF.
2751
+ '|'.self::CALCULATION_REGEXP_NUMBER.
2752
+ '|'.self::CALCULATION_REGEXP_STRING.
2753
+ '|'.self::CALCULATION_REGEXP_OPENBRACE.
2754
+ '|'.self::CALCULATION_REGEXP_NAMEDRANGE.
2755
+ '|'.self::CALCULATION_REGEXP_ERROR.
2756
+ ')/si';
2757
+
2758
+ // Start with initialisation
2759
+ $index = 0;
2760
+ $stack = new PHPExcel_Calculation_Token_Stack;
2761
+ $output = array();
2762
+ $expectingOperator = FALSE; // We use this test in syntax-checking the expression to determine when a
2763
+ // - is a negation or + is a positive operator rather than an operation
2764
+ $expectingOperand = FALSE; // We use this test in syntax-checking the expression to determine whether an operand
2765
+ // should be null in a function call
2766
+ // The guts of the lexical parser
2767
+ // Loop through the formula extracting each operator and operand in turn
2768
+ while(TRUE) {
2769
+ //echo 'Assessing Expression '.substr($formula, $index),PHP_EOL;
2770
+ $opCharacter = $formula{$index}; // Get the first character of the value at the current index position
2771
+ //echo 'Initial character of expression block is '.$opCharacter,PHP_EOL;
2772
+ if ((isset(self::$_comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$_comparisonOperators[$formula{$index+1}]))) {
2773
+ $opCharacter .= $formula{++$index};
2774
+ //echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL;
2775
+ }
2776
+
2777
+ // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
2778
+ $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
2779
+ //echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').PHP_EOL;
2780
+ //var_dump($match);
2781
+
2782
+ if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
2783
+ //echo 'Element is a Negation operator',PHP_EOL;
2784
+ $stack->push('Unary Operator','~'); // Put a negation on the stack
2785
+ ++$index; // and drop the negation symbol
2786
+ } elseif ($opCharacter == '%' && $expectingOperator) {
2787
+ //echo 'Element is a Percentage operator',PHP_EOL;
2788
+ $stack->push('Unary Operator','%'); // Put a percentage on the stack
2789
+ ++$index;
2790
+ } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
2791
+ //echo 'Element is a Positive number, not Plus operator',PHP_EOL;
2792
+ ++$index; // Drop the redundant plus symbol
2793
+ } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal
2794
+ return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
2795
+
2796
+ } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
2797
+ //echo 'Element with value '.$opCharacter.' is an Operator',PHP_EOL;
2798
+ while($stack->count() > 0 &&
2799
+ ($o2 = $stack->last()) &&
2800
+ isset(self::$_operators[$o2['value']]) &&
2801
+ @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
2802
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
2803
+ }
2804
+ $stack->push('Binary Operator',$opCharacter); // Finally put our current operator onto the stack
2805
+ ++$index;
2806
+ $expectingOperator = FALSE;
2807
+
2808
+ } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis?
2809
+ //echo 'Element is a Closing bracket',PHP_EOL;
2810
+ $expectingOperand = FALSE;
2811
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
2812
+ if ($o2 === NULL) return $this->_raiseFormulaError('Formula Error: Unexpected closing brace ")"');
2813
+ else $output[] = $o2;
2814
+ }
2815
+ $d = $stack->last(2);
2816
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function?
2817
+ $functionName = $matches[1]; // Get the function name
2818
+ //echo 'Closed Function is '.$functionName,PHP_EOL;
2819
+ $d = $stack->pop();
2820
+ $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack)
2821
+ //if ($argumentCount == 0) {
2822
+ // echo 'With no arguments',PHP_EOL;
2823
+ //} elseif ($argumentCount == 1) {
2824
+ // echo 'With 1 argument',PHP_EOL;
2825
+ //} else {
2826
+ // echo 'With '.$argumentCount.' arguments',PHP_EOL;
2827
+ //}
2828
+ $output[] = $d; // Dump the argument count on the output
2829
+ $output[] = $stack->pop(); // Pop the function and push onto the output
2830
+ if (isset(self::$_controlFunctions[$functionName])) {
2831
+ //echo 'Built-in function '.$functionName,PHP_EOL;
2832
+ $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount'];
2833
+ $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
2834
+ } elseif (isset(self::$_PHPExcelFunctions[$functionName])) {
2835
+ //echo 'PHPExcel function '.$functionName,PHP_EOL;
2836
+ $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount'];
2837
+ $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
2838
+ } else { // did we somehow push a non-function on the stack? this should never happen
2839
+ return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack");
2840
+ }
2841
+ // Check the argument count
2842
+ $argumentCountError = FALSE;
2843
+ if (is_numeric($expectedArgumentCount)) {
2844
+ if ($expectedArgumentCount < 0) {
2845
+ //echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount),PHP_EOL;
2846
+ if ($argumentCount > abs($expectedArgumentCount)) {
2847
+ $argumentCountError = TRUE;
2848
+ $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount);
2849
+ }
2850
+ } else {
2851
+ //echo '$expectedArgumentCount is numeric '.$expectedArgumentCount,PHP_EOL;
2852
+ if ($argumentCount != $expectedArgumentCount) {
2853
+ $argumentCountError = TRUE;
2854
+ $expectedArgumentCountString = $expectedArgumentCount;
2855
+ }
2856
+ }
2857
+ } elseif ($expectedArgumentCount != '*') {
2858
+ $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/',$expectedArgumentCount,$argMatch);
2859
+ //print_r($argMatch);
2860
+ //echo PHP_EOL;
2861
+ switch ($argMatch[2]) {
2862
+ case '+' :
2863
+ if ($argumentCount < $argMatch[1]) {
2864
+ $argumentCountError = TRUE;
2865
+ $expectedArgumentCountString = $argMatch[1].' or more ';
2866
+ }
2867
+ break;
2868
+ case '-' :
2869
+ if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
2870
+ $argumentCountError = TRUE;
2871
+ $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3];
2872
+ }
2873
+ break;
2874
+ case ',' :
2875
+ if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
2876
+ $argumentCountError = TRUE;
2877
+ $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3];
2878
+ }
2879
+ break;
2880
+ }
2881
+ }
2882
+ if ($argumentCountError) {
2883
+ return $this->_raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected");
2884
+ }
2885
+ }
2886
+ ++$index;
2887
+
2888
+ } elseif ($opCharacter == ',') { // Is this the separator for function arguments?
2889
+ //echo 'Element is a Function argument separator',PHP_EOL;
2890
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
2891
+ if ($o2 === NULL) return $this->_raiseFormulaError("Formula Error: Unexpected ,");
2892
+ else $output[] = $o2; // pop the argument expression stuff and push onto the output
2893
+ }
2894
+ // If we've a comma when we're expecting an operand, then what we actually have is a null operand;
2895
+ // so push a null onto the stack
2896
+ if (($expectingOperand) || (!$expectingOperator)) {
2897
+ $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL);
2898
+ }
2899
+ // make sure there was a function
2900
+ $d = $stack->last(2);
2901
+ if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches))
2902
+ return $this->_raiseFormulaError("Formula Error: Unexpected ,");
2903
+ $d = $stack->pop();
2904
+ $stack->push($d['type'],++$d['value'],$d['reference']); // increment the argument count
2905
+ $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
2906
+ $expectingOperator = FALSE;
2907
+ $expectingOperand = TRUE;
2908
+ ++$index;
2909
+
2910
+ } elseif ($opCharacter == '(' && !$expectingOperator) {
2911
+ // echo 'Element is an Opening Bracket<br />';
2912
+ $stack->push('Brace', '(');
2913
+ ++$index;
2914
+
2915
+ } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
2916
+ $expectingOperator = TRUE;
2917
+ $expectingOperand = FALSE;
2918
+ $val = $match[1];
2919
+ $length = strlen($val);
2920
+ // echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function<br />';
2921
+
2922
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
2923
+ $val = preg_replace('/\s/u','',$val);
2924
+ // echo 'Element '.$val.' is a Function<br />';
2925
+ if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function
2926
+ $stack->push('Function', strtoupper($val));
2927
+ $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch);
2928
+ if ($ax) {
2929
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
2930
+ $expectingOperator = TRUE;
2931
+ } else {
2932
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
2933
+ $expectingOperator = FALSE;
2934
+ }
2935
+ $stack->push('Brace', '(');
2936
+ } else { // it's a var w/ implicit multiplication
2937
+ $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => NULL);
2938
+ }
2939
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
2940
+ // echo 'Element '.$val.' is a Cell reference<br />';
2941
+ // Watch for this case-change when modifying to allow cell references in different worksheets...
2942
+ // Should only be applied to the actual cell column, not the worksheet name
2943
+
2944
+ // If the last entry on the stack was a : operator, then we have a cell range reference
2945
+ $testPrevOp = $stack->last(1);
2946
+ if ($testPrevOp['value'] == ':') {
2947
+ // If we have a worksheet reference, then we're playing with a 3D reference
2948
+ if ($matches[2] == '') {
2949
+ // Otherwise, we 'inherit' the worksheet reference from the start cell reference
2950
+ // The start of the cell range reference should be the last entry in $output
2951
+ $startCellRef = $output[count($output)-1]['value'];
2952
+ preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
2953
+ if ($startMatches[2] > '') {
2954
+ $val = $startMatches[2].'!'.$val;
2955
+ }
2956
+ } else {
2957
+ return $this->_raiseFormulaError("3D Range references are not yet supported");
2958
+ }
2959
+ }
2960
+
2961
+ $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
2962
+ // $expectingOperator = FALSE;
2963
+ } else { // it's a variable, constant, string, number or boolean
2964
+ // echo 'Element is a Variable, Constant, String, Number or Boolean<br />';
2965
+ // If the last entry on the stack was a : operator, then we may have a row or column range reference
2966
+ $testPrevOp = $stack->last(1);
2967
+ if ($testPrevOp['value'] == ':') {
2968
+ $startRowColRef = $output[count($output)-1]['value'];
2969
+ $rangeWS1 = '';
2970
+ if (strpos('!',$startRowColRef) !== FALSE) {
2971
+ list($rangeWS1,$startRowColRef) = explode('!',$startRowColRef);
2972
+ }
2973
+ if ($rangeWS1 != '') $rangeWS1 .= '!';
2974
+ $rangeWS2 = $rangeWS1;
2975
+ if (strpos('!',$val) !== FALSE) {
2976
+ list($rangeWS2,$val) = explode('!',$val);
2977
+ }
2978
+ if ($rangeWS2 != '') $rangeWS2 .= '!';
2979
+ if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
2980
+ ($startRowColRef <= 1048576) && ($val <= 1048576)) {
2981
+ // Row range
2982
+ $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
2983
+ $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
2984
+ $val = $rangeWS2.$endRowColRef.$val;
2985
+ } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
2986
+ (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
2987
+ // Column range
2988
+ $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
2989
+ $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
2990
+ $val = $rangeWS2.$val.$endRowColRef;
2991
+ }
2992
+ }
2993
+
2994
+ $localeConstant = FALSE;
2995
+ if ($opCharacter == '"') {
2996
+ // echo 'Element is a String<br />';
2997
+ // UnEscape any quotes within the string
2998
+ $val = self::_wrapResult(str_replace('""','"',self::_unwrapResult($val)));
2999
+ } elseif (is_numeric($val)) {
3000
+ // echo 'Element is a Number<br />';
3001
+ if ((strpos($val,'.') !== FALSE) || (stripos($val,'e') !== FALSE) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
3002
+ // echo 'Casting '.$val.' to float<br />';
3003
+ $val = (float) $val;
3004
+ } else {
3005
+ // echo 'Casting '.$val.' to integer<br />';
3006
+ $val = (integer) $val;
3007
+ }
3008
+ } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) {
3009
+ $excelConstant = trim(strtoupper($val));
3010
+ // echo 'Element '.$excelConstant.' is an Excel Constant<br />';
3011
+ $val = self::$_ExcelConstants[$excelConstant];
3012
+ } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== FALSE) {
3013
+ // echo 'Element '.$localeConstant.' is an Excel Constant<br />';
3014
+ $val = self::$_ExcelConstants[$localeConstant];
3015
+ }
3016
+ $details = array('type' => 'Value', 'value' => $val, 'reference' => NULL);
3017
+ if ($localeConstant) { $details['localeValue'] = $localeConstant; }
3018
+ $output[] = $details;
3019
+ }
3020
+ $index += $length;
3021
+
3022
+ } elseif ($opCharacter == '$') { // absolute row or column range
3023
+ ++$index;
3024
+ } elseif ($opCharacter == ')') { // miscellaneous error checking
3025
+ if ($expectingOperand) {
3026
+ $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL);
3027
+ $expectingOperand = FALSE;
3028
+ $expectingOperator = TRUE;
3029
+ } else {
3030
+ return $this->_raiseFormulaError("Formula Error: Unexpected ')'");
3031
+ }
3032
+ } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) {
3033
+ return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
3034
+ } else { // I don't even want to know what you did to get here
3035
+ return $this->_raiseFormulaError("Formula Error: An unexpected error occured");
3036
+ }
3037
+ // Test for end of formula string
3038
+ if ($index == strlen($formula)) {
3039
+ // Did we end with an operator?.
3040
+ // Only valid for the % unary operator
3041
+ if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) {
3042
+ return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
3043
+ } else {
3044
+ break;
3045
+ }
3046
+ }
3047
+ // Ignore white space
3048
+ while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
3049
+ ++$index;
3050
+ }
3051
+ if ($formula{$index} == ' ') {
3052
+ while ($formula{$index} == ' ') {
3053
+ ++$index;
3054
+ }
3055
+ // If we're expecting an operator, but only have a space between the previous and next operands (and both are
3056
+ // Cell References) then we have an INTERSECTION operator
3057
+ // echo 'Possible Intersect Operator<br />';
3058
+ if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
3059
+ ($output[count($output)-1]['type'] == 'Cell Reference')) {
3060
+ // echo 'Element is an Intersect Operator<br />';
3061
+ while($stack->count() > 0 &&
3062
+ ($o2 = $stack->last()) &&
3063
+ isset(self::$_operators[$o2['value']]) &&
3064
+ @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) {
3065
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
3066
+ }
3067
+ $stack->push('Binary Operator','|'); // Put an Intersect Operator on the stack
3068
+ $expectingOperator = FALSE;
3069
+ }
3070
+ }
3071
+ }
3072
+
3073
+ while (($op = $stack->pop()) !== NULL) { // pop everything off the stack and push onto output
3074
+ if ((is_array($op) && $op['value'] == '(') || ($op === '('))
3075
+ return $this->_raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
3076
+ $output[] = $op;
3077
+ }
3078
+ return $output;
3079
+ } // function _parseFormula()
3080
+
3081
+
3082
+ private static function _dataTestReference(&$operandData)
3083
+ {
3084
+ $operand = $operandData['value'];
3085
+ if (($operandData['reference'] === NULL) && (is_array($operand))) {
3086
+ $rKeys = array_keys($operand);
3087
+ $rowKey = array_shift($rKeys);
3088
+ $cKeys = array_keys(array_keys($operand[$rowKey]));
3089
+ $colKey = array_shift($cKeys);
3090
+ if (ctype_upper($colKey)) {
3091
+ $operandData['reference'] = $colKey.$rowKey;
3092
+ }
3093
+ }
3094
+ return $operand;
3095
+ }
3096
+
3097
+ // evaluate postfix notation
3098
+ private function _processTokenStack($tokens, $cellID = NULL, PHPExcel_Cell $pCell = NULL) {
3099
+ if ($tokens == FALSE) return FALSE;
3100
+
3101
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
3102
+ // so we store the parent cell collection so that we can re-attach it when necessary
3103
+ $pCellWorksheet = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
3104
+ $pCellParent = ($pCell !== NULL) ? $pCell->getParent() : null;
3105
+ $stack = new PHPExcel_Calculation_Token_Stack;
3106
+
3107
+ // Loop through each token in turn
3108
+ foreach ($tokens as $tokenData) {
3109
+ // print_r($tokenData);
3110
+ // echo '<br />';
3111
+ $token = $tokenData['value'];
3112
+ // echo '<b>Token is '.$token.'</b><br />';
3113
+ // 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
3114
+ if (isset(self::$_binaryOperators[$token])) {
3115
+ // echo 'Token is a binary operator<br />';
3116
+ // We must have two operands, error if we don't
3117
+ if (($operand2Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
3118
+ if (($operand1Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
3119
+
3120
+ $operand1 = self::_dataTestReference($operand1Data);
3121
+ $operand2 = self::_dataTestReference($operand2Data);
3122
+
3123
+ // Log what we're doing
3124
+ if ($token == ':') {
3125
+ $this->_debugLog->writeDebugLog('Evaluating Range ', $this->_showValue($operand1Data['reference']), ' ', $token, ' ', $this->_showValue($operand2Data['reference']));
3126
+ } else {
3127
+ $this->_debugLog->writeDebugLog('Evaluating ', $this->_showValue($operand1), ' ', $token, ' ', $this->_showValue($operand2));
3128
+ }
3129
+
3130
+ // Process the operation in the appropriate manner
3131
+ switch ($token) {
3132
+ // Comparison (Boolean) Operators
3133
+ case '>' : // Greater than
3134
+ case '<' : // Less than
3135
+ case '>=' : // Greater than or Equal to
3136
+ case '<=' : // Less than or Equal to
3137
+ case '=' : // Equality
3138
+ case '<>' : // Inequality
3139
+ $this->_executeBinaryComparisonOperation($cellID,$operand1,$operand2,$token,$stack);
3140
+ break;
3141
+ // Binary Operators
3142
+ case ':' : // Range
3143
+ $sheet1 = $sheet2 = '';
3144
+ if (strpos($operand1Data['reference'],'!') !== FALSE) {
3145
+ list($sheet1,$operand1Data['reference']) = explode('!',$operand1Data['reference']);
3146
+ } else {
3147
+ $sheet1 = ($pCellParent !== NULL) ? $pCellWorksheet->getTitle() : '';
3148
+ }
3149
+ if (strpos($operand2Data['reference'],'!') !== FALSE) {
3150
+ list($sheet2,$operand2Data['reference']) = explode('!',$operand2Data['reference']);
3151
+ } else {
3152
+ $sheet2 = $sheet1;
3153
+ }
3154
+ if ($sheet1 == $sheet2) {
3155
+ if ($operand1Data['reference'] === NULL) {
3156
+ if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
3157
+ $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
3158
+ } elseif (trim($operand1Data['reference']) == '') {
3159
+ $operand1Data['reference'] = $pCell->getCoordinate();
3160
+ } else {
3161
+ $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
3162
+ }
3163
+ }
3164
+ if ($operand2Data['reference'] === NULL) {
3165
+ if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
3166
+ $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
3167
+ } elseif (trim($operand2Data['reference']) == '') {
3168
+ $operand2Data['reference'] = $pCell->getCoordinate();
3169
+ } else {
3170
+ $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
3171
+ }
3172
+ }
3173
+
3174
+ $oData = array_merge(explode(':',$operand1Data['reference']),explode(':',$operand2Data['reference']));
3175
+ $oCol = $oRow = array();
3176
+ foreach($oData as $oDatum) {
3177
+ $oCR = PHPExcel_Cell::coordinateFromString($oDatum);
3178
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1;
3179
+ $oRow[] = $oCR[1];
3180
+ }
3181
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
3182
+ if ($pCellParent !== NULL) {
3183
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($sheet1), FALSE);
3184
+ } else {
3185
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
3186
+ }
3187
+ $stack->push('Cell Reference',$cellValue,$cellRef);
3188
+ } else {
3189
+ $stack->push('Error',PHPExcel_Calculation_Functions::REF(),NULL);
3190
+ }
3191
+
3192
+ break;
3193
+ case '+' : // Addition
3194
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'plusEquals',$stack);
3195
+ break;
3196
+ case '-' : // Subtraction
3197
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'minusEquals',$stack);
3198
+ break;
3199
+ case '*' : // Multiplication
3200
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayTimesEquals',$stack);
3201
+ break;
3202
+ case '/' : // Division
3203
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayRightDivide',$stack);
3204
+ break;
3205
+ case '^' : // Exponential
3206
+ $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'power',$stack);
3207
+ break;
3208
+ case '&' : // Concatenation
3209
+ // If either of the operands is a matrix, we need to treat them both as matrices
3210
+ // (converting the other operand to a matrix if need be); then perform the required
3211
+ // matrix operation
3212
+ if (is_bool($operand1)) {
3213
+ $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
3214
+ }
3215
+ if (is_bool($operand2)) {
3216
+ $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE'];
3217
+ }
3218
+ if ((is_array($operand1)) || (is_array($operand2))) {
3219
+ // Ensure that both operands are arrays/matrices
3220
+ self::_checkMatrixOperands($operand1,$operand2,2);
3221
+ try {
3222
+ // Convert operand 1 from a PHP array to a matrix
3223
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
3224
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
3225
+ $matrixResult = $matrix->concat($operand2);
3226
+ $result = $matrixResult->getArray();
3227
+ } catch (PHPExcel_Exception $ex) {
3228
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
3229
+ $result = '#VALUE!';
3230
+ }
3231
+ } else {
3232
+ $result = '"'.str_replace('""','"',self::_unwrapResult($operand1,'"').self::_unwrapResult($operand2,'"')).'"';
3233
+ }
3234
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
3235
+ $stack->push('Value',$result);
3236
+ break;
3237
+ case '|' : // Intersect
3238
+ $rowIntersect = array_intersect_key($operand1,$operand2);
3239
+ $cellIntersect = $oCol = $oRow = array();
3240
+ foreach(array_keys($rowIntersect) as $row) {
3241
+ $oRow[] = $row;
3242
+ foreach($rowIntersect[$row] as $col => $data) {
3243
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1;
3244
+ $cellIntersect[$row] = array_intersect_key($operand1[$row],$operand2[$row]);
3245
+ }
3246
+ }
3247
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
3248
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($cellIntersect));
3249
+ $stack->push('Value',$cellIntersect,$cellRef);
3250
+ break;
3251
+ }
3252
+
3253
+ // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
3254
+ } elseif (($token === '~') || ($token === '%')) {
3255
+ // echo 'Token is a unary operator<br />';
3256
+ if (($arg = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack');
3257
+ $arg = $arg['value'];
3258
+ if ($token === '~') {
3259
+ // echo 'Token is a negation operator<br />';
3260
+ $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->_showValue($arg));
3261
+ $multiplier = -1;
3262
+ } else {
3263
+ // echo 'Token is a percentile operator<br />';
3264
+ $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->_showValue($arg));
3265
+ $multiplier = 0.01;
3266
+ }
3267
+ if (is_array($arg)) {
3268
+ self::_checkMatrixOperands($arg,$multiplier,2);
3269
+ try {
3270
+ $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg);
3271
+ $matrixResult = $matrix1->arrayTimesEquals($multiplier);
3272
+ $result = $matrixResult->getArray();
3273
+ } catch (PHPExcel_Exception $ex) {
3274
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
3275
+ $result = '#VALUE!';
3276
+ }
3277
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
3278
+ $stack->push('Value',$result);
3279
+ } else {
3280
+ $this->_executeNumericBinaryOperation($cellID,$multiplier,$arg,'*','arrayTimesEquals',$stack);
3281
+ }
3282
+
3283
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
3284
+ $cellRef = NULL;
3285
+ // echo 'Element '.$token.' is a Cell reference<br />';
3286
+ if (isset($matches[8])) {
3287
+ // echo 'Reference is a Range of cells<br />';
3288
+ if ($pCell === NULL) {
3289
+ // We can't access the range, so return a REF error
3290
+ $cellValue = PHPExcel_Calculation_Functions::REF();
3291
+ } else {
3292
+ $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
3293
+ if ($matches[2] > '') {
3294
+ $matches[2] = trim($matches[2],"\"'");
3295
+ if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) {
3296
+ // It's a Reference to an external workbook (not currently supported)
3297
+ return $this->_raiseFormulaError('Unable to access External Workbook');
3298
+ }
3299
+ $matches[2] = trim($matches[2],"\"'");
3300
+ // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />';
3301
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
3302
+ if ($pCellParent !== NULL) {
3303
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE);
3304
+ } else {
3305
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
3306
+ }
3307
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
3308
+ // $cellRef = $matches[2].'!'.$cellRef;
3309
+ } else {
3310
+ // echo '$cellRef='.$cellRef.' in current worksheet<br />';
3311
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet');
3312
+ if ($pCellParent !== NULL) {
3313
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE);
3314
+ } else {
3315
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
3316
+ }
3317
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
3318
+ }
3319
+ }
3320
+ } else {
3321
+ // echo 'Reference is a single Cell<br />';
3322
+ if ($pCell === NULL) {
3323
+ // We can't access the cell, so return a REF error
3324
+ $cellValue = PHPExcel_Calculation_Functions::REF();
3325
+ } else {
3326
+ $cellRef = $matches[6].$matches[7];
3327
+ if ($matches[2] > '') {
3328
+ $matches[2] = trim($matches[2],"\"'");
3329
+ if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) {
3330
+ // It's a Reference to an external workbook (not currently supported)
3331
+ return $this->_raiseFormulaError('Unable to access External Workbook');
3332
+ }
3333
+ // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />';
3334
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
3335
+ if ($pCellParent !== NULL) {
3336
+ $cellSheet = $this->_workbook->getSheetByName($matches[2]);
3337
+ if ($cellSheet && $cellSheet->cellExists($cellRef)) {
3338
+ $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE);
3339
+ $pCell->attach($pCellParent);
3340
+ } else {
3341
+ $cellValue = NULL;
3342
+ }
3343
+ } else {
3344
+ return $this->_raiseFormulaError('Unable to access Cell Reference');
3345
+ }
3346
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue));
3347
+ // $cellRef = $matches[2].'!'.$cellRef;
3348
+ } else {
3349
+ // echo '$cellRef='.$cellRef.' in current worksheet<br />';
3350
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
3351
+ if ($pCellParent->isDataSet($cellRef)) {
3352
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE);
3353
+ $pCell->attach($pCellParent);
3354
+ } else {
3355
+ $cellValue = NULL;
3356
+ }
3357
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->_showTypeDetails($cellValue));
3358
+ }
3359
+ }
3360
+ }
3361
+ $stack->push('Value',$cellValue,$cellRef);
3362
+
3363
+ // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
3364
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
3365
+ // echo 'Token is a function<br />';
3366
+ $functionName = $matches[1];
3367
+ $argCount = $stack->pop();
3368
+ $argCount = $argCount['value'];
3369
+ if ($functionName != 'MKMATRIX') {
3370
+ $this->_debugLog->writeDebugLog('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
3371
+ }
3372
+ if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function
3373
+ if (isset(self::$_PHPExcelFunctions[$functionName])) {
3374
+ $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall'];
3375
+ $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']);
3376
+ $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']);
3377
+ } elseif (isset(self::$_controlFunctions[$functionName])) {
3378
+ $functionCall = self::$_controlFunctions[$functionName]['functionCall'];
3379
+ $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']);
3380
+ $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']);
3381
+ }
3382
+ // get the arguments for this function
3383
+ // echo 'Function '.$functionName.' expects '.$argCount.' arguments<br />';
3384
+ $args = $argArrayVals = array();
3385
+ for ($i = 0; $i < $argCount; ++$i) {
3386
+ $arg = $stack->pop();
3387
+ $a = $argCount - $i - 1;
3388
+ if (($passByReference) &&
3389
+ (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
3390
+ (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) {
3391
+ if ($arg['reference'] === NULL) {
3392
+ $args[] = $cellID;
3393
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($cellID); }
3394
+ } else {
3395
+ $args[] = $arg['reference'];
3396
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['reference']); }
3397
+ }
3398
+ } else {
3399
+ $args[] = self::_unwrapResult($arg['value']);
3400
+ if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['value']); }
3401
+ }
3402
+ }
3403
+ // Reverse the order of the arguments
3404
+ krsort($args);
3405
+ if (($passByReference) && ($argCount == 0)) {
3406
+ $args[] = $cellID;
3407
+ $argArrayVals[] = $this->_showValue($cellID);
3408
+ }
3409
+ // echo 'Arguments are: ';
3410
+ // print_r($args);
3411
+ // echo '<br />';
3412
+ if ($functionName != 'MKMATRIX') {
3413
+ if ($this->_debugLog->getWriteDebugLog()) {
3414
+ krsort($argArrayVals);
3415
+ $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ',PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )');
3416
+ }
3417
+ }
3418
+ // Process each argument in turn, building the return value as an array
3419
+ // if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
3420
+ // $operand1 = $args[1];
3421
+ // $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->_showValue($operand1));
3422
+ // $result = array();
3423
+ // $row = 0;
3424
+ // foreach($operand1 as $args) {
3425
+ // if (is_array($args)) {
3426
+ // foreach($args as $arg) {
3427
+ // $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )');
3428
+ // $r = call_user_func_array($functionCall,$arg);
3429
+ // $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
3430
+ // $result[$row][] = $r;
3431
+ // }
3432
+ // ++$row;
3433
+ // } else {
3434
+ // $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )');
3435
+ // $r = call_user_func_array($functionCall,$args);
3436
+ // $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r));
3437
+ // $result[] = $r;
3438
+ // }
3439
+ // }
3440
+ // } else {
3441
+ // Process the argument with the appropriate function call
3442
+ if ($passCellReference) {
3443
+ $args[] = $pCell;
3444
+ }
3445
+ if (strpos($functionCall,'::') !== FALSE) {
3446
+ $result = call_user_func_array(explode('::',$functionCall),$args);
3447
+ } else {
3448
+ foreach($args as &$arg) {
3449
+ $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg);
3450
+ }
3451
+ unset($arg);
3452
+ $result = call_user_func_array($functionCall,$args);
3453
+ }
3454
+ // }
3455
+ if ($functionName != 'MKMATRIX') {
3456
+ $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result));
3457
+ }
3458
+ $stack->push('Value',self::_wrapResult($result));
3459
+ }
3460
+
3461
+ } else {
3462
+ // if the token is a number, boolean, string or an Excel error, push it onto the stack
3463
+ if (isset(self::$_ExcelConstants[strtoupper($token)])) {
3464
+ $excelConstant = strtoupper($token);
3465
+ // echo 'Token is a PHPExcel constant: '.$excelConstant.'<br />';
3466
+ $stack->push('Constant Value',self::$_ExcelConstants[$excelConstant]);
3467
+ $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant]));
3468
+ } elseif ((is_numeric($token)) || ($token === NULL) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
3469
+ // echo 'Token is a number, boolean, string, null or an Excel error<br />';
3470
+ $stack->push('Value',$token);
3471
+ // if the token is a named range, push the named range name onto the stack
3472
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
3473
+ // echo 'Token is a named range<br />';
3474
+ $namedRange = $matches[6];
3475
+ // echo 'Named Range is '.$namedRange.'<br />';
3476
+ $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange);
3477
+ $cellValue = $this->extractNamedRange($namedRange, ((NULL !== $pCell) ? $pCellWorksheet : NULL), FALSE);
3478
+ $pCell->attach($pCellParent);
3479
+ $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->_showTypeDetails($cellValue));
3480
+ $stack->push('Named Range',$cellValue,$namedRange);
3481
+ } else {
3482
+ return $this->_raiseFormulaError("undefined variable '$token'");
3483
+ }
3484
+ }
3485
+ }
3486
+ // when we're out of tokens, the stack should have a single element, the final result
3487
+ if ($stack->count() != 1) return $this->_raiseFormulaError("internal error");
3488
+ $output = $stack->pop();
3489
+ $output = $output['value'];
3490
+
3491
+ // if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
3492
+ // return array_shift(PHPExcel_Calculation_Functions::flattenArray($output));
3493
+ // }
3494
+ return $output;
3495
+ } // function _processTokenStack()
3496
+
3497
+
3498
+ private function _validateBinaryOperand($cellID, &$operand, &$stack) {
3499
+ if (is_array($operand)) {
3500
+ if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
3501
+ do {
3502
+ $operand = array_pop($operand);
3503
+ } while (is_array($operand));
3504
+ }
3505
+ }
3506
+ // Numbers, matrices and booleans can pass straight through, as they're already valid
3507
+ if (is_string($operand)) {
3508
+ // We only need special validations for the operand if it is a string
3509
+ // Start by stripping off the quotation marks we use to identify true excel string values internally
3510
+ if ($operand > '' && $operand{0} == '"') { $operand = self::_unwrapResult($operand); }
3511
+ // If the string is a numeric value, we treat it as a numeric, so no further testing
3512
+ if (!is_numeric($operand)) {
3513
+ // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
3514
+ if ($operand > '' && $operand{0} == '#') {
3515
+ $stack->push('Value', $operand);
3516
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($operand));
3517
+ return FALSE;
3518
+ } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) {
3519
+ // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
3520
+ $stack->push('Value', '#VALUE!');
3521
+ $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->_showTypeDetails('#VALUE!'));
3522
+ return FALSE;
3523
+ }
3524
+ }
3525
+ }
3526
+
3527
+ // return a true if the value of the operand is one that we can use in normal binary operations
3528
+ return TRUE;
3529
+ } // function _validateBinaryOperand()
3530
+
3531
+
3532
+ private function _executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays=FALSE) {
3533
+ // If we're dealing with matrix operations, we want a matrix result
3534
+ if ((is_array($operand1)) || (is_array($operand2))) {
3535
+ $result = array();
3536
+ if ((is_array($operand1)) && (!is_array($operand2))) {
3537
+ foreach($operand1 as $x => $operandData) {
3538
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2));
3539
+ $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2,$operation,$stack);
3540
+ $r = $stack->pop();
3541
+ $result[$x] = $r['value'];
3542
+ }
3543
+ } elseif ((!is_array($operand1)) && (is_array($operand2))) {
3544
+ foreach($operand2 as $x => $operandData) {
3545
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operand1), ' ', $operation, ' ', $this->_showValue($operandData));
3546
+ $this->_executeBinaryComparisonOperation($cellID,$operand1,$operandData,$operation,$stack);
3547
+ $r = $stack->pop();
3548
+ $result[$x] = $r['value'];
3549
+ }
3550
+ } else {
3551
+ if (!$recursingArrays) { self::_checkMatrixOperands($operand1,$operand2,2); }
3552
+ foreach($operand1 as $x => $operandData) {
3553
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2[$x]));
3554
+ $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2[$x],$operation,$stack,TRUE);
3555
+ $r = $stack->pop();
3556
+ $result[$x] = $r['value'];
3557
+ }
3558
+ }
3559
+ // Log the result details
3560
+ $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->_showTypeDetails($result));
3561
+ // And push the result onto the stack
3562
+ $stack->push('Array',$result);
3563
+ return TRUE;
3564
+ }
3565
+
3566
+ // Simple validate the two operands if they are string values
3567
+ if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { $operand1 = self::_unwrapResult($operand1); }
3568
+ if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { $operand2 = self::_unwrapResult($operand2); }
3569
+
3570
+ // Use case insensitive comparaison if not OpenOffice mode
3571
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE)
3572
+ {
3573
+ if (is_string($operand1)) {
3574
+ $operand1 = strtoupper($operand1);
3575
+ }
3576
+
3577
+ if (is_string($operand2)) {
3578
+ $operand2 = strtoupper($operand2);
3579
+ }
3580
+ }
3581
+
3582
+ $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE;
3583
+
3584
+ // execute the necessary operation
3585
+ switch ($operation) {
3586
+ // Greater than
3587
+ case '>':
3588
+ if ($useLowercaseFirstComparison) {
3589
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0;
3590
+ } else {
3591
+ $result = ($operand1 > $operand2);
3592
+ }
3593
+ break;
3594
+ // Less than
3595
+ case '<':
3596
+ if ($useLowercaseFirstComparison) {
3597
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0;
3598
+ } else {
3599
+ $result = ($operand1 < $operand2);
3600
+ }
3601
+ break;
3602
+ // Equality
3603
+ case '=':
3604
+ if (is_numeric($operand1) && is_numeric($operand2)) {
3605
+ $result = (abs($operand1 - $operand2) < $this->delta);
3606
+ } else {
3607
+ $result = strcmp($operand1, $operand2) == 0;
3608
+ }
3609
+ break;
3610
+ // Greater than or equal
3611
+ case '>=':
3612
+ if (is_numeric($operand1) && is_numeric($operand2)) {
3613
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 > $operand2));
3614
+ } elseif ($useLowercaseFirstComparison) {
3615
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0;
3616
+ } else {
3617
+ $result = strcmp($operand1, $operand2) >= 0;
3618
+ }
3619
+ break;
3620
+ // Less than or equal
3621
+ case '<=':
3622
+ if (is_numeric($operand1) && is_numeric($operand2)) {
3623
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 < $operand2));
3624
+ } elseif ($useLowercaseFirstComparison) {
3625
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0;
3626
+ } else {
3627
+ $result = strcmp($operand1, $operand2) <= 0;
3628
+ }
3629
+ break;
3630
+ // Inequality
3631
+ case '<>':
3632
+ if (is_numeric($operand1) && is_numeric($operand2)) {
3633
+ $result = (abs($operand1 - $operand2) > 1E-14);
3634
+ } else {
3635
+ $result = strcmp($operand1, $operand2) != 0;
3636
+ }
3637
+ break;
3638
+ }
3639
+
3640
+ // Log the result details
3641
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
3642
+ // And push the result onto the stack
3643
+ $stack->push('Value',$result);
3644
+ return true;
3645
+ }
3646
+
3647
+ /**
3648
+ * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters
3649
+ * @param string $str1 First string value for the comparison
3650
+ * @param string $str2 Second string value for the comparison
3651
+ * @return integer
3652
+ */
3653
+ private function strcmpLowercaseFirst($str1, $str2)
3654
+ {
3655
+ $inversedStr1 = PHPExcel_Shared_String::StrCaseReverse($str1);
3656
+ $inversedStr2 = PHPExcel_Shared_String::StrCaseReverse($str2);
3657
+
3658
+ return strcmp($inversedStr1, $inversedStr2);
3659
+ }
3660
+
3661
+ private function _executeNumericBinaryOperation($cellID,$operand1,$operand2,$operation,$matrixFunction,&$stack) {
3662
+ // Validate the two operands
3663
+ if (!$this->_validateBinaryOperand($cellID,$operand1,$stack)) return FALSE;
3664
+ if (!$this->_validateBinaryOperand($cellID,$operand2,$stack)) return FALSE;
3665
+
3666
+ // If either of the operands is a matrix, we need to treat them both as matrices
3667
+ // (converting the other operand to a matrix if need be); then perform the required
3668
+ // matrix operation
3669
+ if ((is_array($operand1)) || (is_array($operand2))) {
3670
+ // Ensure that both operands are arrays/matrices of the same size
3671
+ self::_checkMatrixOperands($operand1, $operand2, 2);
3672
+
3673
+ try {
3674
+ // Convert operand 1 from a PHP array to a matrix
3675
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
3676
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
3677
+ $matrixResult = $matrix->$matrixFunction($operand2);
3678
+ $result = $matrixResult->getArray();
3679
+ } catch (PHPExcel_Exception $ex) {
3680
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
3681
+ $result = '#VALUE!';
3682
+ }
3683
+ } else {
3684
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
3685
+ ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) ||
3686
+ (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) {
3687
+ $result = PHPExcel_Calculation_Functions::VALUE();
3688
+ } else {
3689
+ // If we're dealing with non-matrix operations, execute the necessary operation
3690
+ switch ($operation) {
3691
+ // Addition
3692
+ case '+':
3693
+ $result = $operand1 + $operand2;
3694
+ break;
3695
+ // Subtraction
3696
+ case '-':
3697
+ $result = $operand1 - $operand2;
3698
+ break;
3699
+ // Multiplication
3700
+ case '*':
3701
+ $result = $operand1 * $operand2;
3702
+ break;
3703
+ // Division
3704
+ case '/':
3705
+ if ($operand2 == 0) {
3706
+ // Trap for Divide by Zero error
3707
+ $stack->push('Value','#DIV/0!');
3708
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails('#DIV/0!'));
3709
+ return FALSE;
3710
+ } else {
3711
+ $result = $operand1 / $operand2;
3712
+ }
3713
+ break;
3714
+ // Power
3715
+ case '^':
3716
+ $result = pow($operand1, $operand2);
3717
+ break;
3718
+ }
3719
+ }
3720
+ }
3721
+
3722
+ // Log the result details
3723
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result));
3724
+ // And push the result onto the stack
3725
+ $stack->push('Value',$result);
3726
+ return TRUE;
3727
+ } // function _executeNumericBinaryOperation()
3728
+
3729
+
3730
+ // trigger an error, but nicely, if need be
3731
+ protected function _raiseFormulaError($errorMessage) {
3732
+ $this->formulaError = $errorMessage;
3733
+ $this->_cyclicReferenceStack->clear();
3734
+ if (!$this->suppressFormulaErrors) throw new PHPExcel_Calculation_Exception($errorMessage);
3735
+ trigger_error($errorMessage, E_USER_ERROR);
3736
+ } // function _raiseFormulaError()
3737
+
3738
+
3739
+ /**
3740
+ * Extract range values
3741
+ *
3742
+ * @param string &$pRange String based range representation
3743
+ * @param PHPExcel_Worksheet $pSheet Worksheet
3744
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
3745
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
3746
+ * @throws PHPExcel_Calculation_Exception
3747
+ */
3748
+ public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = NULL, $resetLog = TRUE) {
3749
+ // Return value
3750
+ $returnValue = array ();
3751
+
3752
+ // echo 'extractCellRange('.$pRange.')',PHP_EOL;
3753
+ if ($pSheet !== NULL) {
3754
+ $pSheetName = $pSheet->getTitle();
3755
+ // echo 'Passed sheet name is '.$pSheetName.PHP_EOL;
3756
+ // echo 'Range reference is '.$pRange.PHP_EOL;
3757
+ if (strpos ($pRange, '!') !== false) {
3758
+ // echo '$pRange reference includes sheet reference',PHP_EOL;
3759
+ list($pSheetName,$pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
3760
+ // echo 'New sheet name is '.$pSheetName,PHP_EOL;
3761
+ // echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
3762
+ $pSheet = $this->_workbook->getSheetByName($pSheetName);
3763
+ }
3764
+
3765
+ // Extract range
3766
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
3767
+ $pRange = $pSheetName.'!'.$pRange;
3768
+ if (!isset($aReferences[1])) {
3769
+ // Single cell in range
3770
+ sscanf($aReferences[0],'%[A-Z]%d', $currentCol, $currentRow);
3771
+ $cellValue = NULL;
3772
+ if ($pSheet->cellExists($aReferences[0])) {
3773
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
3774
+ } else {
3775
+ $returnValue[$currentRow][$currentCol] = NULL;
3776
+ }
3777
+ } else {
3778
+ // Extract cell data for all cells in the range
3779
+ foreach ($aReferences as $reference) {
3780
+ // Extract range
3781
+ sscanf($reference,'%[A-Z]%d', $currentCol, $currentRow);
3782
+ $cellValue = NULL;
3783
+ if ($pSheet->cellExists($reference)) {
3784
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
3785
+ } else {
3786
+ $returnValue[$currentRow][$currentCol] = NULL;
3787
+ }
3788
+ }
3789
+ }
3790
+ }
3791
+
3792
+ // Return
3793
+ return $returnValue;
3794
+ } // function extractCellRange()
3795
+
3796
+
3797
+ /**
3798
+ * Extract range values
3799
+ *
3800
+ * @param string &$pRange String based range representation
3801
+ * @param PHPExcel_Worksheet $pSheet Worksheet
3802
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
3803
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
3804
+ * @throws PHPExcel_Calculation_Exception
3805
+ */
3806
+ public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = NULL, $resetLog = TRUE) {
3807
+ // Return value
3808
+ $returnValue = array ();
3809
+
3810
+ // echo 'extractNamedRange('.$pRange.')<br />';
3811
+ if ($pSheet !== NULL) {
3812
+ $pSheetName = $pSheet->getTitle();
3813
+ // echo 'Current sheet name is '.$pSheetName.'<br />';
3814
+ // echo 'Range reference is '.$pRange.'<br />';
3815
+ if (strpos ($pRange, '!') !== false) {
3816
+ // echo '$pRange reference includes sheet reference',PHP_EOL;
3817
+ list($pSheetName,$pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
3818
+ // echo 'New sheet name is '.$pSheetName,PHP_EOL;
3819
+ // echo 'Adjusted Range reference is '.$pRange,PHP_EOL;
3820
+ $pSheet = $this->_workbook->getSheetByName($pSheetName);
3821
+ }
3822
+
3823
+ // Named range?
3824
+ $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet);
3825
+ if ($namedRange !== NULL) {
3826
+ $pSheet = $namedRange->getWorksheet();
3827
+ // echo 'Named Range '.$pRange.' (';
3828
+ $pRange = $namedRange->getRange();
3829
+ $splitRange = PHPExcel_Cell::splitRange($pRange);
3830
+ // Convert row and column references
3831
+ if (ctype_alpha($splitRange[0][0])) {
3832
+ $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
3833
+ } elseif(ctype_digit($splitRange[0][0])) {
3834
+ $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
3835
+ }
3836
+ // echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'<br />';
3837
+
3838
+ // if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
3839
+ // if (!$namedRange->getLocalOnly()) {
3840
+ // $pSheet = $namedRange->getWorksheet();
3841
+ // } else {
3842
+ // return $returnValue;
3843
+ // }
3844
+ // }
3845
+ } else {
3846
+ return PHPExcel_Calculation_Functions::REF();
3847
+ }
3848
+
3849
+ // Extract range
3850
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
3851
+ // var_dump($aReferences);
3852
+ if (!isset($aReferences[1])) {
3853
+ // Single cell (or single column or row) in range
3854
+ list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]);
3855
+ $cellValue = NULL;
3856
+ if ($pSheet->cellExists($aReferences[0])) {
3857
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
3858
+ } else {
3859
+ $returnValue[$currentRow][$currentCol] = NULL;
3860
+ }
3861
+ } else {
3862
+ // Extract cell data for all cells in the range
3863
+ foreach ($aReferences as $reference) {
3864
+ // Extract range
3865
+ list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($reference);
3866
+ // echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'<br />';
3867
+ $cellValue = NULL;
3868
+ if ($pSheet->cellExists($reference)) {
3869
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
3870
+ } else {
3871
+ $returnValue[$currentRow][$currentCol] = NULL;
3872
+ }
3873
+ }
3874
+ }
3875
+ // print_r($returnValue);
3876
+ // echo '<br />';
3877
+ }
3878
+
3879
+ // Return
3880
+ return $returnValue;
3881
+ } // function extractNamedRange()
3882
+
3883
+
3884
+ /**
3885
+ * Is a specific function implemented?
3886
+ *
3887
+ * @param string $pFunction Function Name
3888
+ * @return boolean
3889
+ */
3890
+ public function isImplemented($pFunction = '') {
3891
+ $pFunction = strtoupper ($pFunction);
3892
+ if (isset(self::$_PHPExcelFunctions[$pFunction])) {
3893
+ return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY');
3894
+ } else {
3895
+ return FALSE;
3896
+ }
3897
+ } // function isImplemented()
3898
+
3899
+
3900
+ /**
3901
+ * Get a list of all implemented functions as an array of function objects
3902
+ *
3903
+ * @return array of PHPExcel_Calculation_Function
3904
+ */
3905
+ public function listFunctions() {
3906
+ // Return value
3907
+ $returnValue = array();
3908
+ // Loop functions
3909
+ foreach(self::$_PHPExcelFunctions as $functionName => $function) {
3910
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
3911
+ $returnValue[$functionName] = new PHPExcel_Calculation_Function($function['category'],
3912
+ $functionName,
3913
+ $function['functionCall']
3914
+ );
3915
+ }
3916
+ }
3917
+
3918
+ // Return
3919
+ return $returnValue;
3920
+ } // function listFunctions()
3921
+
3922
+
3923
+ /**
3924
+ * Get a list of all Excel function names
3925
+ *
3926
+ * @return array
3927
+ */
3928
+ public function listAllFunctionNames() {
3929
+ return array_keys(self::$_PHPExcelFunctions);
3930
+ } // function listAllFunctionNames()
3931
+
3932
+ /**
3933
+ * Get a list of implemented Excel function names
3934
+ *
3935
+ * @return array
3936
+ */
3937
+ public function listFunctionNames() {
3938
+ // Return value
3939
+ $returnValue = array();
3940
+ // Loop functions
3941
+ foreach(self::$_PHPExcelFunctions as $functionName => $function) {
3942
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
3943
+ $returnValue[] = $functionName;
3944
+ }
3945
+ }
3946
+
3947
+ // Return
3948
+ return $returnValue;
3949
+ } // function listFunctionNames()
3950
+
3951
+ } // class PHPExcel_Calculation
3952
+
libraries/PHPExcel/Calculation/Database.php ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_Database
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_Database {
47
+
48
+
49
+ /**
50
+ * __fieldExtract
51
+ *
52
+ * Extracts the column ID to use for the data field.
53
+ *
54
+ * @access private
55
+ * @param mixed[] $database The range of cells that makes up the list or database.
56
+ * A database is a list of related data in which rows of related
57
+ * information are records, and columns of data are fields. The
58
+ * first row of the list contains labels for each column.
59
+ * @param mixed $field Indicates which column is used in the function. Enter the
60
+ * column label enclosed between double quotation marks, such as
61
+ * "Age" or "Yield," or a number (without quotation marks) that
62
+ * represents the position of the column within the list: 1 for
63
+ * the first column, 2 for the second column, and so on.
64
+ * @return string|NULL
65
+ *
66
+ */
67
+ private static function __fieldExtract($database,$field) {
68
+ $field = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($field));
69
+ $fieldNames = array_map('strtoupper',array_shift($database));
70
+
71
+ if (is_numeric($field)) {
72
+ $keys = array_keys($fieldNames);
73
+ return $keys[$field-1];
74
+ }
75
+ $key = array_search($field,$fieldNames);
76
+ return ($key) ? $key : NULL;
77
+ }
78
+
79
+ /**
80
+ * __filter
81
+ *
82
+ * Parses the selection criteria, extracts the database rows that match those criteria, and
83
+ * returns that subset of rows.
84
+ *
85
+ * @access private
86
+ * @param mixed[] $database The range of cells that makes up the list or database.
87
+ * A database is a list of related data in which rows of related
88
+ * information are records, and columns of data are fields. The
89
+ * first row of the list contains labels for each column.
90
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
91
+ * You can use any range for the criteria argument, as long as it
92
+ * includes at least one column label and at least one cell below
93
+ * the column label in which you specify a condition for the
94
+ * column.
95
+ * @return array of mixed
96
+ *
97
+ */
98
+ private static function __filter($database,$criteria) {
99
+ $fieldNames = array_shift($database);
100
+ $criteriaNames = array_shift($criteria);
101
+
102
+ // Convert the criteria into a set of AND/OR conditions with [:placeholders]
103
+ $testConditions = $testValues = array();
104
+ $testConditionsCount = 0;
105
+ foreach($criteriaNames as $key => $criteriaName) {
106
+ $testCondition = array();
107
+ $testConditionCount = 0;
108
+ foreach($criteria as $row => $criterion) {
109
+ if ($criterion[$key] > '') {
110
+ $testCondition[] = '[:'.$criteriaName.']'.PHPExcel_Calculation_Functions::_ifCondition($criterion[$key]);
111
+ $testConditionCount++;
112
+ }
113
+ }
114
+ if ($testConditionCount > 1) {
115
+ $testConditions[] = 'OR('.implode(',',$testCondition).')';
116
+ $testConditionsCount++;
117
+ } elseif($testConditionCount == 1) {
118
+ $testConditions[] = $testCondition[0];
119
+ $testConditionsCount++;
120
+ }
121
+ }
122
+
123
+ if ($testConditionsCount > 1) {
124
+ $testConditionSet = 'AND('.implode(',',$testConditions).')';
125
+ } elseif($testConditionsCount == 1) {
126
+ $testConditionSet = $testConditions[0];
127
+ }
128
+
129
+ // Loop through each row of the database
130
+ foreach($database as $dataRow => $dataValues) {
131
+ // Substitute actual values from the database row for our [:placeholders]
132
+ $testConditionList = $testConditionSet;
133
+ foreach($criteriaNames as $key => $criteriaName) {
134
+ $k = array_search($criteriaName,$fieldNames);
135
+ if (isset($dataValues[$k])) {
136
+ $dataValue = $dataValues[$k];
137
+ $dataValue = (is_string($dataValue)) ? PHPExcel_Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue;
138
+ $testConditionList = str_replace('[:'.$criteriaName.']',$dataValue,$testConditionList);
139
+ }
140
+ }
141
+ // evaluate the criteria against the row data
142
+ $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList);
143
+ // If the row failed to meet the criteria, remove it from the database
144
+ if (!$result) {
145
+ unset($database[$dataRow]);
146
+ }
147
+ }
148
+
149
+ return $database;
150
+ }
151
+
152
+
153
+ /**
154
+ * DAVERAGE
155
+ *
156
+ * Averages the values in a column of a list or database that match conditions you specify.
157
+ *
158
+ * Excel Function:
159
+ * DAVERAGE(database,field,criteria)
160
+ *
161
+ * @access public
162
+ * @category Database Functions
163
+ * @param mixed[] $database The range of cells that makes up the list or database.
164
+ * A database is a list of related data in which rows of related
165
+ * information are records, and columns of data are fields. The
166
+ * first row of the list contains labels for each column.
167
+ * @param string|integer $field Indicates which column is used in the function. Enter the
168
+ * column label enclosed between double quotation marks, such as
169
+ * "Age" or "Yield," or a number (without quotation marks) that
170
+ * represents the position of the column within the list: 1 for
171
+ * the first column, 2 for the second column, and so on.
172
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
173
+ * You can use any range for the criteria argument, as long as it
174
+ * includes at least one column label and at least one cell below
175
+ * the column label in which you specify a condition for the
176
+ * column.
177
+ * @return float
178
+ *
179
+ */
180
+ public static function DAVERAGE($database,$field,$criteria) {
181
+ $field = self::__fieldExtract($database,$field);
182
+ if (is_null($field)) {
183
+ return NULL;
184
+ }
185
+ // reduce the database to a set of rows that match all the criteria
186
+ $database = self::__filter($database,$criteria);
187
+ // extract an array of values for the requested column
188
+ $colData = array();
189
+ foreach($database as $row) {
190
+ $colData[] = $row[$field];
191
+ }
192
+
193
+ // Return
194
+ return PHPExcel_Calculation_Statistical::AVERAGE($colData);
195
+ } // function DAVERAGE()
196
+
197
+
198
+ /**
199
+ * DCOUNT
200
+ *
201
+ * Counts the cells that contain numbers in a column of a list or database that match conditions
202
+ * that you specify.
203
+ *
204
+ * Excel Function:
205
+ * DCOUNT(database,[field],criteria)
206
+ *
207
+ * Excel Function:
208
+ * DAVERAGE(database,field,criteria)
209
+ *
210
+ * @access public
211
+ * @category Database Functions
212
+ * @param mixed[] $database The range of cells that makes up the list or database.
213
+ * A database is a list of related data in which rows of related
214
+ * information are records, and columns of data are fields. The
215
+ * first row of the list contains labels for each column.
216
+ * @param string|integer $field Indicates which column is used in the function. Enter the
217
+ * column label enclosed between double quotation marks, such as
218
+ * "Age" or "Yield," or a number (without quotation marks) that
219
+ * represents the position of the column within the list: 1 for
220
+ * the first column, 2 for the second column, and so on.
221
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
222
+ * You can use any range for the criteria argument, as long as it
223
+ * includes at least one column label and at least one cell below
224
+ * the column label in which you specify a condition for the
225
+ * column.
226
+ * @return integer
227
+ *
228
+ * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
229
+ * database that match the criteria.
230
+ *
231
+ */
232
+ public static function DCOUNT($database,$field,$criteria) {
233
+ $field = self::__fieldExtract($database,$field);
234
+ if (is_null($field)) {
235
+ return NULL;
236
+ }
237
+
238
+ // reduce the database to a set of rows that match all the criteria
239
+ $database = self::__filter($database,$criteria);
240
+ // extract an array of values for the requested column
241
+ $colData = array();
242
+ foreach($database as $row) {
243
+ $colData[] = $row[$field];
244
+ }
245
+
246
+ // Return
247
+ return PHPExcel_Calculation_Statistical::COUNT($colData);
248
+ } // function DCOUNT()
249
+
250
+
251
+ /**
252
+ * DCOUNTA
253
+ *
254
+ * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
255
+ *
256
+ * Excel Function:
257
+ * DCOUNTA(database,[field],criteria)
258
+ *
259
+ * @access public
260
+ * @category Database Functions
261
+ * @param mixed[] $database The range of cells that makes up the list or database.
262
+ * A database is a list of related data in which rows of related
263
+ * information are records, and columns of data are fields. The
264
+ * first row of the list contains labels for each column.
265
+ * @param string|integer $field Indicates which column is used in the function. Enter the
266
+ * column label enclosed between double quotation marks, such as
267
+ * "Age" or "Yield," or a number (without quotation marks) that
268
+ * represents the position of the column within the list: 1 for
269
+ * the first column, 2 for the second column, and so on.
270
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
271
+ * You can use any range for the criteria argument, as long as it
272
+ * includes at least one column label and at least one cell below
273
+ * the column label in which you specify a condition for the
274
+ * column.
275
+ * @return integer
276
+ *
277
+ * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
278
+ * database that match the criteria.
279
+ *
280
+ */
281
+ public static function DCOUNTA($database,$field,$criteria) {
282
+ $field = self::__fieldExtract($database,$field);
283
+ if (is_null($field)) {
284
+ return NULL;
285
+ }
286
+
287
+ // reduce the database to a set of rows that match all the criteria
288
+ $database = self::__filter($database,$criteria);
289
+ // extract an array of values for the requested column
290
+ $colData = array();
291
+ foreach($database as $row) {
292
+ $colData[] = $row[$field];
293
+ }
294
+
295
+ // Return
296
+ return PHPExcel_Calculation_Statistical::COUNTA($colData);
297
+ } // function DCOUNTA()
298
+
299
+
300
+ /**
301
+ * DGET
302
+ *
303
+ * Extracts a single value from a column of a list or database that matches conditions that you
304
+ * specify.
305
+ *
306
+ * Excel Function:
307
+ * DGET(database,field,criteria)
308
+ *
309
+ * @access public
310
+ * @category Database Functions
311
+ * @param mixed[] $database The range of cells that makes up the list or database.
312
+ * A database is a list of related data in which rows of related
313
+ * information are records, and columns of data are fields. The
314
+ * first row of the list contains labels for each column.
315
+ * @param string|integer $field Indicates which column is used in the function. Enter the
316
+ * column label enclosed between double quotation marks, such as
317
+ * "Age" or "Yield," or a number (without quotation marks) that
318
+ * represents the position of the column within the list: 1 for
319
+ * the first column, 2 for the second column, and so on.
320
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
321
+ * You can use any range for the criteria argument, as long as it
322
+ * includes at least one column label and at least one cell below
323
+ * the column label in which you specify a condition for the
324
+ * column.
325
+ * @return mixed
326
+ *
327
+ */
328
+ public static function DGET($database,$field,$criteria) {
329
+ $field = self::__fieldExtract($database,$field);
330
+ if (is_null($field)) {
331
+ return NULL;
332
+ }
333
+
334
+ // reduce the database to a set of rows that match all the criteria
335
+ $database = self::__filter($database,$criteria);
336
+ // extract an array of values for the requested column
337
+ $colData = array();
338
+ foreach($database as $row) {
339
+ $colData[] = $row[$field];
340
+ }
341
+
342
+ // Return
343
+ if (count($colData) > 1) {
344
+ return PHPExcel_Calculation_Functions::NaN();
345
+ }
346
+
347
+ return $colData[0];
348
+ } // function DGET()
349
+
350
+
351
+ /**
352
+ * DMAX
353
+ *
354
+ * Returns the largest number in a column of a list or database that matches conditions you that
355
+ * specify.
356
+ *
357
+ * Excel Function:
358
+ * DMAX(database,field,criteria)
359
+ *
360
+ * @access public
361
+ * @category Database Functions
362
+ * @param mixed[] $database The range of cells that makes up the list or database.
363
+ * A database is a list of related data in which rows of related
364
+ * information are records, and columns of data are fields. The
365
+ * first row of the list contains labels for each column.
366
+ * @param string|integer $field Indicates which column is used in the function. Enter the
367
+ * column label enclosed between double quotation marks, such as
368
+ * "Age" or "Yield," or a number (without quotation marks) that
369
+ * represents the position of the column within the list: 1 for
370
+ * the first column, 2 for the second column, and so on.
371
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
372
+ * You can use any range for the criteria argument, as long as it
373
+ * includes at least one column label and at least one cell below
374
+ * the column label in which you specify a condition for the
375
+ * column.
376
+ * @return float
377
+ *
378
+ */
379
+ public static function DMAX($database,$field,$criteria) {
380
+ $field = self::__fieldExtract($database,$field);
381
+ if (is_null($field)) {
382
+ return NULL;
383
+ }
384
+
385
+ // reduce the database to a set of rows that match all the criteria
386
+ $database = self::__filter($database,$criteria);
387
+ // extract an array of values for the requested column
388
+ $colData = array();
389
+ foreach($database as $row) {
390
+ $colData[] = $row[$field];
391
+ }
392
+
393
+ // Return
394
+ return PHPExcel_Calculation_Statistical::MAX($colData);
395
+ } // function DMAX()
396
+
397
+
398
+ /**
399
+ * DMIN
400
+ *
401
+ * Returns the smallest number in a column of a list or database that matches conditions you that
402
+ * specify.
403
+ *
404
+ * Excel Function:
405
+ * DMIN(database,field,criteria)
406
+ *
407
+ * @access public
408
+ * @category Database Functions
409
+ * @param mixed[] $database The range of cells that makes up the list or database.
410
+ * A database is a list of related data in which rows of related
411
+ * information are records, and columns of data are fields. The
412
+ * first row of the list contains labels for each column.
413
+ * @param string|integer $field Indicates which column is used in the function. Enter the
414
+ * column label enclosed between double quotation marks, such as
415
+ * "Age" or "Yield," or a number (without quotation marks) that
416
+ * represents the position of the column within the list: 1 for
417
+ * the first column, 2 for the second column, and so on.
418
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
419
+ * You can use any range for the criteria argument, as long as it
420
+ * includes at least one column label and at least one cell below
421
+ * the column label in which you specify a condition for the
422
+ * column.
423
+ * @return float
424
+ *
425
+ */
426
+ public static function DMIN($database,$field,$criteria) {
427
+ $field = self::__fieldExtract($database,$field);
428
+ if (is_null($field)) {
429
+ return NULL;
430
+ }
431
+
432
+ // reduce the database to a set of rows that match all the criteria
433
+ $database = self::__filter($database,$criteria);
434
+ // extract an array of values for the requested column
435
+ $colData = array();
436
+ foreach($database as $row) {
437
+ $colData[] = $row[$field];
438
+ }
439
+
440
+ // Return
441
+ return PHPExcel_Calculation_Statistical::MIN($colData);
442
+ } // function DMIN()
443
+
444
+
445
+ /**
446
+ * DPRODUCT
447
+ *
448
+ * Multiplies the values in a column of a list or database that match conditions that you specify.
449
+ *
450
+ * Excel Function:
451
+ * DPRODUCT(database,field,criteria)
452
+ *
453
+ * @access public
454
+ * @category Database Functions
455
+ * @param mixed[] $database The range of cells that makes up the list or database.
456
+ * A database is a list of related data in which rows of related
457
+ * information are records, and columns of data are fields. The
458
+ * first row of the list contains labels for each column.
459
+ * @param string|integer $field Indicates which column is used in the function. Enter the
460
+ * column label enclosed between double quotation marks, such as
461
+ * "Age" or "Yield," or a number (without quotation marks) that
462
+ * represents the position of the column within the list: 1 for
463
+ * the first column, 2 for the second column, and so on.
464
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
465
+ * You can use any range for the criteria argument, as long as it
466
+ * includes at least one column label and at least one cell below
467
+ * the column label in which you specify a condition for the
468
+ * column.
469
+ * @return float
470
+ *
471
+ */
472
+ public static function DPRODUCT($database,$field,$criteria) {
473
+ $field = self::__fieldExtract($database,$field);
474
+ if (is_null($field)) {
475
+ return NULL;
476
+ }
477
+
478
+ // reduce the database to a set of rows that match all the criteria
479
+ $database = self::__filter($database,$criteria);
480
+ // extract an array of values for the requested column
481
+ $colData = array();
482
+ foreach($database as $row) {
483
+ $colData[] = $row[$field];
484
+ }
485
+
486
+ // Return
487
+ return PHPExcel_Calculation_MathTrig::PRODUCT($colData);
488
+ } // function DPRODUCT()
489
+
490
+
491
+ /**
492
+ * DSTDEV
493
+ *
494
+ * Estimates the standard deviation of a population based on a sample by using the numbers in a
495
+ * column of a list or database that match conditions that you specify.
496
+ *
497
+ * Excel Function:
498
+ * DSTDEV(database,field,criteria)
499
+ *
500
+ * @access public
501
+ * @category Database Functions
502
+ * @param mixed[] $database The range of cells that makes up the list or database.
503
+ * A database is a list of related data in which rows of related
504
+ * information are records, and columns of data are fields. The
505
+ * first row of the list contains labels for each column.
506
+ * @param string|integer $field Indicates which column is used in the function. Enter the
507
+ * column label enclosed between double quotation marks, such as
508
+ * "Age" or "Yield," or a number (without quotation marks) that
509
+ * represents the position of the column within the list: 1 for
510
+ * the first column, 2 for the second column, and so on.
511
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
512
+ * You can use any range for the criteria argument, as long as it
513
+ * includes at least one column label and at least one cell below
514
+ * the column label in which you specify a condition for the
515
+ * column.
516
+ * @return float
517
+ *
518
+ */
519
+ public static function DSTDEV($database,$field,$criteria) {
520
+ $field = self::__fieldExtract($database,$field);
521
+ if (is_null($field)) {
522
+ return NULL;
523
+ }
524
+
525
+ // reduce the database to a set of rows that match all the criteria
526
+ $database = self::__filter($database,$criteria);
527
+ // extract an array of values for the requested column
528
+ $colData = array();
529
+ foreach($database as $row) {
530
+ $colData[] = $row[$field];
531
+ }
532
+
533
+ // Return
534
+ return PHPExcel_Calculation_Statistical::STDEV($colData);
535
+ } // function DSTDEV()
536
+
537
+
538
+ /**
539
+ * DSTDEVP
540
+ *
541
+ * Calculates the standard deviation of a population based on the entire population by using the
542
+ * numbers in a column of a list or database that match conditions that you specify.
543
+ *
544
+ * Excel Function:
545
+ * DSTDEVP(database,field,criteria)
546
+ *
547
+ * @access public
548
+ * @category Database Functions
549
+ * @param mixed[] $database The range of cells that makes up the list or database.
550
+ * A database is a list of related data in which rows of related
551
+ * information are records, and columns of data are fields. The
552
+ * first row of the list contains labels for each column.
553
+ * @param string|integer $field Indicates which column is used in the function. Enter the
554
+ * column label enclosed between double quotation marks, such as
555
+ * "Age" or "Yield," or a number (without quotation marks) that
556
+ * represents the position of the column within the list: 1 for
557
+ * the first column, 2 for the second column, and so on.
558
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
559
+ * You can use any range for the criteria argument, as long as it
560
+ * includes at least one column label and at least one cell below
561
+ * the column label in which you specify a condition for the
562
+ * column.
563
+ * @return float
564
+ *
565
+ */
566
+ public static function DSTDEVP($database,$field,$criteria) {
567
+ $field = self::__fieldExtract($database,$field);
568
+ if (is_null($field)) {
569
+ return NULL;
570
+ }
571
+
572
+ // reduce the database to a set of rows that match all the criteria
573
+ $database = self::__filter($database,$criteria);
574
+ // extract an array of values for the requested column
575
+ $colData = array();
576
+ foreach($database as $row) {
577
+ $colData[] = $row[$field];
578
+ }
579
+
580
+ // Return
581
+ return PHPExcel_Calculation_Statistical::STDEVP($colData);
582
+ } // function DSTDEVP()
583
+
584
+
585
+ /**
586
+ * DSUM
587
+ *
588
+ * Adds the numbers in a column of a list or database that match conditions that you specify.
589
+ *
590
+ * Excel Function:
591
+ * DSUM(database,field,criteria)
592
+ *
593
+ * @access public
594
+ * @category Database Functions
595
+ * @param mixed[] $database The range of cells that makes up the list or database.
596
+ * A database is a list of related data in which rows of related
597
+ * information are records, and columns of data are fields. The
598
+ * first row of the list contains labels for each column.
599
+ * @param string|integer $field Indicates which column is used in the function. Enter the
600
+ * column label enclosed between double quotation marks, such as
601
+ * "Age" or "Yield," or a number (without quotation marks) that
602
+ * represents the position of the column within the list: 1 for
603
+ * the first column, 2 for the second column, and so on.
604
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
605
+ * You can use any range for the criteria argument, as long as it
606
+ * includes at least one column label and at least one cell below
607
+ * the column label in which you specify a condition for the
608
+ * column.
609
+ * @return float
610
+ *
611
+ */
612
+ public static function DSUM($database,$field,$criteria) {
613
+ $field = self::__fieldExtract($database,$field);
614
+ if (is_null($field)) {
615
+ return NULL;
616
+ }
617
+
618
+ // reduce the database to a set of rows that match all the criteria
619
+ $database = self::__filter($database,$criteria);
620
+ // extract an array of values for the requested column
621
+ $colData = array();
622
+ foreach($database as $row) {
623
+ $colData[] = $row[$field];
624
+ }
625
+
626
+ // Return
627
+ return PHPExcel_Calculation_MathTrig::SUM($colData);
628
+ } // function DSUM()
629
+
630
+
631
+ /**
632
+ * DVAR
633
+ *
634
+ * Estimates the variance of a population based on a sample by using the numbers in a column
635
+ * of a list or database that match conditions that you specify.
636
+ *
637
+ * Excel Function:
638
+ * DVAR(database,field,criteria)
639
+ *
640
+ * @access public
641
+ * @category Database Functions
642
+ * @param mixed[] $database The range of cells that makes up the list or database.
643
+ * A database is a list of related data in which rows of related
644
+ * information are records, and columns of data are fields. The
645
+ * first row of the list contains labels for each column.
646
+ * @param string|integer $field Indicates which column is used in the function. Enter the
647
+ * column label enclosed between double quotation marks, such as
648
+ * "Age" or "Yield," or a number (without quotation marks) that
649
+ * represents the position of the column within the list: 1 for
650
+ * the first column, 2 for the second column, and so on.
651
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
652
+ * You can use any range for the criteria argument, as long as it
653
+ * includes at least one column label and at least one cell below
654
+ * the column label in which you specify a condition for the
655
+ * column.
656
+ * @return float
657
+ *
658
+ */
659
+ public static function DVAR($database,$field,$criteria) {
660
+ $field = self::__fieldExtract($database,$field);
661
+ if (is_null($field)) {
662
+ return NULL;
663
+ }
664
+
665
+ // reduce the database to a set of rows that match all the criteria
666
+ $database = self::__filter($database,$criteria);
667
+ // extract an array of values for the requested column
668
+ $colData = array();
669
+ foreach($database as $row) {
670
+ $colData[] = $row[$field];
671
+ }
672
+
673
+ // Return
674
+ return PHPExcel_Calculation_Statistical::VARFunc($colData);
675
+ } // function DVAR()
676
+
677
+
678
+ /**
679
+ * DVARP
680
+ *
681
+ * Calculates the variance of a population based on the entire population by using the numbers
682
+ * in a column of a list or database that match conditions that you specify.
683
+ *
684
+ * Excel Function:
685
+ * DVARP(database,field,criteria)
686
+ *
687
+ * @access public
688
+ * @category Database Functions
689
+ * @param mixed[] $database The range of cells that makes up the list or database.
690
+ * A database is a list of related data in which rows of related
691
+ * information are records, and columns of data are fields. The
692
+ * first row of the list contains labels for each column.
693
+ * @param string|integer $field Indicates which column is used in the function. Enter the
694
+ * column label enclosed between double quotation marks, such as
695
+ * "Age" or "Yield," or a number (without quotation marks) that
696
+ * represents the position of the column within the list: 1 for
697
+ * the first column, 2 for the second column, and so on.
698
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
699
+ * You can use any range for the criteria argument, as long as it
700
+ * includes at least one column label and at least one cell below
701
+ * the column label in which you specify a condition for the
702
+ * column.
703
+ * @return float
704
+ *
705
+ */
706
+ public static function DVARP($database,$field,$criteria) {
707
+ $field = self::__fieldExtract($database,$field);
708
+ if (is_null($field)) {
709
+ return NULL;
710
+ }
711
+
712
+ // reduce the database to a set of rows that match all the criteria
713
+ $database = self::__filter($database,$criteria);
714
+ // extract an array of values for the requested column
715
+ $colData = array();
716
+ foreach($database as $row) {
717
+ $colData[] = $row[$field];
718
+ }
719
+
720
+ // Return
721
+ return PHPExcel_Calculation_Statistical::VARP($colData);
722
+ } // function DVARP()
723
+
724
+
725
+ } // class PHPExcel_Calculation_Database
libraries/PHPExcel/Calculation/DateTime.php ADDED
@@ -0,0 +1,1485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_DateTime
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_DateTime {
47
+
48
+ /**
49
+ * Identify if a year is a leap year or not
50
+ *
51
+ * @param integer $year The year to test
52
+ * @return boolean TRUE if the year is a leap year, otherwise FALSE
53
+ */
54
+ public static function _isLeapYear($year) {
55
+ return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
56
+ } // function _isLeapYear()
57
+
58
+
59
+ /**
60
+ * Return the number of days between two dates based on a 360 day calendar
61
+ *
62
+ * @param integer $startDay Day of month of the start date
63
+ * @param integer $startMonth Month of the start date
64
+ * @param integer $startYear Year of the start date
65
+ * @param integer $endDay Day of month of the start date
66
+ * @param integer $endMonth Month of the start date
67
+ * @param integer $endYear Year of the start date
68
+ * @param boolean $methodUS Whether to use the US method or the European method of calculation
69
+ * @return integer Number of days between the start date and the end date
70
+ */
71
+ private static function _dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) {
72
+ if ($startDay == 31) {
73
+ --$startDay;
74
+ } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::_isLeapYear($startYear))))) {
75
+ $startDay = 30;
76
+ }
77
+ if ($endDay == 31) {
78
+ if ($methodUS && $startDay != 30) {
79
+ $endDay = 1;
80
+ if ($endMonth == 12) {
81
+ ++$endYear;
82
+ $endMonth = 1;
83
+ } else {
84
+ ++$endMonth;
85
+ }
86
+ } else {
87
+ $endDay = 30;
88
+ }
89
+ }
90
+
91
+ return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
92
+ } // function _dateDiff360()
93
+
94
+
95
+ /**
96
+ * _getDateValue
97
+ *
98
+ * @param string $dateValue
99
+ * @return mixed Excel date/time serial value, or string if error
100
+ */
101
+ public static function _getDateValue($dateValue) {
102
+ if (!is_numeric($dateValue)) {
103
+ if ((is_string($dateValue)) &&
104
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
105
+ return PHPExcel_Calculation_Functions::VALUE();
106
+ }
107
+ if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
108
+ $dateValue = PHPExcel_Shared_Date::PHPToExcel($dateValue);
109
+ } else {
110
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
111
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
112
+ $dateValue = self::DATEVALUE($dateValue);
113
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
114
+ }
115
+ }
116
+ return $dateValue;
117
+ } // function _getDateValue()
118
+
119
+
120
+ /**
121
+ * _getTimeValue
122
+ *
123
+ * @param string $timeValue
124
+ * @return mixed Excel date/time serial value, or string if error
125
+ */
126
+ private static function _getTimeValue($timeValue) {
127
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
128
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
129
+ $timeValue = self::TIMEVALUE($timeValue);
130
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
131
+ return $timeValue;
132
+ } // function _getTimeValue()
133
+
134
+
135
+ private static function _adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) {
136
+ // Execute function
137
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
138
+ $oMonth = (int) $PHPDateObject->format('m');
139
+ $oYear = (int) $PHPDateObject->format('Y');
140
+
141
+ $adjustmentMonthsString = (string) $adjustmentMonths;
142
+ if ($adjustmentMonths > 0) {
143
+ $adjustmentMonthsString = '+'.$adjustmentMonths;
144
+ }
145
+ if ($adjustmentMonths != 0) {
146
+ $PHPDateObject->modify($adjustmentMonthsString.' months');
147
+ }
148
+ $nMonth = (int) $PHPDateObject->format('m');
149
+ $nYear = (int) $PHPDateObject->format('Y');
150
+
151
+ $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
152
+ if ($monthDiff != $adjustmentMonths) {
153
+ $adjustDays = (int) $PHPDateObject->format('d');
154
+ $adjustDaysString = '-'.$adjustDays.' days';
155
+ $PHPDateObject->modify($adjustDaysString);
156
+ }
157
+ return $PHPDateObject;
158
+ } // function _adjustDateByMonths()
159
+
160
+
161
+ /**
162
+ * DATETIMENOW
163
+ *
164
+ * Returns the current date and time.
165
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
166
+ * calculate a value based on the current date and time, and have that value updated each time you
167
+ * open the worksheet.
168
+ *
169
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
170
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
171
+ *
172
+ * Excel Function:
173
+ * NOW()
174
+ *
175
+ * @access public
176
+ * @category Date/Time Functions
177
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
178
+ * depending on the value of the ReturnDateType flag
179
+ */
180
+ public static function DATETIMENOW() {
181
+ $saveTimeZone = date_default_timezone_get();
182
+ date_default_timezone_set('UTC');
183
+ $retValue = False;
184
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
185
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
186
+ $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time());
187
+ break;
188
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
189
+ $retValue = (integer) time();
190
+ break;
191
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
192
+ $retValue = new DateTime();
193
+ break;
194
+ }
195
+ date_default_timezone_set($saveTimeZone);
196
+
197
+ return $retValue;
198
+ } // function DATETIMENOW()
199
+
200
+
201
+ /**
202
+ * DATENOW
203
+ *
204
+ * Returns the current date.
205
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
206
+ * calculate a value based on the current date and time, and have that value updated each time you
207
+ * open the worksheet.
208
+ *
209
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
210
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
211
+ *
212
+ * Excel Function:
213
+ * TODAY()
214
+ *
215
+ * @access public
216
+ * @category Date/Time Functions
217
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
218
+ * depending on the value of the ReturnDateType flag
219
+ */
220
+ public static function DATENOW() {
221
+ $saveTimeZone = date_default_timezone_get();
222
+ date_default_timezone_set('UTC');
223
+ $retValue = False;
224
+ $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time()));
225
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
226
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
227
+ $retValue = (float) $excelDateTime;
228
+ break;
229
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
230
+ $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime);
231
+ break;
232
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
233
+ $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime);
234
+ break;
235
+ }
236
+ date_default_timezone_set($saveTimeZone);
237
+
238
+ return $retValue;
239
+ } // function DATENOW()
240
+
241
+
242
+ /**
243
+ * DATE
244
+ *
245
+ * The DATE function returns a value that represents a particular date.
246
+ *
247
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
248
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
249
+ *
250
+ * Excel Function:
251
+ * DATE(year,month,day)
252
+ *
253
+ * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
254
+ * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
255
+ * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
256
+ *
257
+ * @access public
258
+ * @category Date/Time Functions
259
+ * @param integer $year The value of the year argument can include one to four digits.
260
+ * Excel interprets the year argument according to the configured
261
+ * date system: 1900 or 1904.
262
+ * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
263
+ * value to 1900 to calculate the year. For example, DATE(108,1,2)
264
+ * returns January 2, 2008 (1900+108).
265
+ * If year is between 1900 and 9999 (inclusive), Excel uses that
266
+ * value as the year. For example, DATE(2008,1,2) returns January 2,
267
+ * 2008.
268
+ * If year is less than 0 or is 10000 or greater, Excel returns the
269
+ * #NUM! error value.
270
+ * @param integer $month A positive or negative integer representing the month of the year
271
+ * from 1 to 12 (January to December).
272
+ * If month is greater than 12, month adds that number of months to
273
+ * the first month in the year specified. For example, DATE(2008,14,2)
274
+ * returns the serial number representing February 2, 2009.
275
+ * If month is less than 1, month subtracts the magnitude of that
276
+ * number of months, plus 1, from the first month in the year
277
+ * specified. For example, DATE(2008,-3,2) returns the serial number
278
+ * representing September 2, 2007.
279
+ * @param integer $day A positive or negative integer representing the day of the month
280
+ * from 1 to 31.
281
+ * If day is greater than the number of days in the month specified,
282
+ * day adds that number of days to the first day in the month. For
283
+ * example, DATE(2008,1,35) returns the serial number representing
284
+ * February 4, 2008.
285
+ * If day is less than 1, day subtracts the magnitude that number of
286
+ * days, plus one, from the first day of the month specified. For
287
+ * example, DATE(2008,1,-15) returns the serial number representing
288
+ * December 16, 2007.
289
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
290
+ * depending on the value of the ReturnDateType flag
291
+ */
292
+ public static function DATE($year = 0, $month = 1, $day = 1) {
293
+ $year = PHPExcel_Calculation_Functions::flattenSingleValue($year);
294
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
295
+ $day = PHPExcel_Calculation_Functions::flattenSingleValue($day);
296
+
297
+ if (($month !== NULL) && (!is_numeric($month))) {
298
+ $month = PHPExcel_Shared_Date::monthStringToNumber($month);
299
+ }
300
+
301
+ if (($day !== NULL) && (!is_numeric($day))) {
302
+ $day = PHPExcel_Shared_Date::dayStringToNumber($day);
303
+ }
304
+
305
+ $year = ($year !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0;
306
+ $month = ($month !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0;
307
+ $day = ($day !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0;
308
+ if ((!is_numeric($year)) ||
309
+ (!is_numeric($month)) ||
310
+ (!is_numeric($day))) {
311
+ return PHPExcel_Calculation_Functions::VALUE();
312
+ }
313
+ $year = (integer) $year;
314
+ $month = (integer) $month;
315
+ $day = (integer) $day;
316
+
317
+ $baseYear = PHPExcel_Shared_Date::getExcelCalendar();
318
+ // Validate parameters
319
+ if ($year < ($baseYear-1900)) {
320
+ return PHPExcel_Calculation_Functions::NaN();
321
+ }
322
+ if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
323
+ return PHPExcel_Calculation_Functions::NaN();
324
+ }
325
+
326
+ if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
327
+ $year += 1900;
328
+ }
329
+
330
+ if ($month < 1) {
331
+ // Handle year/month adjustment if month < 1
332
+ --$month;
333
+ $year += ceil($month / 12) - 1;
334
+ $month = 13 - abs($month % 12);
335
+ } elseif ($month > 12) {
336
+ // Handle year/month adjustment if month > 12
337
+ $year += floor($month / 12);
338
+ $month = ($month % 12);
339
+ }
340
+
341
+ // Re-validate the year parameter after adjustments
342
+ if (($year < $baseYear) || ($year >= 10000)) {
343
+ return PHPExcel_Calculation_Functions::NaN();
344
+ }
345
+
346
+ // Execute function
347
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day);
348
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
349
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
350
+ return (float) $excelDateValue;
351
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
352
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
353
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
354
+ return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue);
355
+ }
356
+ } // function DATE()
357
+
358
+
359
+ /**
360
+ * TIME
361
+ *
362
+ * The TIME function returns a value that represents a particular time.
363
+ *
364
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
365
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
366
+ *
367
+ * Excel Function:
368
+ * TIME(hour,minute,second)
369
+ *
370
+ * @access public
371
+ * @category Date/Time Functions
372
+ * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
373
+ * Any value greater than 23 will be divided by 24 and the remainder
374
+ * will be treated as the hour value. For example, TIME(27,0,0) =
375
+ * TIME(3,0,0) = .125 or 3:00 AM.
376
+ * @param integer $minute A number from 0 to 32767 representing the minute.
377
+ * Any value greater than 59 will be converted to hours and minutes.
378
+ * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
379
+ * @param integer $second A number from 0 to 32767 representing the second.
380
+ * Any value greater than 59 will be converted to hours, minutes,
381
+ * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
382
+ * or 12:33:20 AM
383
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
384
+ * depending on the value of the ReturnDateType flag
385
+ */
386
+ public static function TIME($hour = 0, $minute = 0, $second = 0) {
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 == '') { $hour = 0; }
392
+ if ($minute == '') { $minute = 0; }
393
+ if ($second == '') { $second = 0; }
394
+
395
+ if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
396
+ return PHPExcel_Calculation_Functions::VALUE();
397
+ }
398
+ $hour = (integer) $hour;
399
+ $minute = (integer) $minute;
400
+ $second = (integer) $second;
401
+
402
+ if ($second < 0) {
403
+ $minute += floor($second / 60);
404
+ $second = 60 - abs($second % 60);
405
+ if ($second == 60) { $second = 0; }
406
+ } elseif ($second >= 60) {
407
+ $minute += floor($second / 60);
408
+ $second = $second % 60;
409
+ }
410
+ if ($minute < 0) {
411
+ $hour += floor($minute / 60);
412
+ $minute = 60 - abs($minute % 60);
413
+ if ($minute == 60) { $minute = 0; }
414
+ } elseif ($minute >= 60) {
415
+ $hour += floor($minute / 60);
416
+ $minute = $minute % 60;
417
+ }
418
+
419
+ if ($hour > 23) {
420
+ $hour = $hour % 24;
421
+ } elseif ($hour < 0) {
422
+ return PHPExcel_Calculation_Functions::NaN();
423
+ }
424
+
425
+ // Execute function
426
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
427
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
428
+ $date = 0;
429
+ $calendar = PHPExcel_Shared_Date::getExcelCalendar();
430
+ if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) {
431
+ $date = 1;
432
+ }
433
+ return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
434
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
435
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
436
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
437
+ $dayAdjust = 0;
438
+ if ($hour < 0) {
439
+ $dayAdjust = floor($hour / 24);
440
+ $hour = 24 - abs($hour % 24);
441
+ if ($hour == 24) { $hour = 0; }
442
+ } elseif ($hour >= 24) {
443
+ $dayAdjust = floor($hour / 24);
444
+ $hour = $hour % 24;
445
+ }
446
+ $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
447
+ if ($dayAdjust != 0) {
448
+ $phpDateObject->modify($dayAdjust.' days');
449
+ }
450
+ return $phpDateObject;
451
+ }
452
+ } // function TIME()
453
+
454
+
455
+ /**
456
+ * DATEVALUE
457
+ *
458
+ * Returns a value that represents a particular date.
459
+ * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
460
+ * value.
461
+ *
462
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
463
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
464
+ *
465
+ * Excel Function:
466
+ * DATEVALUE(dateValue)
467
+ *
468
+ * @access public
469
+ * @category Date/Time Functions
470
+ * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
471
+ * For example, "1/30/2008" or "30-Jan-2008" are text strings within
472
+ * quotation marks that represent dates. Using the default date
473
+ * system in Excel for Windows, date_text must represent a date from
474
+ * January 1, 1900, to December 31, 9999. Using the default date
475
+ * system in Excel for the Macintosh, date_text must represent a date
476
+ * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
477
+ * #VALUE! error value if date_text is out of this range.
478
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
479
+ * depending on the value of the ReturnDateType flag
480
+ */
481
+ public static function DATEVALUE($dateValue = 1) {
482
+ $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue),'"');
483
+ // Strip any ordinals because they're allowed in Excel (English only)
484
+ $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui','$1$3',$dateValue);
485
+ // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
486
+ $dateValue = str_replace(array('/','.','-',' '),array(' ',' ',' ',' '),$dateValue);
487
+
488
+ $yearFound = false;
489
+ $t1 = explode(' ',$dateValue);
490
+ foreach($t1 as &$t) {
491
+ if ((is_numeric($t)) && ($t > 31)) {
492
+ if ($yearFound) {
493
+ return PHPExcel_Calculation_Functions::VALUE();
494
+ } else {
495
+ if ($t < 100) { $t += 1900; }
496
+ $yearFound = true;
497
+ }
498
+ }
499
+ }
500
+ if ((count($t1) == 1) && (strpos($t,':') != false)) {
501
+ // We've been fed a time value without any date
502
+ return 0.0;
503
+ } elseif (count($t1) == 2) {
504
+ // We only have two parts of the date: either day/month or month/year
505
+ if ($yearFound) {
506
+ array_unshift($t1,1);
507
+ } else {
508
+ array_push($t1,date('Y'));
509
+ }
510
+ }
511
+ unset($t);
512
+ $dateValue = implode(' ',$t1);
513
+
514
+ $PHPDateArray = date_parse($dateValue);
515
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
516
+ $testVal1 = strtok($dateValue,'- ');
517
+ if ($testVal1 !== False) {
518
+ $testVal2 = strtok('- ');
519
+ if ($testVal2 !== False) {
520
+ $testVal3 = strtok('- ');
521
+ if ($testVal3 === False) {
522
+ $testVal3 = strftime('%Y');
523
+ }
524
+ } else {
525
+ return PHPExcel_Calculation_Functions::VALUE();
526
+ }
527
+ } else {
528
+ return PHPExcel_Calculation_Functions::VALUE();
529
+ }
530
+ $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
531
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
532
+ $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
533
+ if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
534
+ return PHPExcel_Calculation_Functions::VALUE();
535
+ }
536
+ }
537
+ }
538
+
539
+ if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
540
+ // Execute function
541
+ if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); }
542
+ if ($PHPDateArray['year'] < 1900)
543
+ return PHPExcel_Calculation_Functions::VALUE();
544
+ if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); }
545
+ if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); }
546
+ $excelDateValue = floor(PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']));
547
+
548
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
549
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
550
+ return (float) $excelDateValue;
551
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
552
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
553
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
554
+ return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
555
+ }
556
+ }
557
+ return PHPExcel_Calculation_Functions::VALUE();
558
+ } // function DATEVALUE()
559
+
560
+
561
+ /**
562
+ * TIMEVALUE
563
+ *
564
+ * Returns a value that represents a particular time.
565
+ * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
566
+ * value.
567
+ *
568
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
569
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
570
+ *
571
+ * Excel Function:
572
+ * TIMEVALUE(timeValue)
573
+ *
574
+ * @access public
575
+ * @category Date/Time Functions
576
+ * @param string $timeValue A text string that represents a time in any one of the Microsoft
577
+ * Excel time formats; for example, "6:45 PM" and "18:45" text strings
578
+ * within quotation marks that represent time.
579
+ * Date information in time_text is ignored.
580
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
581
+ * depending on the value of the ReturnDateType flag
582
+ */
583
+ public static function TIMEVALUE($timeValue) {
584
+ $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue),'"');
585
+ $timeValue = str_replace(array('/','.'),array('-','-'),$timeValue);
586
+
587
+ $PHPDateArray = date_parse($timeValue);
588
+ if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
589
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
590
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']);
591
+ } else {
592
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1;
593
+ }
594
+
595
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
596
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
597
+ return (float) $excelDateValue;
598
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
599
+ return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;;
600
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
601
+ return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
602
+ }
603
+ }
604
+ return PHPExcel_Calculation_Functions::VALUE();
605
+ } // function TIMEVALUE()
606
+
607
+
608
+ /**
609
+ * DATEDIF
610
+ *
611
+ * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
612
+ * or a standard date string
613
+ * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
614
+ * or a standard date string
615
+ * @param string $unit
616
+ * @return integer Interval between the dates
617
+ */
618
+ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') {
619
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
620
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
621
+ $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit));
622
+
623
+ if (is_string($startDate = self::_getDateValue($startDate))) {
624
+ return PHPExcel_Calculation_Functions::VALUE();
625
+ }
626
+ if (is_string($endDate = self::_getDateValue($endDate))) {
627
+ return PHPExcel_Calculation_Functions::VALUE();
628
+ }
629
+
630
+ // Validate parameters
631
+ if ($startDate >= $endDate) {
632
+ return PHPExcel_Calculation_Functions::NaN();
633
+ }
634
+
635
+ // Execute function
636
+ $difference = $endDate - $startDate;
637
+
638
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
639
+ $startDays = $PHPStartDateObject->format('j');
640
+ $startMonths = $PHPStartDateObject->format('n');
641
+ $startYears = $PHPStartDateObject->format('Y');
642
+
643
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
644
+ $endDays = $PHPEndDateObject->format('j');
645
+ $endMonths = $PHPEndDateObject->format('n');
646
+ $endYears = $PHPEndDateObject->format('Y');
647
+
648
+ $retVal = PHPExcel_Calculation_Functions::NaN();
649
+ switch ($unit) {
650
+ case 'D':
651
+ $retVal = intval($difference);
652
+ break;
653
+ case 'M':
654
+ $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
655
+ // We're only interested in full months
656
+ if ($endDays < $startDays) {
657
+ --$retVal;
658
+ }
659
+ break;
660
+ case 'Y':
661
+ $retVal = intval($endYears - $startYears);
662
+ // We're only interested in full months
663
+ if ($endMonths < $startMonths) {
664
+ --$retVal;
665
+ } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
666
+ --$retVal;
667
+ }
668
+ break;
669
+ case 'MD':
670
+ if ($endDays < $startDays) {
671
+ $retVal = $endDays;
672
+ $PHPEndDateObject->modify('-'.$endDays.' days');
673
+ $adjustDays = $PHPEndDateObject->format('j');
674
+ if ($adjustDays > $startDays) {
675
+ $retVal += ($adjustDays - $startDays);
676
+ }
677
+ } else {
678
+ $retVal = $endDays - $startDays;
679
+ }
680
+ break;
681
+ case 'YM':
682
+ $retVal = intval($endMonths - $startMonths);
683
+ if ($retVal < 0) $retVal = 12 + $retVal;
684
+ // We're only interested in full months
685
+ if ($endDays < $startDays) {
686
+ --$retVal;
687
+ }
688
+ break;
689
+ case 'YD':
690
+ $retVal = intval($difference);
691
+ if ($endYears > $startYears) {
692
+ while ($endYears > $startYears) {
693
+ $PHPEndDateObject->modify('-1 year');
694
+ $endYears = $PHPEndDateObject->format('Y');
695
+ }
696
+ $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
697
+ if ($retVal < 0) { $retVal += 365; }
698
+ }
699
+ break;
700
+ default:
701
+ $retVal = PHPExcel_Calculation_Functions::NaN();
702
+ }
703
+ return $retVal;
704
+ } // function DATEDIF()
705
+
706
+
707
+ /**
708
+ * DAYS360
709
+ *
710
+ * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
711
+ * which is used in some accounting calculations. Use this function to help compute payments if
712
+ * your accounting system is based on twelve 30-day months.
713
+ *
714
+ * Excel Function:
715
+ * DAYS360(startDate,endDate[,method])
716
+ *
717
+ * @access public
718
+ * @category Date/Time Functions
719
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
720
+ * PHP DateTime object, or a standard date string
721
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
722
+ * PHP DateTime object, or a standard date string
723
+ * @param boolean $method US or European Method
724
+ * FALSE or omitted: U.S. (NASD) method. If the starting date is
725
+ * the last day of a month, it becomes equal to the 30th of the
726
+ * same month. If the ending date is the last day of a month and
727
+ * the starting date is earlier than the 30th of a month, the
728
+ * ending date becomes equal to the 1st of the next month;
729
+ * otherwise the ending date becomes equal to the 30th of the
730
+ * same month.
731
+ * TRUE: European method. Starting dates and ending dates that
732
+ * occur on the 31st of a month become equal to the 30th of the
733
+ * same month.
734
+ * @return integer Number of days between start date and end date
735
+ */
736
+ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) {
737
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
738
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
739
+
740
+ if (is_string($startDate = self::_getDateValue($startDate))) {
741
+ return PHPExcel_Calculation_Functions::VALUE();
742
+ }
743
+ if (is_string($endDate = self::_getDateValue($endDate))) {
744
+ return PHPExcel_Calculation_Functions::VALUE();
745
+ }
746
+
747
+ if (!is_bool($method)) {
748
+ return PHPExcel_Calculation_Functions::VALUE();
749
+ }
750
+
751
+ // Execute function
752
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
753
+ $startDay = $PHPStartDateObject->format('j');
754
+ $startMonth = $PHPStartDateObject->format('n');
755
+ $startYear = $PHPStartDateObject->format('Y');
756
+
757
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
758
+ $endDay = $PHPEndDateObject->format('j');
759
+ $endMonth = $PHPEndDateObject->format('n');
760
+ $endYear = $PHPEndDateObject->format('Y');
761
+
762
+ return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
763
+ } // function DAYS360()
764
+
765
+
766
+ /**
767
+ * YEARFRAC
768
+ *
769
+ * Calculates the fraction of the year represented by the number of whole days between two dates
770
+ * (the start_date and the end_date).
771
+ * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
772
+ * obligations to assign to a specific term.
773
+ *
774
+ * Excel Function:
775
+ * YEARFRAC(startDate,endDate[,method])
776
+ *
777
+ * @access public
778
+ * @category Date/Time Functions
779
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
780
+ * PHP DateTime object, or a standard date string
781
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
782
+ * PHP DateTime object, or a standard date string
783
+ * @param integer $method Method used for the calculation
784
+ * 0 or omitted US (NASD) 30/360
785
+ * 1 Actual/actual
786
+ * 2 Actual/360
787
+ * 3 Actual/365
788
+ * 4 European 30/360
789
+ * @return float fraction of the year
790
+ */
791
+ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) {
792
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
793
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
794
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
795
+
796
+ if (is_string($startDate = self::_getDateValue($startDate))) {
797
+ return PHPExcel_Calculation_Functions::VALUE();
798
+ }
799
+ if (is_string($endDate = self::_getDateValue($endDate))) {
800
+ return PHPExcel_Calculation_Functions::VALUE();
801
+ }
802
+
803
+ if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
804
+ switch($method) {
805
+ case 0 :
806
+ return self::DAYS360($startDate,$endDate) / 360;
807
+ case 1 :
808
+ $days = self::DATEDIF($startDate,$endDate);
809
+ $startYear = self::YEAR($startDate);
810
+ $endYear = self::YEAR($endDate);
811
+ $years = $endYear - $startYear + 1;
812
+ $leapDays = 0;
813
+ if ($years == 1) {
814
+ if (self::_isLeapYear($endYear)) {
815
+ $startMonth = self::MONTHOFYEAR($startDate);
816
+ $endMonth = self::MONTHOFYEAR($endDate);
817
+ $endDay = self::DAYOFMONTH($endDate);
818
+ if (($startMonth < 3) ||
819
+ (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
820
+ $leapDays += 1;
821
+ }
822
+ }
823
+ } else {
824
+ for($year = $startYear; $year <= $endYear; ++$year) {
825
+ if ($year == $startYear) {
826
+ $startMonth = self::MONTHOFYEAR($startDate);
827
+ $startDay = self::DAYOFMONTH($startDate);
828
+ if ($startMonth < 3) {
829
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
830
+ }
831
+ } elseif($year == $endYear) {
832
+ $endMonth = self::MONTHOFYEAR($endDate);
833
+ $endDay = self::DAYOFMONTH($endDate);
834
+ if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
835
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
836
+ }
837
+ } else {
838
+ $leapDays += (self::_isLeapYear($year)) ? 1 : 0;
839
+ }
840
+ }
841
+ if ($years == 2) {
842
+ if (($leapDays == 0) && (self::_isLeapYear($startYear)) && ($days > 365)) {
843
+ $leapDays = 1;
844
+ } elseif ($days < 366) {
845
+ $years = 1;
846
+ }
847
+ }
848
+ $leapDays /= $years;
849
+ }
850
+ return $days / (365 + $leapDays);
851
+ case 2 :
852
+ return self::DATEDIF($startDate,$endDate) / 360;
853
+ case 3 :
854
+ return self::DATEDIF($startDate,$endDate) / 365;
855
+ case 4 :
856
+ return self::DAYS360($startDate,$endDate,True) / 360;
857
+ }
858
+ }
859
+ return PHPExcel_Calculation_Functions::VALUE();
860
+ } // function YEARFRAC()
861
+
862
+
863
+ /**
864
+ * NETWORKDAYS
865
+ *
866
+ * Returns the number of whole working days between start_date and end_date. Working days
867
+ * exclude weekends and any dates identified in holidays.
868
+ * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
869
+ * worked during a specific term.
870
+ *
871
+ * Excel Function:
872
+ * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
873
+ *
874
+ * @access public
875
+ * @category Date/Time Functions
876
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
877
+ * PHP DateTime object, or a standard date string
878
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
879
+ * PHP DateTime object, or a standard date string
880
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
881
+ * timestamp (integer), PHP DateTime object, or a standard date
882
+ * strings that will be excluded from the working calendar, such
883
+ * as state and federal holidays and floating holidays.
884
+ * @return integer Interval between the dates
885
+ */
886
+ public static function NETWORKDAYS($startDate,$endDate) {
887
+ // Retrieve the mandatory start and end date that are referenced in the function definition
888
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
889
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
890
+ // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
891
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
892
+ array_shift($dateArgs);
893
+ array_shift($dateArgs);
894
+
895
+ // Validate the start and end dates
896
+ if (is_string($startDate = $sDate = self::_getDateValue($startDate))) {
897
+ return PHPExcel_Calculation_Functions::VALUE();
898
+ }
899
+ $startDate = (float) floor($startDate);
900
+ if (is_string($endDate = $eDate = self::_getDateValue($endDate))) {
901
+ return PHPExcel_Calculation_Functions::VALUE();
902
+ }
903
+ $endDate = (float) floor($endDate);
904
+
905
+ if ($sDate > $eDate) {
906
+ $startDate = $eDate;
907
+ $endDate = $sDate;
908
+ }
909
+
910
+ // Execute function
911
+ $startDoW = 6 - self::DAYOFWEEK($startDate,2);
912
+ if ($startDoW < 0) { $startDoW = 0; }
913
+ $endDoW = self::DAYOFWEEK($endDate,2);
914
+ if ($endDoW >= 6) { $endDoW = 0; }
915
+
916
+ $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
917
+ $partWeekDays = $endDoW + $startDoW;
918
+ if ($partWeekDays > 5) {
919
+ $partWeekDays -= 5;
920
+ }
921
+
922
+ // Test any extra holiday parameters
923
+ $holidayCountedArray = array();
924
+ foreach ($dateArgs as $holidayDate) {
925
+ if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
926
+ return PHPExcel_Calculation_Functions::VALUE();
927
+ }
928
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
929
+ if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
930
+ --$partWeekDays;
931
+ $holidayCountedArray[] = $holidayDate;
932
+ }
933
+ }
934
+ }
935
+
936
+ if ($sDate > $eDate) {
937
+ return 0 - ($wholeWeekDays + $partWeekDays);
938
+ }
939
+ return $wholeWeekDays + $partWeekDays;
940
+ } // function NETWORKDAYS()
941
+
942
+
943
+ /**
944
+ * WORKDAY
945
+ *
946
+ * Returns the date that is the indicated number of working days before or after a date (the
947
+ * starting date). Working days exclude weekends and any dates identified as holidays.
948
+ * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
949
+ * delivery times, or the number of days of work performed.
950
+ *
951
+ * Excel Function:
952
+ * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
953
+ *
954
+ * @access public
955
+ * @category Date/Time Functions
956
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
957
+ * PHP DateTime object, or a standard date string
958
+ * @param integer $endDays The number of nonweekend and nonholiday days before or after
959
+ * startDate. A positive value for days yields a future date; a
960
+ * negative value yields a past date.
961
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
962
+ * timestamp (integer), PHP DateTime object, or a standard date
963
+ * strings that will be excluded from the working calendar, such
964
+ * as state and federal holidays and floating holidays.
965
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
966
+ * depending on the value of the ReturnDateType flag
967
+ */
968
+ public static function WORKDAY($startDate,$endDays) {
969
+ // Retrieve the mandatory start date and days that are referenced in the function definition
970
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
971
+ $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays);
972
+ // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
973
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
974
+ array_shift($dateArgs);
975
+ array_shift($dateArgs);
976
+
977
+ if ((is_string($startDate = self::_getDateValue($startDate))) || (!is_numeric($endDays))) {
978
+ return PHPExcel_Calculation_Functions::VALUE();
979
+ }
980
+ $startDate = (float) floor($startDate);
981
+ $endDays = (int) floor($endDays);
982
+ // If endDays is 0, we always return startDate
983
+ if ($endDays == 0) { return $startDate; }
984
+
985
+ $decrementing = ($endDays < 0) ? True : False;
986
+
987
+ // Adjust the start date if it falls over a weekend
988
+
989
+ $startDoW = self::DAYOFWEEK($startDate,3);
990
+ if (self::DAYOFWEEK($startDate,3) >= 5) {
991
+ $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
992
+ ($decrementing) ? $endDays++ : $endDays--;
993
+ }
994
+
995
+ // Add endDays
996
+ $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
997
+
998
+ // Adjust the calculated end date if it falls over a weekend
999
+ $endDoW = self::DAYOFWEEK($endDate,3);
1000
+ if ($endDoW >= 5) {
1001
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
1002
+ }
1003
+
1004
+ // Test any extra holiday parameters
1005
+ if (!empty($dateArgs)) {
1006
+ $holidayCountedArray = $holidayDates = array();
1007
+ foreach ($dateArgs as $holidayDate) {
1008
+ if (($holidayDate !== NULL) && (trim($holidayDate) > '')) {
1009
+ if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
1010
+ return PHPExcel_Calculation_Functions::VALUE();
1011
+ }
1012
+ if (self::DAYOFWEEK($holidayDate,3) < 5) {
1013
+ $holidayDates[] = $holidayDate;
1014
+ }
1015
+ }
1016
+ }
1017
+ if ($decrementing) {
1018
+ rsort($holidayDates, SORT_NUMERIC);
1019
+ } else {
1020
+ sort($holidayDates, SORT_NUMERIC);
1021
+ }
1022
+ foreach ($holidayDates as $holidayDate) {
1023
+ if ($decrementing) {
1024
+ if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
1025
+ if (!in_array($holidayDate,$holidayCountedArray)) {
1026
+ --$endDate;
1027
+ $holidayCountedArray[] = $holidayDate;
1028
+ }
1029
+ }
1030
+ } else {
1031
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
1032
+ if (!in_array($holidayDate,$holidayCountedArray)) {
1033
+ ++$endDate;
1034
+ $holidayCountedArray[] = $holidayDate;
1035
+ }
1036
+ }
1037
+ }
1038
+ // Adjust the calculated end date if it falls over a weekend
1039
+ $endDoW = self::DAYOFWEEK($endDate,3);
1040
+ if ($endDoW >= 5) {
1041
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
1042
+ }
1043
+
1044
+ }
1045
+ }
1046
+
1047
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1048
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
1049
+ return (float) $endDate;
1050
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
1051
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);
1052
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
1053
+ return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
1054
+ }
1055
+ } // function WORKDAY()
1056
+
1057
+
1058
+ /**
1059
+ * DAYOFMONTH
1060
+ *
1061
+ * Returns the day of the month, for a specified date. The day is given as an integer
1062
+ * ranging from 1 to 31.
1063
+ *
1064
+ * Excel Function:
1065
+ * DAY(dateValue)
1066
+ *
1067
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1068
+ * PHP DateTime object, or a standard date string
1069
+ * @return int Day of the month
1070
+ */
1071
+ public static function DAYOFMONTH($dateValue = 1) {
1072
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1073
+
1074
+ if ($dateValue === null) {
1075
+ $dateValue = 1;
1076
+ } elseif (is_string($dateValue = self::_getDateValue($dateValue))) {
1077
+ return PHPExcel_Calculation_Functions::VALUE();
1078
+ } elseif ($dateValue == 0.0) {
1079
+ return 0;
1080
+ } elseif ($dateValue < 0.0) {
1081
+ return PHPExcel_Calculation_Functions::NaN();
1082
+ }
1083
+
1084
+ // Execute function
1085
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1086
+
1087
+ return (int) $PHPDateObject->format('j');
1088
+ } // function DAYOFMONTH()
1089
+
1090
+
1091
+ /**
1092
+ * DAYOFWEEK
1093
+ *
1094
+ * Returns the day of the week for a specified date. The day is given as an integer
1095
+ * ranging from 0 to 7 (dependent on the requested style).
1096
+ *
1097
+ * Excel Function:
1098
+ * WEEKDAY(dateValue[,style])
1099
+ *
1100
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1101
+ * PHP DateTime object, or a standard date string
1102
+ * @param int $style A number that determines the type of return value
1103
+ * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
1104
+ * 2 Numbers 1 (Monday) through 7 (Sunday).
1105
+ * 3 Numbers 0 (Monday) through 6 (Sunday).
1106
+ * @return int Day of the week value
1107
+ */
1108
+ public static function DAYOFWEEK($dateValue = 1, $style = 1) {
1109
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1110
+ $style = PHPExcel_Calculation_Functions::flattenSingleValue($style);
1111
+
1112
+ if (!is_numeric($style)) {
1113
+ return PHPExcel_Calculation_Functions::VALUE();
1114
+ } elseif (($style < 1) || ($style > 3)) {
1115
+ return PHPExcel_Calculation_Functions::NaN();
1116
+ }
1117
+ $style = floor($style);
1118
+
1119
+ if ($dateValue === null) {
1120
+ $dateValue = 1;
1121
+ } elseif (is_string($dateValue = self::_getDateValue($dateValue))) {
1122
+ return PHPExcel_Calculation_Functions::VALUE();
1123
+ } elseif ($dateValue < 0.0) {
1124
+ return PHPExcel_Calculation_Functions::NaN();
1125
+ }
1126
+
1127
+ // Execute function
1128
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1129
+ $DoW = $PHPDateObject->format('w');
1130
+
1131
+ $firstDay = 1;
1132
+ switch ($style) {
1133
+ case 1: ++$DoW;
1134
+ break;
1135
+ case 2: if ($DoW == 0) { $DoW = 7; }
1136
+ break;
1137
+ case 3: if ($DoW == 0) { $DoW = 7; }
1138
+ $firstDay = 0;
1139
+ --$DoW;
1140
+ break;
1141
+ }
1142
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) {
1143
+ // Test for Excel's 1900 leap year, and introduce the error as required
1144
+ if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
1145
+ --$DoW;
1146
+ if ($DoW < $firstDay) {
1147
+ $DoW += 7;
1148
+ }
1149
+ }
1150
+ }
1151
+
1152
+ return (int) $DoW;
1153
+ } // function DAYOFWEEK()
1154
+
1155
+
1156
+ /**
1157
+ * WEEKOFYEAR
1158
+ *
1159
+ * Returns the week of the year for a specified date.
1160
+ * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
1161
+ * However, there is a European standard that defines the first week as the one with the majority
1162
+ * of days (four or more) falling in the new year. This means that for years in which there are
1163
+ * three days or less in the first week of January, the WEEKNUM function returns week numbers
1164
+ * that are incorrect according to the European standard.
1165
+ *
1166
+ * Excel Function:
1167
+ * WEEKNUM(dateValue[,style])
1168
+ *
1169
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1170
+ * PHP DateTime object, or a standard date string
1171
+ * @param boolean $method Week begins on Sunday or Monday
1172
+ * 1 or omitted Week begins on Sunday.
1173
+ * 2 Week begins on Monday.
1174
+ * @return int Week Number
1175
+ */
1176
+ public static function WEEKOFYEAR($dateValue = 1, $method = 1) {
1177
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1178
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
1179
+
1180
+ if (!is_numeric($method)) {
1181
+ return PHPExcel_Calculation_Functions::VALUE();
1182
+ } elseif (($method < 1) || ($method > 2)) {
1183
+ return PHPExcel_Calculation_Functions::NaN();
1184
+ }
1185
+ $method = floor($method);
1186
+
1187
+ if ($dateValue === null) {
1188
+ $dateValue = 1;
1189
+ } elseif (is_string($dateValue = self::_getDateValue($dateValue))) {
1190
+ return PHPExcel_Calculation_Functions::VALUE();
1191
+ } elseif ($dateValue < 0.0) {
1192
+ return PHPExcel_Calculation_Functions::NaN();
1193
+ }
1194
+
1195
+ // Execute function
1196
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1197
+ $dayOfYear = $PHPDateObject->format('z');
1198
+ $dow = $PHPDateObject->format('w');
1199
+ $PHPDateObject->modify('-'.$dayOfYear.' days');
1200
+ $dow = $PHPDateObject->format('w');
1201
+ $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
1202
+ $dayOfYear -= $daysInFirstWeek;
1203
+ $weekOfYear = ceil($dayOfYear / 7) + 1;
1204
+
1205
+ return (int) $weekOfYear;
1206
+ } // function WEEKOFYEAR()
1207
+
1208
+
1209
+ /**
1210
+ * MONTHOFYEAR
1211
+ *
1212
+ * Returns the month of a date represented by a serial number.
1213
+ * The month is given as an integer, ranging from 1 (January) to 12 (December).
1214
+ *
1215
+ * Excel Function:
1216
+ * MONTH(dateValue)
1217
+ *
1218
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1219
+ * PHP DateTime object, or a standard date string
1220
+ * @return int Month of the year
1221
+ */
1222
+ public static function MONTHOFYEAR($dateValue = 1) {
1223
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1224
+
1225
+ if ($dateValue === null) {
1226
+ $dateValue = 1;
1227
+ } elseif (is_string($dateValue = self::_getDateValue($dateValue))) {
1228
+ return PHPExcel_Calculation_Functions::VALUE();
1229
+ } elseif ($dateValue < 0.0) {
1230
+ return PHPExcel_Calculation_Functions::NaN();
1231
+ }
1232
+
1233
+ // Execute function
1234
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1235
+
1236
+ return (int) $PHPDateObject->format('n');
1237
+ } // function MONTHOFYEAR()
1238
+
1239
+
1240
+ /**
1241
+ * YEAR
1242
+ *
1243
+ * Returns the year corresponding to a date.
1244
+ * The year is returned as an integer in the range 1900-9999.
1245
+ *
1246
+ * Excel Function:
1247
+ * YEAR(dateValue)
1248
+ *
1249
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1250
+ * PHP DateTime object, or a standard date string
1251
+ * @return int Year
1252
+ */
1253
+ public static function YEAR($dateValue = 1) {
1254
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1255
+
1256
+ if ($dateValue === null) {
1257
+ $dateValue = 1;
1258
+ } elseif (is_string($dateValue = self::_getDateValue($dateValue))) {
1259
+ return PHPExcel_Calculation_Functions::VALUE();
1260
+ } elseif ($dateValue < 0.0) {
1261
+ return PHPExcel_Calculation_Functions::NaN();
1262
+ }
1263
+
1264
+ // Execute function
1265
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1266
+
1267
+ return (int) $PHPDateObject->format('Y');
1268
+ } // function YEAR()
1269
+
1270
+
1271
+ /**
1272
+ * HOUROFDAY
1273
+ *
1274
+ * Returns the hour of a time value.
1275
+ * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
1276
+ *
1277
+ * Excel Function:
1278
+ * HOUR(timeValue)
1279
+ *
1280
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1281
+ * PHP DateTime object, or a standard time string
1282
+ * @return int Hour
1283
+ */
1284
+ public static function HOUROFDAY($timeValue = 0) {
1285
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1286
+
1287
+ if (!is_numeric($timeValue)) {
1288
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1289
+ $testVal = strtok($timeValue,'/-: ');
1290
+ if (strlen($testVal) < strlen($timeValue)) {
1291
+ return PHPExcel_Calculation_Functions::VALUE();
1292
+ }
1293
+ }
1294
+ $timeValue = self::_getTimeValue($timeValue);
1295
+ if (is_string($timeValue)) {
1296
+ return PHPExcel_Calculation_Functions::VALUE();
1297
+ }
1298
+ }
1299
+ // Execute function
1300
+ if ($timeValue >= 1) {
1301
+ $timeValue = fmod($timeValue,1);
1302
+ } elseif ($timeValue < 0.0) {
1303
+ return PHPExcel_Calculation_Functions::NaN();
1304
+ }
1305
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1306
+
1307
+ return (int) gmdate('G',$timeValue);
1308
+ } // function HOUROFDAY()
1309
+
1310
+
1311
+ /**
1312
+ * MINUTEOFHOUR
1313
+ *
1314
+ * Returns the minutes of a time value.
1315
+ * The minute is given as an integer, ranging from 0 to 59.
1316
+ *
1317
+ * Excel Function:
1318
+ * MINUTE(timeValue)
1319
+ *
1320
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1321
+ * PHP DateTime object, or a standard time string
1322
+ * @return int Minute
1323
+ */
1324
+ public static function MINUTEOFHOUR($timeValue = 0) {
1325
+ $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1326
+
1327
+ if (!is_numeric($timeValue)) {
1328
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1329
+ $testVal = strtok($timeValue,'/-: ');
1330
+ if (strlen($testVal) < strlen($timeValue)) {
1331
+ return PHPExcel_Calculation_Functions::VALUE();
1332
+ }
1333
+ }
1334
+ $timeValue = self::_getTimeValue($timeValue);
1335
+ if (is_string($timeValue)) {
1336
+ return PHPExcel_Calculation_Functions::VALUE();
1337
+ }
1338
+ }
1339
+ // Execute function
1340
+ if ($timeValue >= 1) {
1341
+ $timeValue = fmod($timeValue,1);
1342
+ } elseif ($timeValue < 0.0) {
1343
+ return PHPExcel_Calculation_Functions::NaN();
1344
+ }
1345
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1346
+
1347
+ return (int) gmdate('i',$timeValue);
1348
+ } // function MINUTEOFHOUR()
1349
+
1350
+
1351
+ /**
1352
+ * SECONDOFMINUTE
1353
+ *
1354
+ * Returns the seconds of a time value.
1355
+ * The second is given as an integer in the range 0 (zero) to 59.
1356
+ *
1357
+ * Excel Function:
1358
+ * SECOND(timeValue)
1359
+ *
1360
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1361
+ * PHP DateTime object, or a standard time string
1362
+ * @return int Second
1363
+ */
1364
+ public static function SECONDOFMINUTE($timeValue = 0) {
1365
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1366
+
1367
+ if (!is_numeric($timeValue)) {
1368
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1369
+ $testVal = strtok($timeValue,'/-: ');
1370
+ if (strlen($testVal) < strlen($timeValue)) {
1371
+ return PHPExcel_Calculation_Functions::VALUE();
1372
+ }
1373
+ }
1374
+ $timeValue = self::_getTimeValue($timeValue);
1375
+ if (is_string($timeValue)) {
1376
+ return PHPExcel_Calculation_Functions::VALUE();
1377
+ }
1378
+ }
1379
+ // Execute function
1380
+ if ($timeValue >= 1) {
1381
+ $timeValue = fmod($timeValue,1);
1382
+ } elseif ($timeValue < 0.0) {
1383
+ return PHPExcel_Calculation_Functions::NaN();
1384
+ }
1385
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1386
+
1387
+ return (int) gmdate('s',$timeValue);
1388
+ } // function SECONDOFMINUTE()
1389
+
1390
+
1391
+ /**
1392
+ * EDATE
1393
+ *
1394
+ * Returns the serial number that represents the date that is the indicated number of months
1395
+ * before or after a specified date (the start_date).
1396
+ * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
1397
+ * as the date of issue.
1398
+ *
1399
+ * Excel Function:
1400
+ * EDATE(dateValue,adjustmentMonths)
1401
+ *
1402
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1403
+ * PHP DateTime object, or a standard date string
1404
+ * @param int $adjustmentMonths The number of months before or after start_date.
1405
+ * A positive value for months yields a future date;
1406
+ * a negative value yields a past date.
1407
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
1408
+ * depending on the value of the ReturnDateType flag
1409
+ */
1410
+ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) {
1411
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1412
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
1413
+
1414
+ if (!is_numeric($adjustmentMonths)) {
1415
+ return PHPExcel_Calculation_Functions::VALUE();
1416
+ }
1417
+ $adjustmentMonths = floor($adjustmentMonths);
1418
+
1419
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
1420
+ return PHPExcel_Calculation_Functions::VALUE();
1421
+ }
1422
+
1423
+ // Execute function
1424
+ $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths);
1425
+
1426
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1427
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
1428
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
1429
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
1430
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
1431
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
1432
+ return $PHPDateObject;
1433
+ }
1434
+ } // function EDATE()
1435
+
1436
+
1437
+ /**
1438
+ * EOMONTH
1439
+ *
1440
+ * Returns the date value for the last day of the month that is the indicated number of months
1441
+ * before or after start_date.
1442
+ * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
1443
+ *
1444
+ * Excel Function:
1445
+ * EOMONTH(dateValue,adjustmentMonths)
1446
+ *
1447
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1448
+ * PHP DateTime object, or a standard date string
1449
+ * @param int $adjustmentMonths The number of months before or after start_date.
1450
+ * A positive value for months yields a future date;
1451
+ * a negative value yields a past date.
1452
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
1453
+ * depending on the value of the ReturnDateType flag
1454
+ */
1455
+ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) {
1456
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1457
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
1458
+
1459
+ if (!is_numeric($adjustmentMonths)) {
1460
+ return PHPExcel_Calculation_Functions::VALUE();
1461
+ }
1462
+ $adjustmentMonths = floor($adjustmentMonths);
1463
+
1464
+ if (is_string($dateValue = self::_getDateValue($dateValue))) {
1465
+ return PHPExcel_Calculation_Functions::VALUE();
1466
+ }
1467
+
1468
+ // Execute function
1469
+ $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1);
1470
+ $adjustDays = (int) $PHPDateObject->format('d');
1471
+ $adjustDaysString = '-'.$adjustDays.' days';
1472
+ $PHPDateObject->modify($adjustDaysString);
1473
+
1474
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1475
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL :
1476
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
1477
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC :
1478
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
1479
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT :
1480
+ return $PHPDateObject;
1481
+ }
1482
+ } // function EOMONTH()
1483
+
1484
+ } // class PHPExcel_Calculation_DateTime
1485
+
libraries/PHPExcel/Calculation/Engineering.php ADDED
@@ -0,0 +1,2505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /** EULER */
40
+ define('EULER', 2.71828182845904523536);
41
+
42
+
43
+ /**
44
+ * PHPExcel_Calculation_Engineering
45
+ *
46
+ * @category PHPExcel
47
+ * @package PHPExcel_Calculation
48
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
49
+ */
50
+ class PHPExcel_Calculation_Engineering {
51
+
52
+ /**
53
+ * Details of the Units of measure that can be used in CONVERTUOM()
54
+ *
55
+ * @var mixed[]
56
+ */
57
+ private static $_conversionUnits = array( 'g' => array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ),
58
+ 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ),
59
+ 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ),
60
+ 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ),
61
+ 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ),
62
+ 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ),
63
+ 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ),
64
+ 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ),
65
+ 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ),
66
+ 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ),
67
+ 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ),
68
+ 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ),
69
+ 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ),
70
+ 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ),
71
+ 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ),
72
+ 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ),
73
+ 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ),
74
+ 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ),
75
+ 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
76
+ 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
77
+ 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
78
+ 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
79
+ 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ),
80
+ 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ),
81
+ 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
82
+ 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
83
+ 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ),
84
+ 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ),
85
+ 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ),
86
+ 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ),
87
+ 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ),
88
+ 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
89
+ 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
90
+ 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
91
+ 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
92
+ 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
93
+ 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
94
+ 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ),
95
+ 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
96
+ 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
97
+ 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
98
+ 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
99
+ 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
100
+ 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
101
+ 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ),
102
+ 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ),
103
+ 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
104
+ 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
105
+ 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
106
+ 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
107
+ 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
108
+ 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
109
+ 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ),
110
+ 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ),
111
+ 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ),
112
+ 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ),
113
+ 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
114
+ 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
115
+ 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ),
116
+ 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ),
117
+ 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ),
118
+ 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ),
119
+ 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True )
120
+ );
121
+
122
+ /**
123
+ * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
124
+ *
125
+ * @var mixed[]
126
+ */
127
+ private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ),
128
+ 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ),
129
+ 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ),
130
+ 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ),
131
+ 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ),
132
+ 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ),
133
+ 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ),
134
+ 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ),
135
+ 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ),
136
+ 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ),
137
+ 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ),
138
+ 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ),
139
+ 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ),
140
+ 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ),
141
+ 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ),
142
+ 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ),
143
+ 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ),
144
+ 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ),
145
+ 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ),
146
+ 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' )
147
+ );
148
+
149
+ /**
150
+ * Details of the Units of measure conversion factors, organised by group
151
+ *
152
+ * @var mixed[]
153
+ */
154
+ private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0,
155
+ 'sg' => 6.85220500053478E-05,
156
+ 'lbm' => 2.20462291469134E-03,
157
+ 'u' => 6.02217000000000E+23,
158
+ 'ozm' => 3.52739718003627E-02
159
+ ),
160
+ 'sg' => array( 'g' => 1.45938424189287E+04,
161
+ 'sg' => 1.0,
162
+ 'lbm' => 3.21739194101647E+01,
163
+ 'u' => 8.78866000000000E+27,
164
+ 'ozm' => 5.14782785944229E+02
165
+ ),
166
+ 'lbm' => array( 'g' => 4.5359230974881148E+02,
167
+ 'sg' => 3.10810749306493E-02,
168
+ 'lbm' => 1.0,
169
+ 'u' => 2.73161000000000E+26,
170
+ 'ozm' => 1.60000023429410E+01
171
+ ),
172
+ 'u' => array( 'g' => 1.66053100460465E-24,
173
+ 'sg' => 1.13782988532950E-28,
174
+ 'lbm' => 3.66084470330684E-27,
175
+ 'u' => 1.0,
176
+ 'ozm' => 5.85735238300524E-26
177
+ ),
178
+ 'ozm' => array( 'g' => 2.83495152079732E+01,
179
+ 'sg' => 1.94256689870811E-03,
180
+ 'lbm' => 6.24999908478882E-02,
181
+ 'u' => 1.70725600000000E+25,
182
+ 'ozm' => 1.0
183
+ )
184
+ ),
185
+ 'Distance' => array( 'm' => array( 'm' => 1.0,
186
+ 'mi' => 6.21371192237334E-04,
187
+ 'Nmi' => 5.39956803455724E-04,
188
+ 'in' => 3.93700787401575E+01,
189
+ 'ft' => 3.28083989501312E+00,
190
+ 'yd' => 1.09361329797891E+00,
191
+ 'ang' => 1.00000000000000E+10,
192
+ 'Pica' => 2.83464566929116E+03
193
+ ),
194
+ 'mi' => array( 'm' => 1.60934400000000E+03,
195
+ 'mi' => 1.0,
196
+ 'Nmi' => 8.68976241900648E-01,
197
+ 'in' => 6.33600000000000E+04,
198
+ 'ft' => 5.28000000000000E+03,
199
+ 'yd' => 1.76000000000000E+03,
200
+ 'ang' => 1.60934400000000E+13,
201
+ 'Pica' => 4.56191999999971E+06
202
+ ),
203
+ 'Nmi' => array( 'm' => 1.85200000000000E+03,
204
+ 'mi' => 1.15077944802354E+00,
205
+ 'Nmi' => 1.0,
206
+ 'in' => 7.29133858267717E+04,
207
+ 'ft' => 6.07611548556430E+03,
208
+ 'yd' => 2.02537182785694E+03,
209
+ 'ang' => 1.85200000000000E+13,
210
+ 'Pica' => 5.24976377952723E+06
211
+ ),
212
+ 'in' => array( 'm' => 2.54000000000000E-02,
213
+ 'mi' => 1.57828282828283E-05,
214
+ 'Nmi' => 1.37149028077754E-05,
215
+ 'in' => 1.0,
216
+ 'ft' => 8.33333333333333E-02,
217
+ 'yd' => 2.77777777686643E-02,
218
+ 'ang' => 2.54000000000000E+08,
219
+ 'Pica' => 7.19999999999955E+01
220
+ ),
221
+ 'ft' => array( 'm' => 3.04800000000000E-01,
222
+ 'mi' => 1.89393939393939E-04,
223
+ 'Nmi' => 1.64578833693305E-04,
224
+ 'in' => 1.20000000000000E+01,
225
+ 'ft' => 1.0,
226
+ 'yd' => 3.33333333223972E-01,
227
+ 'ang' => 3.04800000000000E+09,
228
+ 'Pica' => 8.63999999999946E+02
229
+ ),
230
+ 'yd' => array( 'm' => 9.14400000300000E-01,
231
+ 'mi' => 5.68181818368230E-04,
232
+ 'Nmi' => 4.93736501241901E-04,
233
+ 'in' => 3.60000000118110E+01,
234
+ 'ft' => 3.00000000000000E+00,
235
+ 'yd' => 1.0,
236
+ 'ang' => 9.14400000300000E+09,
237
+ 'Pica' => 2.59200000085023E+03
238
+ ),
239
+ 'ang' => array( 'm' => 1.00000000000000E-10,
240
+ 'mi' => 6.21371192237334E-14,
241
+ 'Nmi' => 5.39956803455724E-14,
242
+ 'in' => 3.93700787401575E-09,
243
+ 'ft' => 3.28083989501312E-10,
244
+ 'yd' => 1.09361329797891E-10,
245
+ 'ang' => 1.0,
246
+ 'Pica' => 2.83464566929116E-07
247
+ ),
248
+ 'Pica' => array( 'm' => 3.52777777777800E-04,
249
+ 'mi' => 2.19205948372629E-07,
250
+ 'Nmi' => 1.90484761219114E-07,
251
+ 'in' => 1.38888888888898E-02,
252
+ 'ft' => 1.15740740740748E-03,
253
+ 'yd' => 3.85802469009251E-04,
254
+ 'ang' => 3.52777777777800E+06,
255
+ 'Pica' => 1.0
256
+ )
257
+ ),
258
+ 'Time' => array( 'yr' => array( 'yr' => 1.0,
259
+ 'day' => 365.25,
260
+ 'hr' => 8766.0,
261
+ 'mn' => 525960.0,
262
+ 'sec' => 31557600.0
263
+ ),
264
+ 'day' => array( 'yr' => 2.73785078713210E-03,
265
+ 'day' => 1.0,
266
+ 'hr' => 24.0,
267
+ 'mn' => 1440.0,
268
+ 'sec' => 86400.0
269
+ ),
270
+ 'hr' => array( 'yr' => 1.14077116130504E-04,
271
+ 'day' => 4.16666666666667E-02,
272
+ 'hr' => 1.0,
273
+ 'mn' => 60.0,
274
+ 'sec' => 3600.0
275
+ ),
276
+ 'mn' => array( 'yr' => 1.90128526884174E-06,
277
+ 'day' => 6.94444444444444E-04,
278
+ 'hr' => 1.66666666666667E-02,
279
+ 'mn' => 1.0,
280
+ 'sec' => 60.0
281
+ ),
282
+ 'sec' => array( 'yr' => 3.16880878140289E-08,
283
+ 'day' => 1.15740740740741E-05,
284
+ 'hr' => 2.77777777777778E-04,
285
+ 'mn' => 1.66666666666667E-02,
286
+ 'sec' => 1.0
287
+ )
288
+ ),
289
+ 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0,
290
+ 'p' => 1.0,
291
+ 'atm' => 9.86923299998193E-06,
292
+ 'at' => 9.86923299998193E-06,
293
+ 'mmHg' => 7.50061707998627E-03
294
+ ),
295
+ 'p' => array( 'Pa' => 1.0,
296
+ 'p' => 1.0,
297
+ 'atm' => 9.86923299998193E-06,
298
+ 'at' => 9.86923299998193E-06,
299
+ 'mmHg' => 7.50061707998627E-03
300
+ ),
301
+ 'atm' => array( 'Pa' => 1.01324996583000E+05,
302
+ 'p' => 1.01324996583000E+05,
303
+ 'atm' => 1.0,
304
+ 'at' => 1.0,
305
+ 'mmHg' => 760.0
306
+ ),
307
+ 'at' => array( 'Pa' => 1.01324996583000E+05,
308
+ 'p' => 1.01324996583000E+05,
309
+ 'atm' => 1.0,
310
+ 'at' => 1.0,
311
+ 'mmHg' => 760.0
312
+ ),
313
+ 'mmHg' => array( 'Pa' => 1.33322363925000E+02,
314
+ 'p' => 1.33322363925000E+02,
315
+ 'atm' => 1.31578947368421E-03,
316
+ 'at' => 1.31578947368421E-03,
317
+ 'mmHg' => 1.0
318
+ )
319
+ ),
320
+ 'Force' => array( 'N' => array( 'N' => 1.0,
321
+ 'dyn' => 1.0E+5,
322
+ 'dy' => 1.0E+5,
323
+ 'lbf' => 2.24808923655339E-01
324
+ ),
325
+ 'dyn' => array( 'N' => 1.0E-5,
326
+ 'dyn' => 1.0,
327
+ 'dy' => 1.0,
328
+ 'lbf' => 2.24808923655339E-06
329
+ ),
330
+ 'dy' => array( 'N' => 1.0E-5,
331
+ 'dyn' => 1.0,
332
+ 'dy' => 1.0,
333
+ 'lbf' => 2.24808923655339E-06
334
+ ),
335
+ 'lbf' => array( 'N' => 4.448222,
336
+ 'dyn' => 4.448222E+5,
337
+ 'dy' => 4.448222E+5,
338
+ 'lbf' => 1.0
339
+ )
340
+ ),
341
+ 'Energy' => array( 'J' => array( 'J' => 1.0,
342
+ 'e' => 9.99999519343231E+06,
343
+ 'c' => 2.39006249473467E-01,
344
+ 'cal' => 2.38846190642017E-01,
345
+ 'eV' => 6.24145700000000E+18,
346
+ 'ev' => 6.24145700000000E+18,
347
+ 'HPh' => 3.72506430801000E-07,
348
+ 'hh' => 3.72506430801000E-07,
349
+ 'Wh' => 2.77777916238711E-04,
350
+ 'wh' => 2.77777916238711E-04,
351
+ 'flb' => 2.37304222192651E+01,
352
+ 'BTU' => 9.47815067349015E-04,
353
+ 'btu' => 9.47815067349015E-04
354
+ ),
355
+ 'e' => array( 'J' => 1.00000048065700E-07,
356
+ 'e' => 1.0,
357
+ 'c' => 2.39006364353494E-08,
358
+ 'cal' => 2.38846305445111E-08,
359
+ 'eV' => 6.24146000000000E+11,
360
+ 'ev' => 6.24146000000000E+11,
361
+ 'HPh' => 3.72506609848824E-14,
362
+ 'hh' => 3.72506609848824E-14,
363
+ 'Wh' => 2.77778049754611E-11,
364
+ 'wh' => 2.77778049754611E-11,
365
+ 'flb' => 2.37304336254586E-06,
366
+ 'BTU' => 9.47815522922962E-11,
367
+ 'btu' => 9.47815522922962E-11
368
+ ),
369
+ 'c' => array( 'J' => 4.18399101363672E+00,
370
+ 'e' => 4.18398900257312E+07,
371
+ 'c' => 1.0,
372
+ 'cal' => 9.99330315287563E-01,
373
+ 'eV' => 2.61142000000000E+19,
374
+ 'ev' => 2.61142000000000E+19,
375
+ 'HPh' => 1.55856355899327E-06,
376
+ 'hh' => 1.55856355899327E-06,
377
+ 'Wh' => 1.16222030532950E-03,
378
+ 'wh' => 1.16222030532950E-03,
379
+ 'flb' => 9.92878733152102E+01,
380
+ 'BTU' => 3.96564972437776E-03,
381
+ 'btu' => 3.96564972437776E-03
382
+ ),
383
+ 'cal' => array( 'J' => 4.18679484613929E+00,
384
+ 'e' => 4.18679283372801E+07,
385
+ 'c' => 1.00067013349059E+00,
386
+ 'cal' => 1.0,
387
+ 'eV' => 2.61317000000000E+19,
388
+ 'ev' => 2.61317000000000E+19,
389
+ 'HPh' => 1.55960800463137E-06,
390
+ 'hh' => 1.55960800463137E-06,
391
+ 'Wh' => 1.16299914807955E-03,
392
+ 'wh' => 1.16299914807955E-03,
393
+ 'flb' => 9.93544094443283E+01,
394
+ 'BTU' => 3.96830723907002E-03,
395
+ 'btu' => 3.96830723907002E-03
396
+ ),
397
+ 'eV' => array( 'J' => 1.60219000146921E-19,
398
+ 'e' => 1.60218923136574E-12,
399
+ 'c' => 3.82933423195043E-20,
400
+ 'cal' => 3.82676978535648E-20,
401
+ 'eV' => 1.0,
402
+ 'ev' => 1.0,
403
+ 'HPh' => 5.96826078912344E-26,
404
+ 'hh' => 5.96826078912344E-26,
405
+ 'Wh' => 4.45053000026614E-23,
406
+ 'wh' => 4.45053000026614E-23,
407
+ 'flb' => 3.80206452103492E-18,
408
+ 'BTU' => 1.51857982414846E-22,
409
+ 'btu' => 1.51857982414846E-22
410
+ ),
411
+ 'ev' => array( 'J' => 1.60219000146921E-19,
412
+ 'e' => 1.60218923136574E-12,
413
+ 'c' => 3.82933423195043E-20,
414
+ 'cal' => 3.82676978535648E-20,
415
+ 'eV' => 1.0,
416
+ 'ev' => 1.0,
417
+ 'HPh' => 5.96826078912344E-26,
418
+ 'hh' => 5.96826078912344E-26,
419
+ 'Wh' => 4.45053000026614E-23,
420
+ 'wh' => 4.45053000026614E-23,
421
+ 'flb' => 3.80206452103492E-18,
422
+ 'BTU' => 1.51857982414846E-22,
423
+ 'btu' => 1.51857982414846E-22
424
+ ),
425
+ 'HPh' => array( 'J' => 2.68451741316170E+06,
426
+ 'e' => 2.68451612283024E+13,
427
+ 'c' => 6.41616438565991E+05,
428
+ 'cal' => 6.41186757845835E+05,
429
+ 'eV' => 1.67553000000000E+25,
430
+ 'ev' => 1.67553000000000E+25,
431
+ 'HPh' => 1.0,
432
+ 'hh' => 1.0,
433
+ 'Wh' => 7.45699653134593E+02,
434
+ 'wh' => 7.45699653134593E+02,
435
+ 'flb' => 6.37047316692964E+07,
436
+ 'BTU' => 2.54442605275546E+03,
437
+ 'btu' => 2.54442605275546E+03
438
+ ),
439
+ 'hh' => array( 'J' => 2.68451741316170E+06,
440
+ 'e' => 2.68451612283024E+13,
441
+ 'c' => 6.41616438565991E+05,
442
+ 'cal' => 6.41186757845835E+05,
443
+ 'eV' => 1.67553000000000E+25,
444
+ 'ev' => 1.67553000000000E+25,
445
+ 'HPh' => 1.0,
446
+ 'hh' => 1.0,
447
+ 'Wh' => 7.45699653134593E+02,
448
+ 'wh' => 7.45699653134593E+02,
449
+ 'flb' => 6.37047316692964E+07,
450
+ 'BTU' => 2.54442605275546E+03,
451
+ 'btu' => 2.54442605275546E+03
452
+ ),
453
+ 'Wh' => array( 'J' => 3.59999820554720E+03,
454
+ 'e' => 3.59999647518369E+10,
455
+ 'c' => 8.60422069219046E+02,
456
+ 'cal' => 8.59845857713046E+02,
457
+ 'eV' => 2.24692340000000E+22,
458
+ 'ev' => 2.24692340000000E+22,
459
+ 'HPh' => 1.34102248243839E-03,
460
+ 'hh' => 1.34102248243839E-03,
461
+ 'Wh' => 1.0,
462
+ 'wh' => 1.0,
463
+ 'flb' => 8.54294774062316E+04,
464
+ 'BTU' => 3.41213254164705E+00,
465
+ 'btu' => 3.41213254164705E+00
466
+ ),
467
+ 'wh' => array( 'J' => 3.59999820554720E+03,
468
+ 'e' => 3.59999647518369E+10,
469
+ 'c' => 8.60422069219046E+02,
470
+ 'cal' => 8.59845857713046E+02,
471
+ 'eV' => 2.24692340000000E+22,
472
+ 'ev' => 2.24692340000000E+22,
473
+ 'HPh' => 1.34102248243839E-03,
474
+ 'hh' => 1.34102248243839E-03,
475
+ 'Wh' => 1.0,
476
+ 'wh' => 1.0,
477
+ 'flb' => 8.54294774062316E+04,
478
+ 'BTU' => 3.41213254164705E+00,
479
+ 'btu' => 3.41213254164705E+00
480
+ ),
481
+ 'flb' => array( 'J' => 4.21400003236424E-02,
482
+ 'e' => 4.21399800687660E+05,
483
+ 'c' => 1.00717234301644E-02,
484
+ 'cal' => 1.00649785509554E-02,
485
+ 'eV' => 2.63015000000000E+17,
486
+ 'ev' => 2.63015000000000E+17,
487
+ 'HPh' => 1.56974211145130E-08,
488
+ 'hh' => 1.56974211145130E-08,
489
+ 'Wh' => 1.17055614802000E-05,
490
+ 'wh' => 1.17055614802000E-05,
491
+ 'flb' => 1.0,
492
+ 'BTU' => 3.99409272448406E-05,
493
+ 'btu' => 3.99409272448406E-05
494
+ ),
495
+ 'BTU' => array( 'J' => 1.05505813786749E+03,
496
+ 'e' => 1.05505763074665E+10,
497
+ 'c' => 2.52165488508168E+02,
498
+ 'cal' => 2.51996617135510E+02,
499
+ 'eV' => 6.58510000000000E+21,
500
+ 'ev' => 6.58510000000000E+21,
501
+ 'HPh' => 3.93015941224568E-04,
502
+ 'hh' => 3.93015941224568E-04,
503
+ 'Wh' => 2.93071851047526E-01,
504
+ 'wh' => 2.93071851047526E-01,
505
+ 'flb' => 2.50369750774671E+04,
506
+ 'BTU' => 1.0,
507
+ 'btu' => 1.0,
508
+ ),
509
+ 'btu' => array( 'J' => 1.05505813786749E+03,
510
+ 'e' => 1.05505763074665E+10,
511
+ 'c' => 2.52165488508168E+02,
512
+ 'cal' => 2.51996617135510E+02,
513
+ 'eV' => 6.58510000000000E+21,
514
+ 'ev' => 6.58510000000000E+21,
515
+ 'HPh' => 3.93015941224568E-04,
516
+ 'hh' => 3.93015941224568E-04,
517
+ 'Wh' => 2.93071851047526E-01,
518
+ 'wh' => 2.93071851047526E-01,
519
+ 'flb' => 2.50369750774671E+04,
520
+ 'BTU' => 1.0,
521
+ 'btu' => 1.0,
522
+ )
523
+ ),
524
+ 'Power' => array( 'HP' => array( 'HP' => 1.0,
525
+ 'h' => 1.0,
526
+ 'W' => 7.45701000000000E+02,
527
+ 'w' => 7.45701000000000E+02
528
+ ),
529
+ 'h' => array( 'HP' => 1.0,
530
+ 'h' => 1.0,
531
+ 'W' => 7.45701000000000E+02,
532
+ 'w' => 7.45701000000000E+02
533
+ ),
534
+ 'W' => array( 'HP' => 1.34102006031908E-03,
535
+ 'h' => 1.34102006031908E-03,
536
+ 'W' => 1.0,
537
+ 'w' => 1.0
538
+ ),
539
+ 'w' => array( 'HP' => 1.34102006031908E-03,
540
+ 'h' => 1.34102006031908E-03,
541
+ 'W' => 1.0,
542
+ 'w' => 1.0
543
+ )
544
+ ),
545
+ 'Magnetism' => array( 'T' => array( 'T' => 1.0,
546
+ 'ga' => 10000.0
547
+ ),
548
+ 'ga' => array( 'T' => 0.0001,
549
+ 'ga' => 1.0
550
+ )
551
+ ),
552
+ 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0,
553
+ 'tbs' => 3.33333333333333E-01,
554
+ 'oz' => 1.66666666666667E-01,
555
+ 'cup' => 2.08333333333333E-02,
556
+ 'pt' => 1.04166666666667E-02,
557
+ 'us_pt' => 1.04166666666667E-02,
558
+ 'uk_pt' => 8.67558516821960E-03,
559
+ 'qt' => 5.20833333333333E-03,
560
+ 'gal' => 1.30208333333333E-03,
561
+ 'l' => 4.92999408400710E-03,
562
+ 'lt' => 4.92999408400710E-03
563
+ ),
564
+ 'tbs' => array( 'tsp' => 3.00000000000000E+00,
565
+ 'tbs' => 1.0,
566
+ 'oz' => 5.00000000000000E-01,
567
+ 'cup' => 6.25000000000000E-02,
568
+ 'pt' => 3.12500000000000E-02,
569
+ 'us_pt' => 3.12500000000000E-02,
570
+ 'uk_pt' => 2.60267555046588E-02,
571
+ 'qt' => 1.56250000000000E-02,
572
+ 'gal' => 3.90625000000000E-03,
573
+ 'l' => 1.47899822520213E-02,
574
+ 'lt' => 1.47899822520213E-02
575
+ ),
576
+ 'oz' => array( 'tsp' => 6.00000000000000E+00,
577
+ 'tbs' => 2.00000000000000E+00,
578
+ 'oz' => 1.0,
579
+ 'cup' => 1.25000000000000E-01,
580
+ 'pt' => 6.25000000000000E-02,
581
+ 'us_pt' => 6.25000000000000E-02,
582
+ 'uk_pt' => 5.20535110093176E-02,
583
+ 'qt' => 3.12500000000000E-02,
584
+ 'gal' => 7.81250000000000E-03,
585
+ 'l' => 2.95799645040426E-02,
586
+ 'lt' => 2.95799645040426E-02
587
+ ),
588
+ 'cup' => array( 'tsp' => 4.80000000000000E+01,
589
+ 'tbs' => 1.60000000000000E+01,
590
+ 'oz' => 8.00000000000000E+00,
591
+ 'cup' => 1.0,
592
+ 'pt' => 5.00000000000000E-01,
593
+ 'us_pt' => 5.00000000000000E-01,
594
+ 'uk_pt' => 4.16428088074541E-01,
595
+ 'qt' => 2.50000000000000E-01,
596
+ 'gal' => 6.25000000000000E-02,
597
+ 'l' => 2.36639716032341E-01,
598
+ 'lt' => 2.36639716032341E-01
599
+ ),
600
+ 'pt' => array( 'tsp' => 9.60000000000000E+01,
601
+ 'tbs' => 3.20000000000000E+01,
602
+ 'oz' => 1.60000000000000E+01,
603
+ 'cup' => 2.00000000000000E+00,
604
+ 'pt' => 1.0,
605
+ 'us_pt' => 1.0,
606
+ 'uk_pt' => 8.32856176149081E-01,
607
+ 'qt' => 5.00000000000000E-01,
608
+ 'gal' => 1.25000000000000E-01,
609
+ 'l' => 4.73279432064682E-01,
610
+ 'lt' => 4.73279432064682E-01
611
+ ),
612
+ 'us_pt' => array( 'tsp' => 9.60000000000000E+01,
613
+ 'tbs' => 3.20000000000000E+01,
614
+ 'oz' => 1.60000000000000E+01,
615
+ 'cup' => 2.00000000000000E+00,
616
+ 'pt' => 1.0,
617
+ 'us_pt' => 1.0,
618
+ 'uk_pt' => 8.32856176149081E-01,
619
+ 'qt' => 5.00000000000000E-01,
620
+ 'gal' => 1.25000000000000E-01,
621
+ 'l' => 4.73279432064682E-01,
622
+ 'lt' => 4.73279432064682E-01
623
+ ),
624
+ 'uk_pt' => array( 'tsp' => 1.15266000000000E+02,
625
+ 'tbs' => 3.84220000000000E+01,
626
+ 'oz' => 1.92110000000000E+01,
627
+ 'cup' => 2.40137500000000E+00,
628
+ 'pt' => 1.20068750000000E+00,
629
+ 'us_pt' => 1.20068750000000E+00,
630
+ 'uk_pt' => 1.0,
631
+ 'qt' => 6.00343750000000E-01,
632
+ 'gal' => 1.50085937500000E-01,
633
+ 'l' => 5.68260698087162E-01,
634
+ 'lt' => 5.68260698087162E-01
635
+ ),
636
+ 'qt' => array( 'tsp' => 1.92000000000000E+02,
637
+ 'tbs' => 6.40000000000000E+01,
638
+ 'oz' => 3.20000000000000E+01,
639
+ 'cup' => 4.00000000000000E+00,
640
+ 'pt' => 2.00000000000000E+00,
641
+ 'us_pt' => 2.00000000000000E+00,
642
+ 'uk_pt' => 1.66571235229816E+00,
643
+ 'qt' => 1.0,
644
+ 'gal' => 2.50000000000000E-01,
645
+ 'l' => 9.46558864129363E-01,
646
+ 'lt' => 9.46558864129363E-01
647
+ ),
648
+ 'gal' => array( 'tsp' => 7.68000000000000E+02,
649
+ 'tbs' => 2.56000000000000E+02,
650
+ 'oz' => 1.28000000000000E+02,
651
+ 'cup' => 1.60000000000000E+01,
652
+ 'pt' => 8.00000000000000E+00,
653
+ 'us_pt' => 8.00000000000000E+00,
654
+ 'uk_pt' => 6.66284940919265E+00,
655
+ 'qt' => 4.00000000000000E+00,
656
+ 'gal' => 1.0,
657
+ 'l' => 3.78623545651745E+00,
658
+ 'lt' => 3.78623545651745E+00
659
+ ),
660
+ 'l' => array( 'tsp' => 2.02840000000000E+02,
661
+ 'tbs' => 6.76133333333333E+01,
662
+ 'oz' => 3.38066666666667E+01,
663
+ 'cup' => 4.22583333333333E+00,
664
+ 'pt' => 2.11291666666667E+00,
665
+ 'us_pt' => 2.11291666666667E+00,
666
+ 'uk_pt' => 1.75975569552166E+00,
667
+ 'qt' => 1.05645833333333E+00,
668
+ 'gal' => 2.64114583333333E-01,
669
+ 'l' => 1.0,
670
+ 'lt' => 1.0
671
+ ),
672
+ 'lt' => array( 'tsp' => 2.02840000000000E+02,
673
+ 'tbs' => 6.76133333333333E+01,
674
+ 'oz' => 3.38066666666667E+01,
675
+ 'cup' => 4.22583333333333E+00,
676
+ 'pt' => 2.11291666666667E+00,
677
+ 'us_pt' => 2.11291666666667E+00,
678
+ 'uk_pt' => 1.75975569552166E+00,
679
+ 'qt' => 1.05645833333333E+00,
680
+ 'gal' => 2.64114583333333E-01,
681
+ 'l' => 1.0,
682
+ 'lt' => 1.0
683
+ )
684
+ )
685
+ );
686
+
687
+
688
+ /**
689
+ * _parseComplex
690
+ *
691
+ * Parses a complex number into its real and imaginary parts, and an I or J suffix
692
+ *
693
+ * @param string $complexNumber The complex number
694
+ * @return string[] Indexed on "real", "imaginary" and "suffix"
695
+ */
696
+ public static function _parseComplex($complexNumber) {
697
+ $workString = (string) $complexNumber;
698
+
699
+ $realNumber = $imaginary = 0;
700
+ // Extract the suffix, if there is one
701
+ $suffix = substr($workString,-1);
702
+ if (!is_numeric($suffix)) {
703
+ $workString = substr($workString,0,-1);
704
+ } else {
705
+ $suffix = '';
706
+ }
707
+
708
+ // Split the input into its Real and Imaginary components
709
+ $leadingSign = 0;
710
+ if (strlen($workString) > 0) {
711
+ $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
712
+ }
713
+ $power = '';
714
+ $realNumber = strtok($workString, '+-');
715
+ if (strtoupper(substr($realNumber,-1)) == 'E') {
716
+ $power = strtok('+-');
717
+ ++$leadingSign;
718
+ }
719
+
720
+ $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign);
721
+
722
+ if ($suffix != '') {
723
+ $imaginary = substr($workString,strlen($realNumber));
724
+
725
+ if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
726
+ $imaginary = $realNumber.'1';
727
+ $realNumber = '0';
728
+ } else if ($imaginary == '') {
729
+ $imaginary = $realNumber;
730
+ $realNumber = '0';
731
+ } elseif (($imaginary == '+') || ($imaginary == '-')) {
732
+ $imaginary .= '1';
733
+ }
734
+ }
735
+
736
+ return array( 'real' => $realNumber,
737
+ 'imaginary' => $imaginary,
738
+ 'suffix' => $suffix
739
+ );
740
+ } // function _parseComplex()
741
+
742
+
743
+ /**
744
+ * Cleans the leading characters in a complex number string
745
+ *
746
+ * @param string $complexNumber The complex number to clean
747
+ * @return string The "cleaned" complex number
748
+ */
749
+ private static function _cleanComplex($complexNumber) {
750
+ if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
751
+ if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1);
752
+ if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber;
753
+ if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
754
+ return $complexNumber;
755
+ }
756
+
757
+ /**
758
+ * Formats a number base string value with leading zeroes
759
+ *
760
+ * @param string $xVal The "number" to pad
761
+ * @param integer $places The length that we want to pad this value
762
+ * @return string The padded "number"
763
+ */
764
+ private static function _nbrConversionFormat($xVal, $places) {
765
+ if (!is_null($places)) {
766
+ if (strlen($xVal) <= $places) {
767
+ return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
768
+ } else {
769
+ return PHPExcel_Calculation_Functions::NaN();
770
+ }
771
+ }
772
+
773
+ return substr($xVal, -10);
774
+ } // function _nbrConversionFormat()
775
+
776
+ /**
777
+ * BESSELI
778
+ *
779
+ * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
780
+ * for purely imaginary arguments
781
+ *
782
+ * Excel Function:
783
+ * BESSELI(x,ord)
784
+ *
785
+ * @access public
786
+ * @category Engineering Functions
787
+ * @param float $x The value at which to evaluate the function.
788
+ * If x is nonnumeric, BESSELI returns the #VALUE! error value.
789
+ * @param integer $ord The order of the Bessel function.
790
+ * If ord is not an integer, it is truncated.
791
+ * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
792
+ * If $ord < 0, BESSELI returns the #NUM! error value.
793
+ * @return float
794
+ *
795
+ */
796
+ public static function BESSELI($x, $ord) {
797
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
798
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
799
+
800
+ if ((is_numeric($x)) && (is_numeric($ord))) {
801
+ $ord = floor($ord);
802
+ if ($ord < 0) {
803
+ return PHPExcel_Calculation_Functions::NaN();
804
+ }
805
+
806
+ if (abs($x) <= 30) {
807
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
808
+ $ordK = 1;
809
+ $fSqrX = ($x * $x) / 4;
810
+ do {
811
+ $fTerm *= $fSqrX;
812
+ $fTerm /= ($ordK * ($ordK + $ord));
813
+ $fResult += $fTerm;
814
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
815
+ } else {
816
+ $f_2_PI = 2 * M_PI;
817
+
818
+ $fXAbs = abs($x);
819
+ $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
820
+ if (($ord & 1) && ($x < 0)) {
821
+ $fResult = -$fResult;
822
+ }
823
+ }
824
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
825
+ }
826
+ return PHPExcel_Calculation_Functions::VALUE();
827
+ } // function BESSELI()
828
+
829
+
830
+ /**
831
+ * BESSELJ
832
+ *
833
+ * Returns the Bessel function
834
+ *
835
+ * Excel Function:
836
+ * BESSELJ(x,ord)
837
+ *
838
+ * @access public
839
+ * @category Engineering Functions
840
+ * @param float $x The value at which to evaluate the function.
841
+ * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
842
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
843
+ * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
844
+ * If $ord < 0, BESSELJ returns the #NUM! error value.
845
+ * @return float
846
+ *
847
+ */
848
+ public static function BESSELJ($x, $ord) {
849
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
850
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
851
+
852
+ if ((is_numeric($x)) && (is_numeric($ord))) {
853
+ $ord = floor($ord);
854
+ if ($ord < 0) {
855
+ return PHPExcel_Calculation_Functions::NaN();
856
+ }
857
+
858
+ $fResult = 0;
859
+ if (abs($x) <= 30) {
860
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
861
+ $ordK = 1;
862
+ $fSqrX = ($x * $x) / -4;
863
+ do {
864
+ $fTerm *= $fSqrX;
865
+ $fTerm /= ($ordK * ($ordK + $ord));
866
+ $fResult += $fTerm;
867
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
868
+ } else {
869
+ $f_PI_DIV_2 = M_PI / 2;
870
+ $f_PI_DIV_4 = M_PI / 4;
871
+
872
+ $fXAbs = abs($x);
873
+ $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
874
+ if (($ord & 1) && ($x < 0)) {
875
+ $fResult = -$fResult;
876
+ }
877
+ }
878
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
879
+ }
880
+ return PHPExcel_Calculation_Functions::VALUE();
881
+ } // function BESSELJ()
882
+
883
+
884
+ private static function _Besselk0($fNum) {
885
+ if ($fNum <= 2) {
886
+ $fNum2 = $fNum * 0.5;
887
+ $y = ($fNum2 * $fNum2);
888
+ $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
889
+ (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
890
+ (0.10750e-3 + $y * 0.74e-5))))));
891
+ } else {
892
+ $y = 2 / $fNum;
893
+ $fRet = exp(-$fNum) / sqrt($fNum) *
894
+ (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
895
+ (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
896
+ }
897
+ return $fRet;
898
+ } // function _Besselk0()
899
+
900
+
901
+ private static function _Besselk1($fNum) {
902
+ if ($fNum <= 2) {
903
+ $fNum2 = $fNum * 0.5;
904
+ $y = ($fNum2 * $fNum2);
905
+ $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
906
+ (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
907
+ (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
908
+ } else {
909
+ $y = 2 / $fNum;
910
+ $fRet = exp(-$fNum) / sqrt($fNum) *
911
+ (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
912
+ (0.325614e-2 + $y * (-0.68245e-3)))))));
913
+ }
914
+ return $fRet;
915
+ } // function _Besselk1()
916
+
917
+
918
+ /**
919
+ * BESSELK
920
+ *
921
+ * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
922
+ * for purely imaginary arguments.
923
+ *
924
+ * Excel Function:
925
+ * BESSELK(x,ord)
926
+ *
927
+ * @access public
928
+ * @category Engineering Functions
929
+ * @param float $x The value at which to evaluate the function.
930
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
931
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
932
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
933
+ * If $ord < 0, BESSELK returns the #NUM! error value.
934
+ * @return float
935
+ *
936
+ */
937
+ public static function BESSELK($x, $ord) {
938
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
939
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
940
+
941
+ if ((is_numeric($x)) && (is_numeric($ord))) {
942
+ if (($ord < 0) || ($x == 0.0)) {
943
+ return PHPExcel_Calculation_Functions::NaN();
944
+ }
945
+
946
+ switch(floor($ord)) {
947
+ case 0 : return self::_Besselk0($x);
948
+ break;
949
+ case 1 : return self::_Besselk1($x);
950
+ break;
951
+ default : $fTox = 2 / $x;
952
+ $fBkm = self::_Besselk0($x);
953
+ $fBk = self::_Besselk1($x);
954
+ for ($n = 1; $n < $ord; ++$n) {
955
+ $fBkp = $fBkm + $n * $fTox * $fBk;
956
+ $fBkm = $fBk;
957
+ $fBk = $fBkp;
958
+ }
959
+ }
960
+ return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk;
961
+ }
962
+ return PHPExcel_Calculation_Functions::VALUE();
963
+ } // function BESSELK()
964
+
965
+
966
+ private static function _Bessely0($fNum) {
967
+ if ($fNum < 8.0) {
968
+ $y = ($fNum * $fNum);
969
+ $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
970
+ $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
971
+ $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
972
+ } else {
973
+ $z = 8.0 / $fNum;
974
+ $y = ($z * $z);
975
+ $xx = $fNum - 0.785398164;
976
+ $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
977
+ $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
978
+ $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
979
+ }
980
+ return $fRet;
981
+ } // function _Bessely0()
982
+
983
+
984
+ private static function _Bessely1($fNum) {
985
+ if ($fNum < 8.0) {
986
+ $y = ($fNum * $fNum);
987
+ $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
988
+ (-0.4237922726e7 + $y * 0.8511937935e4)))));
989
+ $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
990
+ (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
991
+ $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
992
+ } else {
993
+ $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
994
+ }
995
+ return $fRet;
996
+ } // function _Bessely1()
997
+
998
+
999
+ /**
1000
+ * BESSELY
1001
+ *
1002
+ * Returns the Bessel function, which is also called the Weber function or the Neumann function.
1003
+ *
1004
+ * Excel Function:
1005
+ * BESSELY(x,ord)
1006
+ *
1007
+ * @access public
1008
+ * @category Engineering Functions
1009
+ * @param float $x The value at which to evaluate the function.
1010
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
1011
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
1012
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
1013
+ * If $ord < 0, BESSELK returns the #NUM! error value.
1014
+ *
1015
+ * @return float
1016
+ */
1017
+ public static function BESSELY($x, $ord) {
1018
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
1019
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
1020
+
1021
+ if ((is_numeric($x)) && (is_numeric($ord))) {
1022
+ if (($ord < 0) || ($x == 0.0)) {
1023
+ return PHPExcel_Calculation_Functions::NaN();
1024
+ }
1025
+
1026
+ switch(floor($ord)) {
1027
+ case 0 : return self::_Bessely0($x);
1028
+ break;
1029
+ case 1 : return self::_Bessely1($x);
1030
+ break;
1031
+ default: $fTox = 2 / $x;
1032
+ $fBym = self::_Bessely0($x);
1033
+ $fBy = self::_Bessely1($x);
1034
+ for ($n = 1; $n < $ord; ++$n) {
1035
+ $fByp = $n * $fTox * $fBy - $fBym;
1036
+ $fBym = $fBy;
1037
+ $fBy = $fByp;
1038
+ }
1039
+ }
1040
+ return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy;
1041
+ }
1042
+ return PHPExcel_Calculation_Functions::VALUE();
1043
+ } // function BESSELY()
1044
+
1045
+
1046
+ /**
1047
+ * BINTODEC
1048
+ *
1049
+ * Return a binary value as decimal.
1050
+ *
1051
+ * Excel Function:
1052
+ * BIN2DEC(x)
1053
+ *
1054
+ * @access public
1055
+ * @category Engineering Functions
1056
+ * @param string $x The binary number (as a string) that you want to convert. The number
1057
+ * cannot contain more than 10 characters (10 bits). The most significant
1058
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1059
+ * Negative numbers are represented using two's-complement notation.
1060
+ * If number is not a valid binary number, or if number contains more than
1061
+ * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
1062
+ * @return string
1063
+ */
1064
+ public static function BINTODEC($x) {
1065
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1066
+
1067
+ if (is_bool($x)) {
1068
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1069
+ $x = (int) $x;
1070
+ } else {
1071
+ return PHPExcel_Calculation_Functions::VALUE();
1072
+ }
1073
+ }
1074
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1075
+ $x = floor($x);
1076
+ }
1077
+ $x = (string) $x;
1078
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
1079
+ return PHPExcel_Calculation_Functions::NaN();
1080
+ }
1081
+ if (strlen($x) > 10) {
1082
+ return PHPExcel_Calculation_Functions::NaN();
1083
+ } elseif (strlen($x) == 10) {
1084
+ // Two's Complement
1085
+ $x = substr($x,-9);
1086
+ return '-'.(512-bindec($x));
1087
+ }
1088
+ return bindec($x);
1089
+ } // function BINTODEC()
1090
+
1091
+
1092
+ /**
1093
+ * BINTOHEX
1094
+ *
1095
+ * Return a binary value as hex.
1096
+ *
1097
+ * Excel Function:
1098
+ * BIN2HEX(x[,places])
1099
+ *
1100
+ * @access public
1101
+ * @category Engineering Functions
1102
+ * @param string $x The binary number (as a string) that you want to convert. The number
1103
+ * cannot contain more than 10 characters (10 bits). The most significant
1104
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1105
+ * Negative numbers are represented using two's-complement notation.
1106
+ * If number is not a valid binary number, or if number contains more than
1107
+ * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
1108
+ * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
1109
+ * minimum number of characters necessary. Places is useful for padding the
1110
+ * return value with leading 0s (zeros).
1111
+ * If places is not an integer, it is truncated.
1112
+ * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
1113
+ * If places is negative, BIN2HEX returns the #NUM! error value.
1114
+ * @return string
1115
+ */
1116
+ public static function BINTOHEX($x, $places=NULL) {
1117
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1118
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1119
+
1120
+ if (is_bool($x)) {
1121
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1122
+ $x = (int) $x;
1123
+ } else {
1124
+ return PHPExcel_Calculation_Functions::VALUE();
1125
+ }
1126
+ }
1127
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1128
+ $x = floor($x);
1129
+ }
1130
+ $x = (string) $x;
1131
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
1132
+ return PHPExcel_Calculation_Functions::NaN();
1133
+ }
1134
+ if (strlen($x) > 10) {
1135
+ return PHPExcel_Calculation_Functions::NaN();
1136
+ } elseif (strlen($x) == 10) {
1137
+ // Two's Complement
1138
+ return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2);
1139
+ }
1140
+ $hexVal = (string) strtoupper(dechex(bindec($x)));
1141
+
1142
+ return self::_nbrConversionFormat($hexVal,$places);
1143
+ } // function BINTOHEX()
1144
+
1145
+
1146
+ /**
1147
+ * BINTOOCT
1148
+ *
1149
+ * Return a binary value as octal.
1150
+ *
1151
+ * Excel Function:
1152
+ * BIN2OCT(x[,places])
1153
+ *
1154
+ * @access public
1155
+ * @category Engineering Functions
1156
+ * @param string $x The binary number (as a string) that you want to convert. The number
1157
+ * cannot contain more than 10 characters (10 bits). The most significant
1158
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1159
+ * Negative numbers are represented using two's-complement notation.
1160
+ * If number is not a valid binary number, or if number contains more than
1161
+ * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
1162
+ * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
1163
+ * minimum number of characters necessary. Places is useful for padding the
1164
+ * return value with leading 0s (zeros).
1165
+ * If places is not an integer, it is truncated.
1166
+ * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
1167
+ * If places is negative, BIN2OCT returns the #NUM! error value.
1168
+ * @return string
1169
+ */
1170
+ public static function BINTOOCT($x, $places=NULL) {
1171
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1172
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1173
+
1174
+ if (is_bool($x)) {
1175
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1176
+ $x = (int) $x;
1177
+ } else {
1178
+ return PHPExcel_Calculation_Functions::VALUE();
1179
+ }
1180
+ }
1181
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1182
+ $x = floor($x);
1183
+ }
1184
+ $x = (string) $x;
1185
+ if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
1186
+ return PHPExcel_Calculation_Functions::NaN();
1187
+ }
1188
+ if (strlen($x) > 10) {
1189
+ return PHPExcel_Calculation_Functions::NaN();
1190
+ } elseif (strlen($x) == 10) {
1191
+ // Two's Complement
1192
+ return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3);
1193
+ }
1194
+ $octVal = (string) decoct(bindec($x));
1195
+
1196
+ return self::_nbrConversionFormat($octVal,$places);
1197
+ } // function BINTOOCT()
1198
+
1199
+
1200
+ /**
1201
+ * DECTOBIN
1202
+ *
1203
+ * Return a decimal value as binary.
1204
+ *
1205
+ * Excel Function:
1206
+ * DEC2BIN(x[,places])
1207
+ *
1208
+ * @access public
1209
+ * @category Engineering Functions
1210
+ * @param string $x The decimal integer you want to convert. If number is negative,
1211
+ * valid place values are ignored and DEC2BIN returns a 10-character
1212
+ * (10-bit) binary number in which the most significant bit is the sign
1213
+ * bit. The remaining 9 bits are magnitude bits. Negative numbers are
1214
+ * represented using two's-complement notation.
1215
+ * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
1216
+ * value.
1217
+ * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
1218
+ * If DEC2BIN requires more than places characters, it returns the #NUM!
1219
+ * error value.
1220
+ * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
1221
+ * the minimum number of characters necessary. Places is useful for
1222
+ * padding the return value with leading 0s (zeros).
1223
+ * If places is not an integer, it is truncated.
1224
+ * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
1225
+ * If places is zero or negative, DEC2BIN returns the #NUM! error value.
1226
+ * @return string
1227
+ */
1228
+ public static function DECTOBIN($x, $places=NULL) {
1229
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1230
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1231
+
1232
+ if (is_bool($x)) {
1233
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1234
+ $x = (int) $x;
1235
+ } else {
1236
+ return PHPExcel_Calculation_Functions::VALUE();
1237
+ }
1238
+ }
1239
+ $x = (string) $x;
1240
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
1241
+ return PHPExcel_Calculation_Functions::VALUE();
1242
+ }
1243
+ $x = (string) floor($x);
1244
+ $r = decbin($x);
1245
+ if (strlen($r) == 32) {
1246
+ // Two's Complement
1247
+ $r = substr($r,-10);
1248
+ } elseif (strlen($r) > 11) {
1249
+ return PHPExcel_Calculation_Functions::NaN();
1250
+ }
1251
+
1252
+ return self::_nbrConversionFormat($r,$places);
1253
+ } // function DECTOBIN()
1254
+
1255
+
1256
+ /**
1257
+ * DECTOHEX
1258
+ *
1259
+ * Return a decimal value as hex.
1260
+ *
1261
+ * Excel Function:
1262
+ * DEC2HEX(x[,places])
1263
+ *
1264
+ * @access public
1265
+ * @category Engineering Functions
1266
+ * @param string $x The decimal integer you want to convert. If number is negative,
1267
+ * places is ignored and DEC2HEX returns a 10-character (40-bit)
1268
+ * hexadecimal number in which the most significant bit is the sign
1269
+ * bit. The remaining 39 bits are magnitude bits. Negative numbers
1270
+ * are represented using two's-complement notation.
1271
+ * If number < -549,755,813,888 or if number > 549,755,813,887,
1272
+ * DEC2HEX returns the #NUM! error value.
1273
+ * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
1274
+ * If DEC2HEX requires more than places characters, it returns the
1275
+ * #NUM! error value.
1276
+ * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
1277
+ * the minimum number of characters necessary. Places is useful for
1278
+ * padding the return value with leading 0s (zeros).
1279
+ * If places is not an integer, it is truncated.
1280
+ * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
1281
+ * If places is zero or negative, DEC2HEX returns the #NUM! error value.
1282
+ * @return string
1283
+ */
1284
+ public static function DECTOHEX($x, $places=null) {
1285
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1286
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1287
+
1288
+ if (is_bool($x)) {
1289
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1290
+ $x = (int) $x;
1291
+ } else {
1292
+ return PHPExcel_Calculation_Functions::VALUE();
1293
+ }
1294
+ }
1295
+ $x = (string) $x;
1296
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
1297
+ return PHPExcel_Calculation_Functions::VALUE();
1298
+ }
1299
+ $x = (string) floor($x);
1300
+ $r = strtoupper(dechex($x));
1301
+ if (strlen($r) == 8) {
1302
+ // Two's Complement
1303
+ $r = 'FF'.$r;
1304
+ }
1305
+
1306
+ return self::_nbrConversionFormat($r,$places);
1307
+ } // function DECTOHEX()
1308
+
1309
+
1310
+ /**
1311
+ * DECTOOCT
1312
+ *
1313
+ * Return an decimal value as octal.
1314
+ *
1315
+ * Excel Function:
1316
+ * DEC2OCT(x[,places])
1317
+ *
1318
+ * @access public
1319
+ * @category Engineering Functions
1320
+ * @param string $x The decimal integer you want to convert. If number is negative,
1321
+ * places is ignored and DEC2OCT returns a 10-character (30-bit)
1322
+ * octal number in which the most significant bit is the sign bit.
1323
+ * The remaining 29 bits are magnitude bits. Negative numbers are
1324
+ * represented using two's-complement notation.
1325
+ * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
1326
+ * returns the #NUM! error value.
1327
+ * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
1328
+ * If DEC2OCT requires more than places characters, it returns the
1329
+ * #NUM! error value.
1330
+ * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
1331
+ * the minimum number of characters necessary. Places is useful for
1332
+ * padding the return value with leading 0s (zeros).
1333
+ * If places is not an integer, it is truncated.
1334
+ * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
1335
+ * If places is zero or negative, DEC2OCT returns the #NUM! error value.
1336
+ * @return string
1337
+ */
1338
+ public static function DECTOOCT($x, $places=null) {
1339
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1340
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1341
+
1342
+ if (is_bool($x)) {
1343
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1344
+ $x = (int) $x;
1345
+ } else {
1346
+ return PHPExcel_Calculation_Functions::VALUE();
1347
+ }
1348
+ }
1349
+ $x = (string) $x;
1350
+ if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
1351
+ return PHPExcel_Calculation_Functions::VALUE();
1352
+ }
1353
+ $x = (string) floor($x);
1354
+ $r = decoct($x);
1355
+ if (strlen($r) == 11) {
1356
+ // Two's Complement
1357
+ $r = substr($r,-10);
1358
+ }
1359
+
1360
+ return self::_nbrConversionFormat($r,$places);
1361
+ } // function DECTOOCT()
1362
+
1363
+
1364
+ /**
1365
+ * HEXTOBIN
1366
+ *
1367
+ * Return a hex value as binary.
1368
+ *
1369
+ * Excel Function:
1370
+ * HEX2BIN(x[,places])
1371
+ *
1372
+ * @access public
1373
+ * @category Engineering Functions
1374
+ * @param string $x the hexadecimal number you want to convert. Number cannot
1375
+ * contain more than 10 characters. The most significant bit of
1376
+ * number is the sign bit (40th bit from the right). The remaining
1377
+ * 9 bits are magnitude bits. Negative numbers are represented
1378
+ * using two's-complement notation.
1379
+ * If number is negative, HEX2BIN ignores places and returns a
1380
+ * 10-character binary number.
1381
+ * If number is negative, it cannot be less than FFFFFFFE00, and
1382
+ * if number is positive, it cannot be greater than 1FF.
1383
+ * If number is not a valid hexadecimal number, HEX2BIN returns
1384
+ * the #NUM! error value.
1385
+ * If HEX2BIN requires more than places characters, it returns
1386
+ * the #NUM! error value.
1387
+ * @param integer $places The number of characters to use. If places is omitted,
1388
+ * HEX2BIN uses the minimum number of characters necessary. Places
1389
+ * is useful for padding the return value with leading 0s (zeros).
1390
+ * If places is not an integer, it is truncated.
1391
+ * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
1392
+ * If places is negative, HEX2BIN returns the #NUM! error value.
1393
+ * @return string
1394
+ */
1395
+ public static function HEXTOBIN($x, $places=null) {
1396
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1397
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1398
+
1399
+ if (is_bool($x)) {
1400
+ return PHPExcel_Calculation_Functions::VALUE();
1401
+ }
1402
+ $x = (string) $x;
1403
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
1404
+ return PHPExcel_Calculation_Functions::NaN();
1405
+ }
1406
+ $binVal = decbin(hexdec($x));
1407
+
1408
+ return substr(self::_nbrConversionFormat($binVal,$places),-10);
1409
+ } // function HEXTOBIN()
1410
+
1411
+
1412
+ /**
1413
+ * HEXTODEC
1414
+ *
1415
+ * Return a hex value as decimal.
1416
+ *
1417
+ * Excel Function:
1418
+ * HEX2DEC(x)
1419
+ *
1420
+ * @access public
1421
+ * @category Engineering Functions
1422
+ * @param string $x The hexadecimal number you want to convert. This number cannot
1423
+ * contain more than 10 characters (40 bits). The most significant
1424
+ * bit of number is the sign bit. The remaining 39 bits are magnitude
1425
+ * bits. Negative numbers are represented using two's-complement
1426
+ * notation.
1427
+ * If number is not a valid hexadecimal number, HEX2DEC returns the
1428
+ * #NUM! error value.
1429
+ * @return string
1430
+ */
1431
+ public static function HEXTODEC($x) {
1432
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1433
+
1434
+ if (is_bool($x)) {
1435
+ return PHPExcel_Calculation_Functions::VALUE();
1436
+ }
1437
+ $x = (string) $x;
1438
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
1439
+ return PHPExcel_Calculation_Functions::NaN();
1440
+ }
1441
+ return hexdec($x);
1442
+ } // function HEXTODEC()
1443
+
1444
+
1445
+ /**
1446
+ * HEXTOOCT
1447
+ *
1448
+ * Return a hex value as octal.
1449
+ *
1450
+ * Excel Function:
1451
+ * HEX2OCT(x[,places])
1452
+ *
1453
+ * @access public
1454
+ * @category Engineering Functions
1455
+ * @param string $x The hexadecimal number you want to convert. Number cannot
1456
+ * contain more than 10 characters. The most significant bit of
1457
+ * number is the sign bit. The remaining 39 bits are magnitude
1458
+ * bits. Negative numbers are represented using two's-complement
1459
+ * notation.
1460
+ * If number is negative, HEX2OCT ignores places and returns a
1461
+ * 10-character octal number.
1462
+ * If number is negative, it cannot be less than FFE0000000, and
1463
+ * if number is positive, it cannot be greater than 1FFFFFFF.
1464
+ * If number is not a valid hexadecimal number, HEX2OCT returns
1465
+ * the #NUM! error value.
1466
+ * If HEX2OCT requires more than places characters, it returns
1467
+ * the #NUM! error value.
1468
+ * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
1469
+ * uses the minimum number of characters necessary. Places is
1470
+ * useful for padding the return value with leading 0s (zeros).
1471
+ * If places is not an integer, it is truncated.
1472
+ * If places is nonnumeric, HEX2OCT returns the #VALUE! error
1473
+ * value.
1474
+ * If places is negative, HEX2OCT returns the #NUM! error value.
1475
+ * @return string
1476
+ */
1477
+ public static function HEXTOOCT($x, $places=null) {
1478
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1479
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1480
+
1481
+ if (is_bool($x)) {
1482
+ return PHPExcel_Calculation_Functions::VALUE();
1483
+ }
1484
+ $x = (string) $x;
1485
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
1486
+ return PHPExcel_Calculation_Functions::NaN();
1487
+ }
1488
+ $octVal = decoct(hexdec($x));
1489
+
1490
+ return self::_nbrConversionFormat($octVal,$places);
1491
+ } // function HEXTOOCT()
1492
+
1493
+
1494
+ /**
1495
+ * OCTTOBIN
1496
+ *
1497
+ * Return an octal value as binary.
1498
+ *
1499
+ * Excel Function:
1500
+ * OCT2BIN(x[,places])
1501
+ *
1502
+ * @access public
1503
+ * @category Engineering Functions
1504
+ * @param string $x The octal number you want to convert. Number may not
1505
+ * contain more than 10 characters. The most significant
1506
+ * bit of number is the sign bit. The remaining 29 bits
1507
+ * are magnitude bits. Negative numbers are represented
1508
+ * using two's-complement notation.
1509
+ * If number is negative, OCT2BIN ignores places and returns
1510
+ * a 10-character binary number.
1511
+ * If number is negative, it cannot be less than 7777777000,
1512
+ * and if number is positive, it cannot be greater than 777.
1513
+ * If number is not a valid octal number, OCT2BIN returns
1514
+ * the #NUM! error value.
1515
+ * If OCT2BIN requires more than places characters, it
1516
+ * returns the #NUM! error value.
1517
+ * @param integer $places The number of characters to use. If places is omitted,
1518
+ * OCT2BIN uses the minimum number of characters necessary.
1519
+ * Places is useful for padding the return value with
1520
+ * leading 0s (zeros).
1521
+ * If places is not an integer, it is truncated.
1522
+ * If places is nonnumeric, OCT2BIN returns the #VALUE!
1523
+ * error value.
1524
+ * If places is negative, OCT2BIN returns the #NUM! error
1525
+ * value.
1526
+ * @return string
1527
+ */
1528
+ public static function OCTTOBIN($x, $places=null) {
1529
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1530
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1531
+
1532
+ if (is_bool($x)) {
1533
+ return PHPExcel_Calculation_Functions::VALUE();
1534
+ }
1535
+ $x = (string) $x;
1536
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
1537
+ return PHPExcel_Calculation_Functions::NaN();
1538
+ }
1539
+ $r = decbin(octdec($x));
1540
+
1541
+ return self::_nbrConversionFormat($r,$places);
1542
+ } // function OCTTOBIN()
1543
+
1544
+
1545
+ /**
1546
+ * OCTTODEC
1547
+ *
1548
+ * Return an octal value as decimal.
1549
+ *
1550
+ * Excel Function:
1551
+ * OCT2DEC(x)
1552
+ *
1553
+ * @access public
1554
+ * @category Engineering Functions
1555
+ * @param string $x The octal number you want to convert. Number may not contain
1556
+ * more than 10 octal characters (30 bits). The most significant
1557
+ * bit of number is the sign bit. The remaining 29 bits are
1558
+ * magnitude bits. Negative numbers are represented using
1559
+ * two's-complement notation.
1560
+ * If number is not a valid octal number, OCT2DEC returns the
1561
+ * #NUM! error value.
1562
+ * @return string
1563
+ */
1564
+ public static function OCTTODEC($x) {
1565
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1566
+
1567
+ if (is_bool($x)) {
1568
+ return PHPExcel_Calculation_Functions::VALUE();
1569
+ }
1570
+ $x = (string) $x;
1571
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
1572
+ return PHPExcel_Calculation_Functions::NaN();
1573
+ }
1574
+ return octdec($x);
1575
+ } // function OCTTODEC()
1576
+
1577
+
1578
+ /**
1579
+ * OCTTOHEX
1580
+ *
1581
+ * Return an octal value as hex.
1582
+ *
1583
+ * Excel Function:
1584
+ * OCT2HEX(x[,places])
1585
+ *
1586
+ * @access public
1587
+ * @category Engineering Functions
1588
+ * @param string $x The octal number you want to convert. Number may not contain
1589
+ * more than 10 octal characters (30 bits). The most significant
1590
+ * bit of number is the sign bit. The remaining 29 bits are
1591
+ * magnitude bits. Negative numbers are represented using
1592
+ * two's-complement notation.
1593
+ * If number is negative, OCT2HEX ignores places and returns a
1594
+ * 10-character hexadecimal number.
1595
+ * If number is not a valid octal number, OCT2HEX returns the
1596
+ * #NUM! error value.
1597
+ * If OCT2HEX requires more than places characters, it returns
1598
+ * the #NUM! error value.
1599
+ * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
1600
+ * uses the minimum number of characters necessary. Places is useful
1601
+ * for padding the return value with leading 0s (zeros).
1602
+ * If places is not an integer, it is truncated.
1603
+ * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
1604
+ * If places is negative, OCT2HEX returns the #NUM! error value.
1605
+ * @return string
1606
+ */
1607
+ public static function OCTTOHEX($x, $places=null) {
1608
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1609
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1610
+
1611
+ if (is_bool($x)) {
1612
+ return PHPExcel_Calculation_Functions::VALUE();
1613
+ }
1614
+ $x = (string) $x;
1615
+ if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
1616
+ return PHPExcel_Calculation_Functions::NaN();
1617
+ }
1618
+ $hexVal = strtoupper(dechex(octdec($x)));
1619
+
1620
+ return self::_nbrConversionFormat($hexVal,$places);
1621
+ } // function OCTTOHEX()
1622
+
1623
+
1624
+ /**
1625
+ * COMPLEX
1626
+ *
1627
+ * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
1628
+ *
1629
+ * Excel Function:
1630
+ * COMPLEX(realNumber,imaginary[,places])
1631
+ *
1632
+ * @access public
1633
+ * @category Engineering Functions
1634
+ * @param float $realNumber The real coefficient of the complex number.
1635
+ * @param float $imaginary The imaginary coefficient of the complex number.
1636
+ * @param string $suffix The suffix for the imaginary component of the complex number.
1637
+ * If omitted, the suffix is assumed to be "i".
1638
+ * @return string
1639
+ */
1640
+ public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') {
1641
+ $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
1642
+ $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary);
1643
+ $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix);
1644
+
1645
+ if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
1646
+ (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
1647
+ $realNumber = (float) $realNumber;
1648
+ $imaginary = (float) $imaginary;
1649
+
1650
+ if ($suffix == '') $suffix = 'i';
1651
+ if ($realNumber == 0.0) {
1652
+ if ($imaginary == 0.0) {
1653
+ return (string) '0';
1654
+ } elseif ($imaginary == 1.0) {
1655
+ return (string) $suffix;
1656
+ } elseif ($imaginary == -1.0) {
1657
+ return (string) '-'.$suffix;
1658
+ }
1659
+ return (string) $imaginary.$suffix;
1660
+ } elseif ($imaginary == 0.0) {
1661
+ return (string) $realNumber;
1662
+ } elseif ($imaginary == 1.0) {
1663
+ return (string) $realNumber.'+'.$suffix;
1664
+ } elseif ($imaginary == -1.0) {
1665
+ return (string) $realNumber.'-'.$suffix;
1666
+ }
1667
+ if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; }
1668
+ return (string) $realNumber.$imaginary.$suffix;
1669
+ }
1670
+
1671
+ return PHPExcel_Calculation_Functions::VALUE();
1672
+ } // function COMPLEX()
1673
+
1674
+
1675
+ /**
1676
+ * IMAGINARY
1677
+ *
1678
+ * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
1679
+ *
1680
+ * Excel Function:
1681
+ * IMAGINARY(complexNumber)
1682
+ *
1683
+ * @access public
1684
+ * @category Engineering Functions
1685
+ * @param string $complexNumber The complex number for which you want the imaginary
1686
+ * coefficient.
1687
+ * @return float
1688
+ */
1689
+ public static function IMAGINARY($complexNumber) {
1690
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1691
+
1692
+ $parsedComplex = self::_parseComplex($complexNumber);
1693
+ return $parsedComplex['imaginary'];
1694
+ } // function IMAGINARY()
1695
+
1696
+
1697
+ /**
1698
+ * IMREAL
1699
+ *
1700
+ * Returns the real coefficient of a complex number in x + yi or x + yj text format.
1701
+ *
1702
+ * Excel Function:
1703
+ * IMREAL(complexNumber)
1704
+ *
1705
+ * @access public
1706
+ * @category Engineering Functions
1707
+ * @param string $complexNumber The complex number for which you want the real coefficient.
1708
+ * @return float
1709
+ */
1710
+ public static function IMREAL($complexNumber) {
1711
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1712
+
1713
+ $parsedComplex = self::_parseComplex($complexNumber);
1714
+ return $parsedComplex['real'];
1715
+ } // function IMREAL()
1716
+
1717
+
1718
+ /**
1719
+ * IMABS
1720
+ *
1721
+ * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
1722
+ *
1723
+ * Excel Function:
1724
+ * IMABS(complexNumber)
1725
+ *
1726
+ * @param string $complexNumber The complex number for which you want the absolute value.
1727
+ * @return float
1728
+ */
1729
+ public static function IMABS($complexNumber) {
1730
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1731
+
1732
+ $parsedComplex = self::_parseComplex($complexNumber);
1733
+
1734
+ return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
1735
+ } // function IMABS()
1736
+
1737
+
1738
+ /**
1739
+ * IMARGUMENT
1740
+ *
1741
+ * Returns the argument theta of a complex number, i.e. the angle in radians from the real
1742
+ * axis to the representation of the number in polar coordinates.
1743
+ *
1744
+ * Excel Function:
1745
+ * IMARGUMENT(complexNumber)
1746
+ *
1747
+ * @param string $complexNumber The complex number for which you want the argument theta.
1748
+ * @return float
1749
+ */
1750
+ public static function IMARGUMENT($complexNumber) {
1751
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1752
+
1753
+ $parsedComplex = self::_parseComplex($complexNumber);
1754
+
1755
+ if ($parsedComplex['real'] == 0.0) {
1756
+ if ($parsedComplex['imaginary'] == 0.0) {
1757
+ return 0.0;
1758
+ } elseif($parsedComplex['imaginary'] < 0.0) {
1759
+ return M_PI / -2;
1760
+ } else {
1761
+ return M_PI / 2;
1762
+ }
1763
+ } elseif ($parsedComplex['real'] > 0.0) {
1764
+ return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
1765
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
1766
+ return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
1767
+ } else {
1768
+ return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
1769
+ }
1770
+ } // function IMARGUMENT()
1771
+
1772
+
1773
+ /**
1774
+ * IMCONJUGATE
1775
+ *
1776
+ * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
1777
+ *
1778
+ * Excel Function:
1779
+ * IMCONJUGATE(complexNumber)
1780
+ *
1781
+ * @param string $complexNumber The complex number for which you want the conjugate.
1782
+ * @return string
1783
+ */
1784
+ public static function IMCONJUGATE($complexNumber) {
1785
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1786
+
1787
+ $parsedComplex = self::_parseComplex($complexNumber);
1788
+
1789
+ if ($parsedComplex['imaginary'] == 0.0) {
1790
+ return $parsedComplex['real'];
1791
+ } else {
1792
+ return self::_cleanComplex( self::COMPLEX( $parsedComplex['real'],
1793
+ 0 - $parsedComplex['imaginary'],
1794
+ $parsedComplex['suffix']
1795
+ )
1796
+ );
1797
+ }
1798
+ } // function IMCONJUGATE()
1799
+
1800
+
1801
+ /**
1802
+ * IMCOS
1803
+ *
1804
+ * Returns the cosine of a complex number in x + yi or x + yj text format.
1805
+ *
1806
+ * Excel Function:
1807
+ * IMCOS(complexNumber)
1808
+ *
1809
+ * @param string $complexNumber The complex number for which you want the cosine.
1810
+ * @return string|float
1811
+ */
1812
+ public static function IMCOS($complexNumber) {
1813
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1814
+
1815
+ $parsedComplex = self::_parseComplex($complexNumber);
1816
+
1817
+ if ($parsedComplex['imaginary'] == 0.0) {
1818
+ return cos($parsedComplex['real']);
1819
+ } else {
1820
+ return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']));
1821
+ }
1822
+ } // function IMCOS()
1823
+
1824
+
1825
+ /**
1826
+ * IMSIN
1827
+ *
1828
+ * Returns the sine of a complex number in x + yi or x + yj text format.
1829
+ *
1830
+ * Excel Function:
1831
+ * IMSIN(complexNumber)
1832
+ *
1833
+ * @param string $complexNumber The complex number for which you want the sine.
1834
+ * @return string|float
1835
+ */
1836
+ public static function IMSIN($complexNumber) {
1837
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1838
+
1839
+ $parsedComplex = self::_parseComplex($complexNumber);
1840
+
1841
+ if ($parsedComplex['imaginary'] == 0.0) {
1842
+ return sin($parsedComplex['real']);
1843
+ } else {
1844
+ return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']);
1845
+ }
1846
+ } // function IMSIN()
1847
+
1848
+
1849
+ /**
1850
+ * IMSQRT
1851
+ *
1852
+ * Returns the square root of a complex number in x + yi or x + yj text format.
1853
+ *
1854
+ * Excel Function:
1855
+ * IMSQRT(complexNumber)
1856
+ *
1857
+ * @param string $complexNumber The complex number for which you want the square root.
1858
+ * @return string
1859
+ */
1860
+ public static function IMSQRT($complexNumber) {
1861
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1862
+
1863
+ $parsedComplex = self::_parseComplex($complexNumber);
1864
+
1865
+ $theta = self::IMARGUMENT($complexNumber);
1866
+ $d1 = cos($theta / 2);
1867
+ $d2 = sin($theta / 2);
1868
+ $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
1869
+
1870
+ if ($parsedComplex['suffix'] == '') {
1871
+ return self::COMPLEX($d1 * $r,$d2 * $r);
1872
+ } else {
1873
+ return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']);
1874
+ }
1875
+ } // function IMSQRT()
1876
+
1877
+
1878
+ /**
1879
+ * IMLN
1880
+ *
1881
+ * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
1882
+ *
1883
+ * Excel Function:
1884
+ * IMLN(complexNumber)
1885
+ *
1886
+ * @param string $complexNumber The complex number for which you want the natural logarithm.
1887
+ * @return string
1888
+ */
1889
+ public static function IMLN($complexNumber) {
1890
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1891
+
1892
+ $parsedComplex = self::_parseComplex($complexNumber);
1893
+
1894
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1895
+ return PHPExcel_Calculation_Functions::NaN();
1896
+ }
1897
+
1898
+ $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
1899
+ $t = self::IMARGUMENT($complexNumber);
1900
+
1901
+ if ($parsedComplex['suffix'] == '') {
1902
+ return self::COMPLEX($logR,$t);
1903
+ } else {
1904
+ return self::COMPLEX($logR,$t,$parsedComplex['suffix']);
1905
+ }
1906
+ } // function IMLN()
1907
+
1908
+
1909
+ /**
1910
+ * IMLOG10
1911
+ *
1912
+ * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
1913
+ *
1914
+ * Excel Function:
1915
+ * IMLOG10(complexNumber)
1916
+ *
1917
+ * @param string $complexNumber The complex number for which you want the common logarithm.
1918
+ * @return string
1919
+ */
1920
+ public static function IMLOG10($complexNumber) {
1921
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1922
+
1923
+ $parsedComplex = self::_parseComplex($complexNumber);
1924
+
1925
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1926
+ return PHPExcel_Calculation_Functions::NaN();
1927
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1928
+ return log10($parsedComplex['real']);
1929
+ }
1930
+
1931
+ return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber));
1932
+ } // function IMLOG10()
1933
+
1934
+
1935
+ /**
1936
+ * IMLOG2
1937
+ *
1938
+ * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format.
1939
+ *
1940
+ * Excel Function:
1941
+ * IMLOG2(complexNumber)
1942
+ *
1943
+ * @param string $complexNumber The complex number for which you want the base-2 logarithm.
1944
+ * @return string
1945
+ */
1946
+ public static function IMLOG2($complexNumber) {
1947
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1948
+
1949
+ $parsedComplex = self::_parseComplex($complexNumber);
1950
+
1951
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1952
+ return PHPExcel_Calculation_Functions::NaN();
1953
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1954
+ return log($parsedComplex['real'],2);
1955
+ }
1956
+
1957
+ return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber));
1958
+ } // function IMLOG2()
1959
+
1960
+
1961
+ /**
1962
+ * IMEXP
1963
+ *
1964
+ * Returns the exponential of a complex number in x + yi or x + yj text format.
1965
+ *
1966
+ * Excel Function:
1967
+ * IMEXP(complexNumber)
1968
+ *
1969
+ * @param string $complexNumber The complex number for which you want the exponential.
1970
+ * @return string
1971
+ */
1972
+ public static function IMEXP($complexNumber) {
1973
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1974
+
1975
+ $parsedComplex = self::_parseComplex($complexNumber);
1976
+
1977
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
1978
+ return '1';
1979
+ }
1980
+
1981
+ $e = exp($parsedComplex['real']);
1982
+ $eX = $e * cos($parsedComplex['imaginary']);
1983
+ $eY = $e * sin($parsedComplex['imaginary']);
1984
+
1985
+ if ($parsedComplex['suffix'] == '') {
1986
+ return self::COMPLEX($eX,$eY);
1987
+ } else {
1988
+ return self::COMPLEX($eX,$eY,$parsedComplex['suffix']);
1989
+ }
1990
+ } // function IMEXP()
1991
+
1992
+
1993
+ /**
1994
+ * IMPOWER
1995
+ *
1996
+ * Returns a complex number in x + yi or x + yj text format raised to a power.
1997
+ *
1998
+ * Excel Function:
1999
+ * IMPOWER(complexNumber,realNumber)
2000
+ *
2001
+ * @param string $complexNumber The complex number you want to raise to a power.
2002
+ * @param float $realNumber The power to which you want to raise the complex number.
2003
+ * @return string
2004
+ */
2005
+ public static function IMPOWER($complexNumber,$realNumber) {
2006
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2007
+ $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
2008
+
2009
+ if (!is_numeric($realNumber)) {
2010
+ return PHPExcel_Calculation_Functions::VALUE();
2011
+ }
2012
+
2013
+ $parsedComplex = self::_parseComplex($complexNumber);
2014
+
2015
+ $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
2016
+ $rPower = pow($r,$realNumber);
2017
+ $theta = self::IMARGUMENT($complexNumber) * $realNumber;
2018
+ if ($theta == 0) {
2019
+ return 1;
2020
+ } elseif ($parsedComplex['imaginary'] == 0.0) {
2021
+ return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
2022
+ } else {
2023
+ return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
2024
+ }
2025
+ } // function IMPOWER()
2026
+
2027
+
2028
+ /**
2029
+ * IMDIV
2030
+ *
2031
+ * Returns the quotient of two complex numbers in x + yi or x + yj text format.
2032
+ *
2033
+ * Excel Function:
2034
+ * IMDIV(complexDividend,complexDivisor)
2035
+ *
2036
+ * @param string $complexDividend The complex numerator or dividend.
2037
+ * @param string $complexDivisor The complex denominator or divisor.
2038
+ * @return string
2039
+ */
2040
+ public static function IMDIV($complexDividend,$complexDivisor) {
2041
+ $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend);
2042
+ $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor);
2043
+
2044
+ $parsedComplexDividend = self::_parseComplex($complexDividend);
2045
+ $parsedComplexDivisor = self::_parseComplex($complexDivisor);
2046
+
2047
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
2048
+ ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
2049
+ return PHPExcel_Calculation_Functions::NaN();
2050
+ }
2051
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
2052
+ $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
2053
+ }
2054
+
2055
+ $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
2056
+ $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
2057
+ $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
2058
+
2059
+ $r = $d1/$d3;
2060
+ $i = $d2/$d3;
2061
+
2062
+ if ($i > 0.0) {
2063
+ return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
2064
+ } elseif ($i < 0.0) {
2065
+ return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
2066
+ } else {
2067
+ return $r;
2068
+ }
2069
+ } // function IMDIV()
2070
+
2071
+
2072
+ /**
2073
+ * IMSUB
2074
+ *
2075
+ * Returns the difference of two complex numbers in x + yi or x + yj text format.
2076
+ *
2077
+ * Excel Function:
2078
+ * IMSUB(complexNumber1,complexNumber2)
2079
+ *
2080
+ * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
2081
+ * @param string $complexNumber2 The complex number to subtract from complexNumber1.
2082
+ * @return string
2083
+ */
2084
+ public static function IMSUB($complexNumber1,$complexNumber2) {
2085
+ $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1);
2086
+ $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2);
2087
+
2088
+ $parsedComplex1 = self::_parseComplex($complexNumber1);
2089
+ $parsedComplex2 = self::_parseComplex($complexNumber2);
2090
+
2091
+ if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
2092
+ ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
2093
+ return PHPExcel_Calculation_Functions::NaN();
2094
+ } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
2095
+ $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
2096
+ }
2097
+
2098
+ $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
2099
+ $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
2100
+
2101
+ return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']);
2102
+ } // function IMSUB()
2103
+
2104
+
2105
+ /**
2106
+ * IMSUM
2107
+ *
2108
+ * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
2109
+ *
2110
+ * Excel Function:
2111
+ * IMSUM(complexNumber[,complexNumber[,...]])
2112
+ *
2113
+ * @param string $complexNumber,... Series of complex numbers to add
2114
+ * @return string
2115
+ */
2116
+ public static function IMSUM() {
2117
+ // Return value
2118
+ $returnValue = self::_parseComplex('0');
2119
+ $activeSuffix = '';
2120
+
2121
+ // Loop through the arguments
2122
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2123
+ foreach ($aArgs as $arg) {
2124
+ $parsedComplex = self::_parseComplex($arg);
2125
+
2126
+ if ($activeSuffix == '') {
2127
+ $activeSuffix = $parsedComplex['suffix'];
2128
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
2129
+ return PHPExcel_Calculation_Functions::VALUE();
2130
+ }
2131
+
2132
+ $returnValue['real'] += $parsedComplex['real'];
2133
+ $returnValue['imaginary'] += $parsedComplex['imaginary'];
2134
+ }
2135
+
2136
+ if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
2137
+ return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
2138
+ } // function IMSUM()
2139
+
2140
+
2141
+ /**
2142
+ * IMPRODUCT
2143
+ *
2144
+ * Returns the product of two or more complex numbers in x + yi or x + yj text format.
2145
+ *
2146
+ * Excel Function:
2147
+ * IMPRODUCT(complexNumber[,complexNumber[,...]])
2148
+ *
2149
+ * @param string $complexNumber,... Series of complex numbers to multiply
2150
+ * @return string
2151
+ */
2152
+ public static function IMPRODUCT() {
2153
+ // Return value
2154
+ $returnValue = self::_parseComplex('1');
2155
+ $activeSuffix = '';
2156
+
2157
+ // Loop through the arguments
2158
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2159
+ foreach ($aArgs as $arg) {
2160
+ $parsedComplex = self::_parseComplex($arg);
2161
+
2162
+ $workValue = $returnValue;
2163
+ if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
2164
+ $activeSuffix = $parsedComplex['suffix'];
2165
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
2166
+ return PHPExcel_Calculation_Functions::NaN();
2167
+ }
2168
+ $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
2169
+ $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
2170
+ }
2171
+
2172
+ if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
2173
+ return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
2174
+ } // function IMPRODUCT()
2175
+
2176
+
2177
+ /**
2178
+ * DELTA
2179
+ *
2180
+ * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
2181
+ * Use this function to filter a set of values. For example, by summing several DELTA
2182
+ * functions you calculate the count of equal pairs. This function is also known as the
2183
+ * Kronecker Delta function.
2184
+ *
2185
+ * Excel Function:
2186
+ * DELTA(a[,b])
2187
+ *
2188
+ * @param float $a The first number.
2189
+ * @param float $b The second number. If omitted, b is assumed to be zero.
2190
+ * @return int
2191
+ */
2192
+ public static function DELTA($a, $b=0) {
2193
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
2194
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
2195
+
2196
+ return (int) ($a == $b);
2197
+ } // function DELTA()
2198
+
2199
+
2200
+ /**
2201
+ * GESTEP
2202
+ *
2203
+ * Excel Function:
2204
+ * GESTEP(number[,step])
2205
+ *
2206
+ * Returns 1 if number >= step; returns 0 (zero) otherwise
2207
+ * Use this function to filter a set of values. For example, by summing several GESTEP
2208
+ * functions you calculate the count of values that exceed a threshold.
2209
+ *
2210
+ * @param float $number The value to test against step.
2211
+ * @param float $step The threshold value.
2212
+ * If you omit a value for step, GESTEP uses zero.
2213
+ * @return int
2214
+ */
2215
+ public static function GESTEP($number, $step=0) {
2216
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
2217
+ $step = PHPExcel_Calculation_Functions::flattenSingleValue($step);
2218
+
2219
+ return (int) ($number >= $step);
2220
+ } // function GESTEP()
2221
+
2222
+
2223
+ //
2224
+ // Private method to calculate the erf value
2225
+ //
2226
+ private static $_two_sqrtpi = 1.128379167095512574;
2227
+
2228
+ public static function _erfVal($x) {
2229
+ if (abs($x) > 2.2) {
2230
+ return 1 - self::_erfcVal($x);
2231
+ }
2232
+ $sum = $term = $x;
2233
+ $xsqr = ($x * $x);
2234
+ $j = 1;
2235
+ do {
2236
+ $term *= $xsqr / $j;
2237
+ $sum -= $term / (2 * $j + 1);
2238
+ ++$j;
2239
+ $term *= $xsqr / $j;
2240
+ $sum += $term / (2 * $j + 1);
2241
+ ++$j;
2242
+ if ($sum == 0.0) {
2243
+ break;
2244
+ }
2245
+ } while (abs($term / $sum) > PRECISION);
2246
+ return self::$_two_sqrtpi * $sum;
2247
+ } // function _erfVal()
2248
+
2249
+
2250
+ /**
2251
+ * ERF
2252
+ *
2253
+ * Returns the error function integrated between the lower and upper bound arguments.
2254
+ *
2255
+ * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
2256
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
2257
+ * improved, so that it can now calculate the function for both positive and negative ranges.
2258
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
2259
+ *
2260
+ * Excel Function:
2261
+ * ERF(lower[,upper])
2262
+ *
2263
+ * @param float $lower lower bound for integrating ERF
2264
+ * @param float $upper upper bound for integrating ERF.
2265
+ * If omitted, ERF integrates between zero and lower_limit
2266
+ * @return float
2267
+ */
2268
+ public static function ERF($lower, $upper = NULL) {
2269
+ $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower);
2270
+ $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper);
2271
+
2272
+ if (is_numeric($lower)) {
2273
+ if (is_null($upper)) {
2274
+ return self::_erfVal($lower);
2275
+ }
2276
+ if (is_numeric($upper)) {
2277
+ return self::_erfVal($upper) - self::_erfVal($lower);
2278
+ }
2279
+ }
2280
+ return PHPExcel_Calculation_Functions::VALUE();
2281
+ } // function ERF()
2282
+
2283
+
2284
+ //
2285
+ // Private method to calculate the erfc value
2286
+ //
2287
+ private static $_one_sqrtpi = 0.564189583547756287;
2288
+
2289
+ private static function _erfcVal($x) {
2290
+ if (abs($x) < 2.2) {
2291
+ return 1 - self::_erfVal($x);
2292
+ }
2293
+ if ($x < 0) {
2294
+ return 2 - self::ERFC(-$x);
2295
+ }
2296
+ $a = $n = 1;
2297
+ $b = $c = $x;
2298
+ $d = ($x * $x) + 0.5;
2299
+ $q1 = $q2 = $b / $d;
2300
+ $t = 0;
2301
+ do {
2302
+ $t = $a * $n + $b * $x;
2303
+ $a = $b;
2304
+ $b = $t;
2305
+ $t = $c * $n + $d * $x;
2306
+ $c = $d;
2307
+ $d = $t;
2308
+ $n += 0.5;
2309
+ $q1 = $q2;
2310
+ $q2 = $b / $d;
2311
+ } while ((abs($q1 - $q2) / $q2) > PRECISION);
2312
+ return self::$_one_sqrtpi * exp(-$x * $x) * $q2;
2313
+ } // function _erfcVal()
2314
+
2315
+
2316
+ /**
2317
+ * ERFC
2318
+ *
2319
+ * Returns the complementary ERF function integrated between x and infinity
2320
+ *
2321
+ * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
2322
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
2323
+ * improved, so that it can now calculate the function for both positive and negative x values.
2324
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
2325
+ *
2326
+ * Excel Function:
2327
+ * ERFC(x)
2328
+ *
2329
+ * @param float $x The lower bound for integrating ERFC
2330
+ * @return float
2331
+ */
2332
+ public static function ERFC($x) {
2333
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
2334
+
2335
+ if (is_numeric($x)) {
2336
+ return self::_erfcVal($x);
2337
+ }
2338
+ return PHPExcel_Calculation_Functions::VALUE();
2339
+ } // function ERFC()
2340
+
2341
+
2342
+ /**
2343
+ * getConversionGroups
2344
+ * Returns a list of the different conversion groups for UOM conversions
2345
+ *
2346
+ * @return array
2347
+ */
2348
+ public static function getConversionGroups() {
2349
+ $conversionGroups = array();
2350
+ foreach(self::$_conversionUnits as $conversionUnit) {
2351
+ $conversionGroups[] = $conversionUnit['Group'];
2352
+ }
2353
+ return array_merge(array_unique($conversionGroups));
2354
+ } // function getConversionGroups()
2355
+
2356
+
2357
+ /**
2358
+ * getConversionGroupUnits
2359
+ * Returns an array of units of measure, for a specified conversion group, or for all groups
2360
+ *
2361
+ * @param string $group The group whose units of measure you want to retrieve
2362
+ * @return array
2363
+ */
2364
+ public static function getConversionGroupUnits($group = NULL) {
2365
+ $conversionGroups = array();
2366
+ foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
2367
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
2368
+ $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
2369
+ }
2370
+ }
2371
+ return $conversionGroups;
2372
+ } // function getConversionGroupUnits()
2373
+
2374
+
2375
+ /**
2376
+ * getConversionGroupUnitDetails
2377
+ *
2378
+ * @param string $group The group whose units of measure you want to retrieve
2379
+ * @return array
2380
+ */
2381
+ public static function getConversionGroupUnitDetails($group = NULL) {
2382
+ $conversionGroups = array();
2383
+ foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
2384
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
2385
+ $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit,
2386
+ 'description' => $conversionGroup['Unit Name']
2387
+ );
2388
+ }
2389
+ }
2390
+ return $conversionGroups;
2391
+ } // function getConversionGroupUnitDetails()
2392
+
2393
+
2394
+ /**
2395
+ * getConversionMultipliers
2396
+ * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
2397
+ *
2398
+ * @return array of mixed
2399
+ */
2400
+ public static function getConversionMultipliers() {
2401
+ return self::$_conversionMultipliers;
2402
+ } // function getConversionGroups()
2403
+
2404
+
2405
+ /**
2406
+ * CONVERTUOM
2407
+ *
2408
+ * Converts a number from one measurement system to another.
2409
+ * For example, CONVERT can translate a table of distances in miles to a table of distances
2410
+ * in kilometers.
2411
+ *
2412
+ * Excel Function:
2413
+ * CONVERT(value,fromUOM,toUOM)
2414
+ *
2415
+ * @param float $value The value in fromUOM to convert.
2416
+ * @param string $fromUOM The units for value.
2417
+ * @param string $toUOM The units for the result.
2418
+ *
2419
+ * @return float
2420
+ */
2421
+ public static function CONVERTUOM($value, $fromUOM, $toUOM) {
2422
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2423
+ $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM);
2424
+ $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM);
2425
+
2426
+ if (!is_numeric($value)) {
2427
+ return PHPExcel_Calculation_Functions::VALUE();
2428
+ }
2429
+ $fromMultiplier = 1.0;
2430
+ if (isset(self::$_conversionUnits[$fromUOM])) {
2431
+ $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
2432
+ } else {
2433
+ $fromMultiplier = substr($fromUOM,0,1);
2434
+ $fromUOM = substr($fromUOM,1);
2435
+ if (isset(self::$_conversionMultipliers[$fromMultiplier])) {
2436
+ $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier'];
2437
+ } else {
2438
+ return PHPExcel_Calculation_Functions::NA();
2439
+ }
2440
+ if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) {
2441
+ $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
2442
+ } else {
2443
+ return PHPExcel_Calculation_Functions::NA();
2444
+ }
2445
+ }
2446
+ $value *= $fromMultiplier;
2447
+
2448
+ $toMultiplier = 1.0;
2449
+ if (isset(self::$_conversionUnits[$toUOM])) {
2450
+ $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
2451
+ } else {
2452
+ $toMultiplier = substr($toUOM,0,1);
2453
+ $toUOM = substr($toUOM,1);
2454
+ if (isset(self::$_conversionMultipliers[$toMultiplier])) {
2455
+ $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier'];
2456
+ } else {
2457
+ return PHPExcel_Calculation_Functions::NA();
2458
+ }
2459
+ if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) {
2460
+ $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
2461
+ } else {
2462
+ return PHPExcel_Calculation_Functions::NA();
2463
+ }
2464
+ }
2465
+ if ($unitGroup1 != $unitGroup2) {
2466
+ return PHPExcel_Calculation_Functions::NA();
2467
+ }
2468
+
2469
+ if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
2470
+ // We've already factored $fromMultiplier into the value, so we need
2471
+ // to reverse it again
2472
+ return $value / $fromMultiplier;
2473
+ } elseif ($unitGroup1 == 'Temperature') {
2474
+ if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
2475
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
2476
+ return $value;
2477
+ } else {
2478
+ $value = (($value - 32) / 1.8);
2479
+ if (($toUOM == 'K') || ($toUOM == 'kel')) {
2480
+ $value += 273.15;
2481
+ }
2482
+ return $value;
2483
+ }
2484
+ } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
2485
+ (($toUOM == 'K') || ($toUOM == 'kel'))) {
2486
+ return $value;
2487
+ } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
2488
+ (($toUOM == 'C') || ($toUOM == 'cel'))) {
2489
+ return $value;
2490
+ }
2491
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
2492
+ if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
2493
+ $value -= 273.15;
2494
+ }
2495
+ return ($value * 1.8) + 32;
2496
+ }
2497
+ if (($toUOM == 'C') || ($toUOM == 'cel')) {
2498
+ return $value - 273.15;
2499
+ }
2500
+ return $value + 273.15;
2501
+ }
2502
+ return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
2503
+ } // function CONVERTUOM()
2504
+
2505
+ } // class PHPExcel_Calculation_Engineering
libraries/PHPExcel/Calculation/Exception.php ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Calculation_Exception
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Calculation
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Calculation_Exception extends PHPExcel_Exception {
37
+ /**
38
+ * Error handler callback
39
+ *
40
+ * @param mixed $code
41
+ * @param mixed $string
42
+ * @param mixed $file
43
+ * @param mixed $line
44
+ * @param mixed $context
45
+ */
46
+ public static function errorHandlerCallback($code, $string, $file, $line, $context) {
47
+ $e = new self($string, $code);
48
+ $e->line = $line;
49
+ $e->file = $file;
50
+ throw $e;
51
+ }
52
+ }
libraries/PHPExcel/Calculation/ExceptionHandler.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+ /**
29
+ * PHPExcel_Calculation_ExceptionHandler
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ */
35
+ class PHPExcel_Calculation_ExceptionHandler {
36
+ /**
37
+ * Register errorhandler
38
+ */
39
+ public function __construct() {
40
+ set_error_handler(array('PHPExcel_Calculation_Exception', 'errorHandlerCallback'), E_ALL);
41
+ }
42
+
43
+ /**
44
+ * Unregister errorhandler
45
+ */
46
+ public function __destruct() {
47
+ restore_error_handler();
48
+ }
49
+ }
libraries/PHPExcel/Calculation/Financial.php ADDED
@@ -0,0 +1,2292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /** FINANCIAL_MAX_ITERATIONS */
40
+ define('FINANCIAL_MAX_ITERATIONS', 128);
41
+
42
+ /** FINANCIAL_PRECISION */
43
+ define('FINANCIAL_PRECISION', 1.0e-08);
44
+
45
+
46
+ /**
47
+ * PHPExcel_Calculation_Financial
48
+ *
49
+ * @category PHPExcel
50
+ * @package PHPExcel_Calculation
51
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
52
+ */
53
+ class PHPExcel_Calculation_Financial {
54
+
55
+ /**
56
+ * _lastDayOfMonth
57
+ *
58
+ * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
59
+ *
60
+ * @param DateTime $testDate The date for testing
61
+ * @return boolean
62
+ */
63
+ private static function _lastDayOfMonth($testDate)
64
+ {
65
+ return ($testDate->format('d') == $testDate->format('t'));
66
+ } // function _lastDayOfMonth()
67
+
68
+
69
+ /**
70
+ * _firstDayOfMonth
71
+ *
72
+ * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
73
+ *
74
+ * @param DateTime $testDate The date for testing
75
+ * @return boolean
76
+ */
77
+ private static function _firstDayOfMonth($testDate)
78
+ {
79
+ return ($testDate->format('d') == 1);
80
+ } // function _firstDayOfMonth()
81
+
82
+
83
+ private static function _coupFirstPeriodDate($settlement, $maturity, $frequency, $next)
84
+ {
85
+ $months = 12 / $frequency;
86
+
87
+ $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity);
88
+ $eom = self::_lastDayOfMonth($result);
89
+
90
+ while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) {
91
+ $result->modify('-'.$months.' months');
92
+ }
93
+ if ($next) {
94
+ $result->modify('+'.$months.' months');
95
+ }
96
+
97
+ if ($eom) {
98
+ $result->modify('-1 day');
99
+ }
100
+
101
+ return PHPExcel_Shared_Date::PHPToExcel($result);
102
+ } // function _coupFirstPeriodDate()
103
+
104
+
105
+ private static function _validFrequency($frequency)
106
+ {
107
+ if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
108
+ return true;
109
+ }
110
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
111
+ (($frequency == 6) || ($frequency == 12))) {
112
+ return true;
113
+ }
114
+ return false;
115
+ } // function _validFrequency()
116
+
117
+
118
+ /**
119
+ * _daysPerYear
120
+ *
121
+ * Returns the number of days in a specified year, as defined by the "basis" value
122
+ *
123
+ * @param integer $year The year against which we're testing
124
+ * @param integer $basis The type of day count:
125
+ * 0 or omitted US (NASD) 360
126
+ * 1 Actual (365 or 366 in a leap year)
127
+ * 2 360
128
+ * 3 365
129
+ * 4 European 360
130
+ * @return integer
131
+ */
132
+ private static function _daysPerYear($year, $basis=0)
133
+ {
134
+ switch ($basis) {
135
+ case 0 :
136
+ case 2 :
137
+ case 4 :
138
+ $daysPerYear = 360;
139
+ break;
140
+ case 3 :
141
+ $daysPerYear = 365;
142
+ break;
143
+ case 1 :
144
+ $daysPerYear = (PHPExcel_Calculation_DateTime::_isLeapYear($year)) ? 366 : 365;
145
+ break;
146
+ default :
147
+ return PHPExcel_Calculation_Functions::NaN();
148
+ }
149
+ return $daysPerYear;
150
+ } // function _daysPerYear()
151
+
152
+
153
+ private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0)
154
+ {
155
+ $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
156
+ $capital = $pv;
157
+ for ($i = 1; $i<= $per; ++$i) {
158
+ $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
159
+ $principal = $pmt - $interest;
160
+ $capital += $principal;
161
+ }
162
+ return array($interest, $principal);
163
+ } // function _interestAndPrincipal()
164
+
165
+
166
+ /**
167
+ * ACCRINT
168
+ *
169
+ * Returns the accrued interest for a security that pays periodic interest.
170
+ *
171
+ * Excel Function:
172
+ * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
173
+ *
174
+ * @access public
175
+ * @category Financial Functions
176
+ * @param mixed $issue The security's issue date.
177
+ * @param mixed $firstinterest The security's first interest date.
178
+ * @param mixed $settlement The security's settlement date.
179
+ * The security settlement date is the date after the issue date
180
+ * when the security is traded to the buyer.
181
+ * @param float $rate The security's annual coupon rate.
182
+ * @param float $par The security's par value.
183
+ * If you omit par, ACCRINT uses $1,000.
184
+ * @param integer $frequency the number of coupon payments per year.
185
+ * Valid frequency values are:
186
+ * 1 Annual
187
+ * 2 Semi-Annual
188
+ * 4 Quarterly
189
+ * If working in Gnumeric Mode, the following frequency options are
190
+ * also available
191
+ * 6 Bimonthly
192
+ * 12 Monthly
193
+ * @param integer $basis The type of day count to use.
194
+ * 0 or omitted US (NASD) 30/360
195
+ * 1 Actual/actual
196
+ * 2 Actual/360
197
+ * 3 Actual/365
198
+ * 4 European 30/360
199
+ * @return float
200
+ */
201
+ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par=1000, $frequency=1, $basis=0)
202
+ {
203
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
204
+ $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest);
205
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
206
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
207
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
208
+ $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
209
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
210
+
211
+ // Validate
212
+ if ((is_numeric($rate)) && (is_numeric($par))) {
213
+ $rate = (float) $rate;
214
+ $par = (float) $par;
215
+ if (($rate <= 0) || ($par <= 0)) {
216
+ return PHPExcel_Calculation_Functions::NaN();
217
+ }
218
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
219
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
220
+ // return date error
221
+ return $daysBetweenIssueAndSettlement;
222
+ }
223
+
224
+ return $par * $rate * $daysBetweenIssueAndSettlement;
225
+ }
226
+ return PHPExcel_Calculation_Functions::VALUE();
227
+ } // function ACCRINT()
228
+
229
+
230
+ /**
231
+ * ACCRINTM
232
+ *
233
+ * Returns the accrued interest for a security that pays interest at maturity.
234
+ *
235
+ * Excel Function:
236
+ * ACCRINTM(issue,settlement,rate[,par[,basis]])
237
+ *
238
+ * @access public
239
+ * @category Financial Functions
240
+ * @param mixed issue The security's issue date.
241
+ * @param mixed settlement The security's settlement (or maturity) date.
242
+ * @param float rate The security's annual coupon rate.
243
+ * @param float par The security's par value.
244
+ * If you omit par, ACCRINT uses $1,000.
245
+ * @param integer basis The type of day count to use.
246
+ * 0 or omitted US (NASD) 30/360
247
+ * 1 Actual/actual
248
+ * 2 Actual/360
249
+ * 3 Actual/365
250
+ * 4 European 30/360
251
+ * @return float
252
+ */
253
+ public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) {
254
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
255
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
256
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
257
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
258
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
259
+
260
+ // Validate
261
+ if ((is_numeric($rate)) && (is_numeric($par))) {
262
+ $rate = (float) $rate;
263
+ $par = (float) $par;
264
+ if (($rate <= 0) || ($par <= 0)) {
265
+ return PHPExcel_Calculation_Functions::NaN();
266
+ }
267
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
268
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
269
+ // return date error
270
+ return $daysBetweenIssueAndSettlement;
271
+ }
272
+ return $par * $rate * $daysBetweenIssueAndSettlement;
273
+ }
274
+ return PHPExcel_Calculation_Functions::VALUE();
275
+ } // function ACCRINTM()
276
+
277
+
278
+ /**
279
+ * AMORDEGRC
280
+ *
281
+ * Returns the depreciation for each accounting period.
282
+ * This function is provided for the French accounting system. If an asset is purchased in
283
+ * the middle of the accounting period, the prorated depreciation is taken into account.
284
+ * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
285
+ * the calculation depending on the life of the assets.
286
+ * This function will return the depreciation until the last period of the life of the assets
287
+ * or until the cumulated value of depreciation is greater than the cost of the assets minus
288
+ * the salvage value.
289
+ *
290
+ * Excel Function:
291
+ * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
292
+ *
293
+ * @access public
294
+ * @category Financial Functions
295
+ * @param float cost The cost of the asset.
296
+ * @param mixed purchased Date of the purchase of the asset.
297
+ * @param mixed firstPeriod Date of the end of the first period.
298
+ * @param mixed salvage The salvage value at the end of the life of the asset.
299
+ * @param float period The period.
300
+ * @param float rate Rate of depreciation.
301
+ * @param integer basis The type of day count to use.
302
+ * 0 or omitted US (NASD) 30/360
303
+ * 1 Actual/actual
304
+ * 2 Actual/360
305
+ * 3 Actual/365
306
+ * 4 European 30/360
307
+ * @return float
308
+ */
309
+ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
310
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
311
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
312
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
313
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
314
+ $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period));
315
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
316
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
317
+
318
+ // The depreciation coefficients are:
319
+ // Life of assets (1/rate) Depreciation coefficient
320
+ // Less than 3 years 1
321
+ // Between 3 and 4 years 1.5
322
+ // Between 5 and 6 years 2
323
+ // More than 6 years 2.5
324
+ $fUsePer = 1.0 / $rate;
325
+ if ($fUsePer < 3.0) {
326
+ $amortiseCoeff = 1.0;
327
+ } elseif ($fUsePer < 5.0) {
328
+ $amortiseCoeff = 1.5;
329
+ } elseif ($fUsePer <= 6.0) {
330
+ $amortiseCoeff = 2.0;
331
+ } else {
332
+ $amortiseCoeff = 2.5;
333
+ }
334
+
335
+ $rate *= $amortiseCoeff;
336
+ $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost,0);
337
+ $cost -= $fNRate;
338
+ $fRest = $cost - $salvage;
339
+
340
+ for ($n = 0; $n < $period; ++$n) {
341
+ $fNRate = round($rate * $cost,0);
342
+ $fRest -= $fNRate;
343
+
344
+ if ($fRest < 0.0) {
345
+ switch ($period - $n) {
346
+ case 0 :
347
+ case 1 : return round($cost * 0.5, 0);
348
+ break;
349
+ default : return 0.0;
350
+ break;
351
+ }
352
+ }
353
+ $cost -= $fNRate;
354
+ }
355
+ return $fNRate;
356
+ } // function AMORDEGRC()
357
+
358
+
359
+ /**
360
+ * AMORLINC
361
+ *
362
+ * Returns the depreciation for each accounting period.
363
+ * This function is provided for the French accounting system. If an asset is purchased in
364
+ * the middle of the accounting period, the prorated depreciation is taken into account.
365
+ *
366
+ * Excel Function:
367
+ * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
368
+ *
369
+ * @access public
370
+ * @category Financial Functions
371
+ * @param float cost The cost of the asset.
372
+ * @param mixed purchased Date of the purchase of the asset.
373
+ * @param mixed firstPeriod Date of the end of the first period.
374
+ * @param mixed salvage The salvage value at the end of the life of the asset.
375
+ * @param float period The period.
376
+ * @param float rate Rate of depreciation.
377
+ * @param integer basis The type of day count to use.
378
+ * 0 or omitted US (NASD) 30/360
379
+ * 1 Actual/actual
380
+ * 2 Actual/360
381
+ * 3 Actual/365
382
+ * 4 European 30/360
383
+ * @return float
384
+ */
385
+ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
386
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
387
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
388
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
389
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
390
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
391
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
392
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
393
+
394
+ $fOneRate = $cost * $rate;
395
+ $fCostDelta = $cost - $salvage;
396
+ // Note, quirky variation for leap years on the YEARFRAC for this function
397
+ $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased);
398
+ $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
399
+
400
+ if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::_isLeapYear($purchasedYear))) {
401
+ $yearFrac *= 365 / 366;
402
+ }
403
+
404
+ $f0Rate = $yearFrac * $rate * $cost;
405
+ $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
406
+
407
+ if ($period == 0) {
408
+ return $f0Rate;
409
+ } elseif ($period <= $nNumOfFullPeriods) {
410
+ return $fOneRate;
411
+ } elseif ($period == ($nNumOfFullPeriods + 1)) {
412
+ return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate);
413
+ } else {
414
+ return 0.0;
415
+ }
416
+ } // function AMORLINC()
417
+
418
+
419
+ /**
420
+ * COUPDAYBS
421
+ *
422
+ * Returns the number of days from the beginning of the coupon period to the settlement date.
423
+ *
424
+ * Excel Function:
425
+ * COUPDAYBS(settlement,maturity,frequency[,basis])
426
+ *
427
+ * @access public
428
+ * @category Financial Functions
429
+ * @param mixed settlement The security's settlement date.
430
+ * The security settlement date is the date after the issue
431
+ * date when the security is traded to the buyer.
432
+ * @param mixed maturity The security's maturity date.
433
+ * The maturity date is the date when the security expires.
434
+ * @param mixed frequency the number of coupon payments per year.
435
+ * Valid frequency values are:
436
+ * 1 Annual
437
+ * 2 Semi-Annual
438
+ * 4 Quarterly
439
+ * If working in Gnumeric Mode, the following frequency options are
440
+ * also available
441
+ * 6 Bimonthly
442
+ * 12 Monthly
443
+ * @param integer basis The type of day count to use.
444
+ * 0 or omitted US (NASD) 30/360
445
+ * 1 Actual/actual
446
+ * 2 Actual/360
447
+ * 3 Actual/365
448
+ * 4 European 30/360
449
+ * @return float
450
+ */
451
+ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) {
452
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
453
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
454
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
455
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
456
+
457
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
458
+ return PHPExcel_Calculation_Functions::VALUE();
459
+ }
460
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
461
+ return PHPExcel_Calculation_Functions::VALUE();
462
+ }
463
+
464
+ if (($settlement > $maturity) ||
465
+ (!self::_validFrequency($frequency)) ||
466
+ (($basis < 0) || ($basis > 4))) {
467
+ return PHPExcel_Calculation_Functions::NaN();
468
+ }
469
+
470
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
471
+ $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
472
+
473
+ return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
474
+ } // function COUPDAYBS()
475
+
476
+
477
+ /**
478
+ * COUPDAYS
479
+ *
480
+ * Returns the number of days in the coupon period that contains the settlement date.
481
+ *
482
+ * Excel Function:
483
+ * COUPDAYS(settlement,maturity,frequency[,basis])
484
+ *
485
+ * @access public
486
+ * @category Financial Functions
487
+ * @param mixed settlement The security's settlement date.
488
+ * The security settlement date is the date after the issue
489
+ * date when the security is traded to the buyer.
490
+ * @param mixed maturity The security's maturity date.
491
+ * The maturity date is the date when the security expires.
492
+ * @param mixed frequency the number of coupon payments per year.
493
+ * Valid frequency values are:
494
+ * 1 Annual
495
+ * 2 Semi-Annual
496
+ * 4 Quarterly
497
+ * If working in Gnumeric Mode, the following frequency options are
498
+ * also available
499
+ * 6 Bimonthly
500
+ * 12 Monthly
501
+ * @param integer basis The type of day count to use.
502
+ * 0 or omitted US (NASD) 30/360
503
+ * 1 Actual/actual
504
+ * 2 Actual/360
505
+ * 3 Actual/365
506
+ * 4 European 30/360
507
+ * @return float
508
+ */
509
+ public static function COUPDAYS($settlement, $maturity, $frequency, $basis=0) {
510
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
511
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
512
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
513
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
514
+
515
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
516
+ return PHPExcel_Calculation_Functions::VALUE();
517
+ }
518
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
519
+ return PHPExcel_Calculation_Functions::VALUE();
520
+ }
521
+
522
+ if (($settlement > $maturity) ||
523
+ (!self::_validFrequency($frequency)) ||
524
+ (($basis < 0) || ($basis > 4))) {
525
+ return PHPExcel_Calculation_Functions::NaN();
526
+ }
527
+
528
+ switch ($basis) {
529
+ case 3: // Actual/365
530
+ return 365 / $frequency;
531
+ case 1: // Actual/actual
532
+ if ($frequency == 1) {
533
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity),$basis);
534
+ return ($daysPerYear / $frequency);
535
+ } else {
536
+ $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
537
+ $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
538
+ return ($next - $prev);
539
+ }
540
+ default: // US (NASD) 30/360, Actual/360 or European 30/360
541
+ return 360 / $frequency;
542
+ }
543
+ return PHPExcel_Calculation_Functions::VALUE();
544
+ } // function COUPDAYS()
545
+
546
+
547
+ /**
548
+ * COUPDAYSNC
549
+ *
550
+ * Returns the number of days from the settlement date to the next coupon date.
551
+ *
552
+ * Excel Function:
553
+ * COUPDAYSNC(settlement,maturity,frequency[,basis])
554
+ *
555
+ * @access public
556
+ * @category Financial Functions
557
+ * @param mixed settlement The security's settlement date.
558
+ * The security settlement date is the date after the issue
559
+ * date when the security is traded to the buyer.
560
+ * @param mixed maturity The security's maturity date.
561
+ * The maturity date is the date when the security expires.
562
+ * @param mixed frequency the number of coupon payments per year.
563
+ * Valid frequency values are:
564
+ * 1 Annual
565
+ * 2 Semi-Annual
566
+ * 4 Quarterly
567
+ * If working in Gnumeric Mode, the following frequency options are
568
+ * also available
569
+ * 6 Bimonthly
570
+ * 12 Monthly
571
+ * @param integer basis The type of day count to use.
572
+ * 0 or omitted US (NASD) 30/360
573
+ * 1 Actual/actual
574
+ * 2 Actual/360
575
+ * 3 Actual/365
576
+ * 4 European 30/360
577
+ * @return float
578
+ */
579
+ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis=0) {
580
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
581
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
582
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
583
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
584
+
585
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
586
+ return PHPExcel_Calculation_Functions::VALUE();
587
+ }
588
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
589
+ return PHPExcel_Calculation_Functions::VALUE();
590
+ }
591
+
592
+ if (($settlement > $maturity) ||
593
+ (!self::_validFrequency($frequency)) ||
594
+ (($basis < 0) || ($basis > 4))) {
595
+ return PHPExcel_Calculation_Functions::NaN();
596
+ }
597
+
598
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
599
+ $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
600
+
601
+ return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
602
+ } // function COUPDAYSNC()
603
+
604
+
605
+ /**
606
+ * COUPNCD
607
+ *
608
+ * Returns the next coupon date after the settlement date.
609
+ *
610
+ * Excel Function:
611
+ * COUPNCD(settlement,maturity,frequency[,basis])
612
+ *
613
+ * @access public
614
+ * @category Financial Functions
615
+ * @param mixed settlement The security's settlement date.
616
+ * The security settlement date is the date after the issue
617
+ * date when the security is traded to the buyer.
618
+ * @param mixed maturity The security's maturity date.
619
+ * The maturity date is the date when the security expires.
620
+ * @param mixed frequency the number of coupon payments per year.
621
+ * Valid frequency values are:
622
+ * 1 Annual
623
+ * 2 Semi-Annual
624
+ * 4 Quarterly
625
+ * If working in Gnumeric Mode, the following frequency options are
626
+ * also available
627
+ * 6 Bimonthly
628
+ * 12 Monthly
629
+ * @param integer basis The type of day count to use.
630
+ * 0 or omitted US (NASD) 30/360
631
+ * 1 Actual/actual
632
+ * 2 Actual/360
633
+ * 3 Actual/365
634
+ * 4 European 30/360
635
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
636
+ * depending on the value of the ReturnDateType flag
637
+ */
638
+ public static function COUPNCD($settlement, $maturity, $frequency, $basis=0) {
639
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
640
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
641
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
642
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
643
+
644
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
645
+ return PHPExcel_Calculation_Functions::VALUE();
646
+ }
647
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
648
+ return PHPExcel_Calculation_Functions::VALUE();
649
+ }
650
+
651
+ if (($settlement > $maturity) ||
652
+ (!self::_validFrequency($frequency)) ||
653
+ (($basis < 0) || ($basis > 4))) {
654
+ return PHPExcel_Calculation_Functions::NaN();
655
+ }
656
+
657
+ return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True);
658
+ } // function COUPNCD()
659
+
660
+
661
+ /**
662
+ * COUPNUM
663
+ *
664
+ * Returns the number of coupons payable between the settlement date and maturity date,
665
+ * rounded up to the nearest whole coupon.
666
+ *
667
+ * Excel Function:
668
+ * COUPNUM(settlement,maturity,frequency[,basis])
669
+ *
670
+ * @access public
671
+ * @category Financial Functions
672
+ * @param mixed settlement The security's settlement date.
673
+ * The security settlement date is the date after the issue
674
+ * date when the security is traded to the buyer.
675
+ * @param mixed maturity The security's maturity date.
676
+ * The maturity date is the date when the security expires.
677
+ * @param mixed frequency the number of coupon payments per year.
678
+ * Valid frequency values are:
679
+ * 1 Annual
680
+ * 2 Semi-Annual
681
+ * 4 Quarterly
682
+ * If working in Gnumeric Mode, the following frequency options are
683
+ * also available
684
+ * 6 Bimonthly
685
+ * 12 Monthly
686
+ * @param integer basis The type of day count to use.
687
+ * 0 or omitted US (NASD) 30/360
688
+ * 1 Actual/actual
689
+ * 2 Actual/360
690
+ * 3 Actual/365
691
+ * 4 European 30/360
692
+ * @return integer
693
+ */
694
+ public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) {
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::_validFrequency($frequency)) ||
709
+ (($basis < 0) || ($basis > 4))) {
710
+ return PHPExcel_Calculation_Functions::NaN();
711
+ }
712
+
713
+ $settlement = self::_coupFirstPeriodDate($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
+ } // function COUPNUM()
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
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
767
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
768
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
769
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
770
+
771
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
772
+ return PHPExcel_Calculation_Functions::VALUE();
773
+ }
774
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
775
+ return PHPExcel_Calculation_Functions::VALUE();
776
+ }
777
+
778
+ if (($settlement > $maturity) ||
779
+ (!self::_validFrequency($frequency)) ||
780
+ (($basis < 0) || ($basis > 4))) {
781
+ return PHPExcel_Calculation_Functions::NaN();
782
+ }
783
+
784
+ return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False);
785
+ } // function COUPPCD()
786
+
787
+
788
+ /**
789
+ * CUMIPMT
790
+ *
791
+ * Returns the cumulative interest paid on a loan between the start and end periods.
792
+ *
793
+ * Excel Function:
794
+ * CUMIPMT(rate,nper,pv,start,end[,type])
795
+ *
796
+ * @access public
797
+ * @category Financial Functions
798
+ * @param float $rate The Interest rate
799
+ * @param integer $nper The total number of payment periods
800
+ * @param float $pv Present Value
801
+ * @param integer $start The first period in the calculation.
802
+ * Payment periods are numbered beginning with 1.
803
+ * @param integer $end The last period in the calculation.
804
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
805
+ * 0 or omitted At the end of the period.
806
+ * 1 At the beginning of the period.
807
+ * @return float
808
+ */
809
+ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) {
810
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
811
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
812
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
813
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
814
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
815
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
816
+
817
+ // Validate parameters
818
+ if ($type != 0 && $type != 1) {
819
+ return PHPExcel_Calculation_Functions::NaN();
820
+ }
821
+ if ($start < 1 || $start > $end) {
822
+ return PHPExcel_Calculation_Functions::VALUE();
823
+ }
824
+
825
+ // Calculate
826
+ $interest = 0;
827
+ for ($per = $start; $per <= $end; ++$per) {
828
+ $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
829
+ }
830
+
831
+ return $interest;
832
+ } // function CUMIPMT()
833
+
834
+
835
+ /**
836
+ * CUMPRINC
837
+ *
838
+ * Returns the cumulative principal paid on a loan between the start and end periods.
839
+ *
840
+ * Excel Function:
841
+ * CUMPRINC(rate,nper,pv,start,end[,type])
842
+ *
843
+ * @access public
844
+ * @category Financial Functions
845
+ * @param float $rate The Interest rate
846
+ * @param integer $nper The total number of payment periods
847
+ * @param float $pv Present Value
848
+ * @param integer $start The first period in the calculation.
849
+ * Payment periods are numbered beginning with 1.
850
+ * @param integer $end The last period in the calculation.
851
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
852
+ * 0 or omitted At the end of the period.
853
+ * 1 At the beginning of the period.
854
+ * @return float
855
+ */
856
+ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) {
857
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
858
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
859
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
860
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
861
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
862
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
863
+
864
+ // Validate parameters
865
+ if ($type != 0 && $type != 1) {
866
+ return PHPExcel_Calculation_Functions::NaN();
867
+ }
868
+ if ($start < 1 || $start > $end) {
869
+ return PHPExcel_Calculation_Functions::VALUE();
870
+ }
871
+
872
+ // Calculate
873
+ $principal = 0;
874
+ for ($per = $start; $per <= $end; ++$per) {
875
+ $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
876
+ }
877
+
878
+ return $principal;
879
+ } // function CUMPRINC()
880
+
881
+
882
+ /**
883
+ * DB
884
+ *
885
+ * Returns the depreciation of an asset for a specified period using the
886
+ * fixed-declining balance method.
887
+ * This form of depreciation is used if you want to get a higher depreciation value
888
+ * at the beginning of the depreciation (as opposed to linear depreciation). The
889
+ * depreciation value is reduced with every depreciation period by the depreciation
890
+ * already deducted from the initial cost.
891
+ *
892
+ * Excel Function:
893
+ * DB(cost,salvage,life,period[,month])
894
+ *
895
+ * @access public
896
+ * @category Financial Functions
897
+ * @param float cost Initial cost of the asset.
898
+ * @param float salvage Value at the end of the depreciation.
899
+ * (Sometimes called the salvage value of the asset)
900
+ * @param integer life Number of periods over which the asset is depreciated.
901
+ * (Sometimes called the useful life of the asset)
902
+ * @param integer period The period for which you want to calculate the
903
+ * depreciation. Period must use the same units as life.
904
+ * @param integer month Number of months in the first year. If month is omitted,
905
+ * it defaults to 12.
906
+ * @return float
907
+ */
908
+ public static function DB($cost, $salvage, $life, $period, $month=12) {
909
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
910
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
911
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
912
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
913
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
914
+
915
+ // Validate
916
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
917
+ $cost = (float) $cost;
918
+ $salvage = (float) $salvage;
919
+ $life = (int) $life;
920
+ $period = (int) $period;
921
+ $month = (int) $month;
922
+ if ($cost == 0) {
923
+ return 0.0;
924
+ } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
925
+ return PHPExcel_Calculation_Functions::NaN();
926
+ }
927
+ // Set Fixed Depreciation Rate
928
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
929
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
930
+
931
+ // Loop through each period calculating the depreciation
932
+ $previousDepreciation = 0;
933
+ for ($per = 1; $per <= $period; ++$per) {
934
+ if ($per == 1) {
935
+ $depreciation = $cost * $fixedDepreciationRate * $month / 12;
936
+ } elseif ($per == ($life + 1)) {
937
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
938
+ } else {
939
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
940
+ }
941
+ $previousDepreciation += $depreciation;
942
+ }
943
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
944
+ $depreciation = round($depreciation,2);
945
+ }
946
+ return $depreciation;
947
+ }
948
+ return PHPExcel_Calculation_Functions::VALUE();
949
+ } // function DB()
950
+
951
+
952
+ /**
953
+ * DDB
954
+ *
955
+ * Returns the depreciation of an asset for a specified period using the
956
+ * double-declining balance method or some other method you specify.
957
+ *
958
+ * Excel Function:
959
+ * DDB(cost,salvage,life,period[,factor])
960
+ *
961
+ * @access public
962
+ * @category Financial Functions
963
+ * @param float cost Initial cost of the asset.
964
+ * @param float salvage Value at the end of the depreciation.
965
+ * (Sometimes called the salvage value of the asset)
966
+ * @param integer life Number of periods over which the asset is depreciated.
967
+ * (Sometimes called the useful life of the asset)
968
+ * @param integer period The period for which you want to calculate the
969
+ * depreciation. Period must use the same units as life.
970
+ * @param float factor The rate at which the balance declines.
971
+ * If factor is omitted, it is assumed to be 2 (the
972
+ * double-declining balance method).
973
+ * @return float
974
+ */
975
+ public static function DDB($cost, $salvage, $life, $period, $factor=2.0) {
976
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
977
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
978
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
979
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
980
+ $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor);
981
+
982
+ // Validate
983
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
984
+ $cost = (float) $cost;
985
+ $salvage = (float) $salvage;
986
+ $life = (int) $life;
987
+ $period = (int) $period;
988
+ $factor = (float) $factor;
989
+ if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
990
+ return PHPExcel_Calculation_Functions::NaN();
991
+ }
992
+ // Set Fixed Depreciation Rate
993
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
994
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
995
+
996
+ // Loop through each period calculating the depreciation
997
+ $previousDepreciation = 0;
998
+ for ($per = 1; $per <= $period; ++$per) {
999
+ $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) );
1000
+ $previousDepreciation += $depreciation;
1001
+ }
1002
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1003
+ $depreciation = round($depreciation,2);
1004
+ }
1005
+ return $depreciation;
1006
+ }
1007
+ return PHPExcel_Calculation_Functions::VALUE();
1008
+ } // function DDB()
1009
+
1010
+
1011
+ /**
1012
+ * DISC
1013
+ *
1014
+ * Returns the discount rate for a security.
1015
+ *
1016
+ * Excel Function:
1017
+ * DISC(settlement,maturity,price,redemption[,basis])
1018
+ *
1019
+ * @access public
1020
+ * @category Financial Functions
1021
+ * @param mixed settlement The security's settlement date.
1022
+ * The security settlement date is the date after the issue
1023
+ * date when the security is traded to the buyer.
1024
+ * @param mixed maturity The security's maturity date.
1025
+ * The maturity date is the date when the security expires.
1026
+ * @param integer price The security's price per $100 face value.
1027
+ * @param integer redemption The security's redemption value per $100 face value.
1028
+ * @param integer basis The type of day count to use.
1029
+ * 0 or omitted US (NASD) 30/360
1030
+ * 1 Actual/actual
1031
+ * 2 Actual/360
1032
+ * 3 Actual/365
1033
+ * 4 European 30/360
1034
+ * @return float
1035
+ */
1036
+ public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) {
1037
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1038
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1039
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
1040
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1041
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1042
+
1043
+ // Validate
1044
+ if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1045
+ $price = (float) $price;
1046
+ $redemption = (float) $redemption;
1047
+ $basis = (int) $basis;
1048
+ if (($price <= 0) || ($redemption <= 0)) {
1049
+ return PHPExcel_Calculation_Functions::NaN();
1050
+ }
1051
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1052
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1053
+ // return date error
1054
+ return $daysBetweenSettlementAndMaturity;
1055
+ }
1056
+
1057
+ return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
1058
+ }
1059
+ return PHPExcel_Calculation_Functions::VALUE();
1060
+ } // function DISC()
1061
+
1062
+
1063
+ /**
1064
+ * DOLLARDE
1065
+ *
1066
+ * Converts a dollar price expressed as an integer part and a fraction
1067
+ * part into a dollar price expressed as a decimal number.
1068
+ * Fractional dollar numbers are sometimes used for security prices.
1069
+ *
1070
+ * Excel Function:
1071
+ * DOLLARDE(fractional_dollar,fraction)
1072
+ *
1073
+ * @access public
1074
+ * @category Financial Functions
1075
+ * @param float $fractional_dollar Fractional Dollar
1076
+ * @param integer $fraction Fraction
1077
+ * @return float
1078
+ */
1079
+ public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) {
1080
+ $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar);
1081
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
1082
+
1083
+ // Validate parameters
1084
+ if (is_null($fractional_dollar) || $fraction < 0) {
1085
+ return PHPExcel_Calculation_Functions::NaN();
1086
+ }
1087
+ if ($fraction == 0) {
1088
+ return PHPExcel_Calculation_Functions::DIV0();
1089
+ }
1090
+
1091
+ $dollars = floor($fractional_dollar);
1092
+ $cents = fmod($fractional_dollar,1);
1093
+ $cents /= $fraction;
1094
+ $cents *= pow(10,ceil(log10($fraction)));
1095
+ return $dollars + $cents;
1096
+ } // function DOLLARDE()
1097
+
1098
+
1099
+ /**
1100
+ * DOLLARFR
1101
+ *
1102
+ * Converts a dollar price expressed as a decimal number into a dollar price
1103
+ * expressed as a fraction.
1104
+ * Fractional dollar numbers are sometimes used for security prices.
1105
+ *
1106
+ * Excel Function:
1107
+ * DOLLARFR(decimal_dollar,fraction)
1108
+ *
1109
+ * @access public
1110
+ * @category Financial Functions
1111
+ * @param float $decimal_dollar Decimal Dollar
1112
+ * @param integer $fraction Fraction
1113
+ * @return float
1114
+ */
1115
+ public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) {
1116
+ $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar);
1117
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
1118
+
1119
+ // Validate parameters
1120
+ if (is_null($decimal_dollar) || $fraction < 0) {
1121
+ return PHPExcel_Calculation_Functions::NaN();
1122
+ }
1123
+ if ($fraction == 0) {
1124
+ return PHPExcel_Calculation_Functions::DIV0();
1125
+ }
1126
+
1127
+ $dollars = floor($decimal_dollar);
1128
+ $cents = fmod($decimal_dollar,1);
1129
+ $cents *= $fraction;
1130
+ $cents *= pow(10,-ceil(log10($fraction)));
1131
+ return $dollars + $cents;
1132
+ } // function DOLLARFR()
1133
+
1134
+
1135
+ /**
1136
+ * EFFECT
1137
+ *
1138
+ * Returns the effective interest rate given the nominal rate and the number of
1139
+ * compounding payments per year.
1140
+ *
1141
+ * Excel Function:
1142
+ * EFFECT(nominal_rate,npery)
1143
+ *
1144
+ * @access public
1145
+ * @category Financial Functions
1146
+ * @param float $nominal_rate Nominal interest rate
1147
+ * @param integer $npery Number of compounding payments per year
1148
+ * @return float
1149
+ */
1150
+ public static function EFFECT($nominal_rate = 0, $npery = 0) {
1151
+ $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate);
1152
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
1153
+
1154
+ // Validate parameters
1155
+ if ($nominal_rate <= 0 || $npery < 1) {
1156
+ return PHPExcel_Calculation_Functions::NaN();
1157
+ }
1158
+
1159
+ return pow((1 + $nominal_rate / $npery), $npery) - 1;
1160
+ } // function EFFECT()
1161
+
1162
+
1163
+ /**
1164
+ * FV
1165
+ *
1166
+ * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
1167
+ *
1168
+ * Excel Function:
1169
+ * FV(rate,nper,pmt[,pv[,type]])
1170
+ *
1171
+ * @access public
1172
+ * @category Financial Functions
1173
+ * @param float $rate The interest rate per period
1174
+ * @param int $nper Total number of payment periods in an annuity
1175
+ * @param float $pmt The payment made each period: it cannot change over the
1176
+ * life of the annuity. Typically, pmt contains principal
1177
+ * and interest but no other fees or taxes.
1178
+ * @param float $pv Present Value, or the lump-sum amount that a series of
1179
+ * future payments is worth right now.
1180
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
1181
+ * 0 or omitted At the end of the period.
1182
+ * 1 At the beginning of the period.
1183
+ * @return float
1184
+ */
1185
+ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
1186
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1187
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1188
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1189
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1190
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1191
+
1192
+ // Validate parameters
1193
+ if ($type != 0 && $type != 1) {
1194
+ return PHPExcel_Calculation_Functions::NaN();
1195
+ }
1196
+
1197
+ // Calculate
1198
+ if (!is_null($rate) && $rate != 0) {
1199
+ return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
1200
+ } else {
1201
+ return -$pv - $pmt * $nper;
1202
+ }
1203
+ } // function FV()
1204
+
1205
+
1206
+ /**
1207
+ * FVSCHEDULE
1208
+ *
1209
+ * Returns the future value of an initial principal after applying a series of compound interest rates.
1210
+ * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate.
1211
+ *
1212
+ * Excel Function:
1213
+ * FVSCHEDULE(principal,schedule)
1214
+ *
1215
+ * @param float $principal The present value.
1216
+ * @param float[] $schedule An array of interest rates to apply.
1217
+ * @return float
1218
+ */
1219
+ public static function FVSCHEDULE($principal, $schedule) {
1220
+ $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal);
1221
+ $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule);
1222
+
1223
+ foreach($schedule as $rate) {
1224
+ $principal *= 1 + $rate;
1225
+ }
1226
+
1227
+ return $principal;
1228
+ } // function FVSCHEDULE()
1229
+
1230
+
1231
+ /**
1232
+ * INTRATE
1233
+ *
1234
+ * Returns the interest rate for a fully invested security.
1235
+ *
1236
+ * Excel Function:
1237
+ * INTRATE(settlement,maturity,investment,redemption[,basis])
1238
+ *
1239
+ * @param mixed $settlement The security's settlement date.
1240
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1241
+ * @param mixed $maturity The security's maturity date.
1242
+ * The maturity date is the date when the security expires.
1243
+ * @param integer $investment The amount invested in the security.
1244
+ * @param integer $redemption The amount to be received at maturity.
1245
+ * @param integer $basis The type of day count to use.
1246
+ * 0 or omitted US (NASD) 30/360
1247
+ * 1 Actual/actual
1248
+ * 2 Actual/360
1249
+ * 3 Actual/365
1250
+ * 4 European 30/360
1251
+ * @return float
1252
+ */
1253
+ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) {
1254
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1255
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1256
+ $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment);
1257
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1258
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1259
+
1260
+ // Validate
1261
+ if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1262
+ $investment = (float) $investment;
1263
+ $redemption = (float) $redemption;
1264
+ $basis = (int) $basis;
1265
+ if (($investment <= 0) || ($redemption <= 0)) {
1266
+ return PHPExcel_Calculation_Functions::NaN();
1267
+ }
1268
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1269
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1270
+ // return date error
1271
+ return $daysBetweenSettlementAndMaturity;
1272
+ }
1273
+
1274
+ return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
1275
+ }
1276
+ return PHPExcel_Calculation_Functions::VALUE();
1277
+ } // function INTRATE()
1278
+
1279
+
1280
+ /**
1281
+ * IPMT
1282
+ *
1283
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
1284
+ *
1285
+ * Excel Function:
1286
+ * IPMT(rate,per,nper,pv[,fv][,type])
1287
+ *
1288
+ * @param float $rate Interest rate per period
1289
+ * @param int $per Period for which we want to find the interest
1290
+ * @param int $nper Number of periods
1291
+ * @param float $pv Present Value
1292
+ * @param float $fv Future Value
1293
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1294
+ * @return float
1295
+ */
1296
+ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
1297
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1298
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
1299
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1300
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1301
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1302
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1303
+
1304
+ // Validate parameters
1305
+ if ($type != 0 && $type != 1) {
1306
+ return PHPExcel_Calculation_Functions::NaN();
1307
+ }
1308
+ if ($per <= 0 || $per > $nper) {
1309
+ return PHPExcel_Calculation_Functions::VALUE();
1310
+ }
1311
+
1312
+ // Calculate
1313
+ $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
1314
+ return $interestAndPrincipal[0];
1315
+ } // function IPMT()
1316
+
1317
+ /**
1318
+ * IRR
1319
+ *
1320
+ * Returns the internal rate of return for a series of cash flows represented by the numbers in values.
1321
+ * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur
1322
+ * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received
1323
+ * for an investment consisting of payments (negative values) and income (positive values) that occur at regular
1324
+ * periods.
1325
+ *
1326
+ * Excel Function:
1327
+ * IRR(values[,guess])
1328
+ *
1329
+ * @param float[] $values An array or a reference to cells that contain numbers for which you want
1330
+ * to calculate the internal rate of return.
1331
+ * Values must contain at least one positive value and one negative value to
1332
+ * calculate the internal rate of return.
1333
+ * @param float $guess A number that you guess is close to the result of IRR
1334
+ * @return float
1335
+ */
1336
+ public static function IRR($values, $guess = 0.1) {
1337
+ if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE();
1338
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
1339
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
1340
+
1341
+ // create an initial range, with a root somewhere between 0 and guess
1342
+ $x1 = 0.0;
1343
+ $x2 = $guess;
1344
+ $f1 = self::NPV($x1, $values);
1345
+ $f2 = self::NPV($x2, $values);
1346
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
1347
+ if (($f1 * $f2) < 0.0) break;
1348
+ if (abs($f1) < abs($f2)) {
1349
+ $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
1350
+ } else {
1351
+ $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
1352
+ }
1353
+ }
1354
+ if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE();
1355
+
1356
+ $f = self::NPV($x1, $values);
1357
+ if ($f < 0.0) {
1358
+ $rtb = $x1;
1359
+ $dx = $x2 - $x1;
1360
+ } else {
1361
+ $rtb = $x2;
1362
+ $dx = $x1 - $x2;
1363
+ }
1364
+
1365
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
1366
+ $dx *= 0.5;
1367
+ $x_mid = $rtb + $dx;
1368
+ $f_mid = self::NPV($x_mid, $values);
1369
+ if ($f_mid <= 0.0)
1370
+ $rtb = $x_mid;
1371
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION))
1372
+ return $x_mid;
1373
+ }
1374
+ return PHPExcel_Calculation_Functions::VALUE();
1375
+ } // function IRR()
1376
+
1377
+
1378
+ /**
1379
+ * ISPMT
1380
+ *
1381
+ * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
1382
+ *
1383
+ * Excel Function:
1384
+ * =ISPMT(interest_rate, period, number_payments, PV)
1385
+ *
1386
+ * interest_rate is the interest rate for the investment
1387
+ *
1388
+ * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
1389
+ *
1390
+ * number_payments is the number of payments for the annuity
1391
+ *
1392
+ * PV is the loan amount or present value of the payments
1393
+ */
1394
+ public static function ISPMT() {
1395
+ // Return value
1396
+ $returnValue = 0;
1397
+
1398
+ // Get the parameters
1399
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1400
+ $interestRate = array_shift($aArgs);
1401
+ $period = array_shift($aArgs);
1402
+ $numberPeriods = array_shift($aArgs);
1403
+ $principleRemaining = array_shift($aArgs);
1404
+
1405
+ // Calculate
1406
+ $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
1407
+ for($i=0; $i <= $period; ++$i) {
1408
+ $returnValue = $interestRate * $principleRemaining * -1;
1409
+ $principleRemaining -= $principlePayment;
1410
+ // principle needs to be 0 after the last payment, don't let floating point screw it up
1411
+ if($i == $numberPeriods) {
1412
+ $returnValue = 0;
1413
+ }
1414
+ }
1415
+ return($returnValue);
1416
+ } // function ISPMT()
1417
+
1418
+
1419
+ /**
1420
+ * MIRR
1421
+ *
1422
+ * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both
1423
+ * the cost of the investment and the interest received on reinvestment of cash.
1424
+ *
1425
+ * Excel Function:
1426
+ * MIRR(values,finance_rate, reinvestment_rate)
1427
+ *
1428
+ * @param float[] $values An array or a reference to cells that contain a series of payments and
1429
+ * income occurring at regular intervals.
1430
+ * Payments are negative value, income is positive values.
1431
+ * @param float $finance_rate The interest rate you pay on the money used in the cash flows
1432
+ * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
1433
+ * @return float
1434
+ */
1435
+ public static function MIRR($values, $finance_rate, $reinvestment_rate) {
1436
+ if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE();
1437
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
1438
+ $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate);
1439
+ $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate);
1440
+ $n = count($values);
1441
+
1442
+ $rr = 1.0 + $reinvestment_rate;
1443
+ $fr = 1.0 + $finance_rate;
1444
+
1445
+ $npv_pos = $npv_neg = 0.0;
1446
+ foreach($values as $i => $v) {
1447
+ if ($v >= 0) {
1448
+ $npv_pos += $v / pow($rr, $i);
1449
+ } else {
1450
+ $npv_neg += $v / pow($fr, $i);
1451
+ }
1452
+ }
1453
+
1454
+ if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
1455
+ return PHPExcel_Calculation_Functions::VALUE();
1456
+ }
1457
+
1458
+ $mirr = pow((-$npv_pos * pow($rr, $n))
1459
+ / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
1460
+
1461
+ return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE());
1462
+ } // function MIRR()
1463
+
1464
+
1465
+ /**
1466
+ * NOMINAL
1467
+ *
1468
+ * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
1469
+ *
1470
+ * @param float $effect_rate Effective interest rate
1471
+ * @param int $npery Number of compounding payments per year
1472
+ * @return float
1473
+ */
1474
+ public static function NOMINAL($effect_rate = 0, $npery = 0) {
1475
+ $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate);
1476
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
1477
+
1478
+ // Validate parameters
1479
+ if ($effect_rate <= 0 || $npery < 1) {
1480
+ return PHPExcel_Calculation_Functions::NaN();
1481
+ }
1482
+
1483
+ // Calculate
1484
+ return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
1485
+ } // function NOMINAL()
1486
+
1487
+
1488
+ /**
1489
+ * NPER
1490
+ *
1491
+ * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
1492
+ *
1493
+ * @param float $rate Interest rate per period
1494
+ * @param int $pmt Periodic payment (annuity)
1495
+ * @param float $pv Present Value
1496
+ * @param float $fv Future Value
1497
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1498
+ * @return float
1499
+ */
1500
+ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) {
1501
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1502
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1503
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1504
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1505
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1506
+
1507
+ // Validate parameters
1508
+ if ($type != 0 && $type != 1) {
1509
+ return PHPExcel_Calculation_Functions::NaN();
1510
+ }
1511
+
1512
+ // Calculate
1513
+ if (!is_null($rate) && $rate != 0) {
1514
+ if ($pmt == 0 && $pv == 0) {
1515
+ return PHPExcel_Calculation_Functions::NaN();
1516
+ }
1517
+ return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
1518
+ } else {
1519
+ if ($pmt == 0) {
1520
+ return PHPExcel_Calculation_Functions::NaN();
1521
+ }
1522
+ return (-$pv -$fv) / $pmt;
1523
+ }
1524
+ } // function NPER()
1525
+
1526
+ /**
1527
+ * NPV
1528
+ *
1529
+ * Returns the Net Present Value of a cash flow series given a discount rate.
1530
+ *
1531
+ * @return float
1532
+ */
1533
+ public static function NPV() {
1534
+ // Return value
1535
+ $returnValue = 0;
1536
+
1537
+ // Loop through arguments
1538
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1539
+
1540
+ // Calculate
1541
+ $rate = array_shift($aArgs);
1542
+ for ($i = 1; $i <= count($aArgs); ++$i) {
1543
+ // Is it a numeric value?
1544
+ if (is_numeric($aArgs[$i - 1])) {
1545
+ $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
1546
+ }
1547
+ }
1548
+
1549
+ // Return
1550
+ return $returnValue;
1551
+ } // function NPV()
1552
+
1553
+ /**
1554
+ * PMT
1555
+ *
1556
+ * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
1557
+ *
1558
+ * @param float $rate Interest rate per period
1559
+ * @param int $nper Number of periods
1560
+ * @param float $pv Present Value
1561
+ * @param float $fv Future Value
1562
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1563
+ * @return float
1564
+ */
1565
+ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) {
1566
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1567
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1568
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1569
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1570
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1571
+
1572
+ // Validate parameters
1573
+ if ($type != 0 && $type != 1) {
1574
+ return PHPExcel_Calculation_Functions::NaN();
1575
+ }
1576
+
1577
+ // Calculate
1578
+ if (!is_null($rate) && $rate != 0) {
1579
+ return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
1580
+ } else {
1581
+ return (-$pv - $fv) / $nper;
1582
+ }
1583
+ } // function PMT()
1584
+
1585
+
1586
+ /**
1587
+ * PPMT
1588
+ *
1589
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
1590
+ *
1591
+ * @param float $rate Interest rate per period
1592
+ * @param int $per Period for which we want to find the interest
1593
+ * @param int $nper Number of periods
1594
+ * @param float $pv Present Value
1595
+ * @param float $fv Future Value
1596
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1597
+ * @return float
1598
+ */
1599
+ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
1600
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1601
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
1602
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1603
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1604
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1605
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1606
+
1607
+ // Validate parameters
1608
+ if ($type != 0 && $type != 1) {
1609
+ return PHPExcel_Calculation_Functions::NaN();
1610
+ }
1611
+ if ($per <= 0 || $per > $nper) {
1612
+ return PHPExcel_Calculation_Functions::VALUE();
1613
+ }
1614
+
1615
+ // Calculate
1616
+ $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
1617
+ return $interestAndPrincipal[1];
1618
+ } // function PPMT()
1619
+
1620
+
1621
+ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis=0) {
1622
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1623
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1624
+ $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1625
+ $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield);
1626
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1627
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
1628
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1629
+
1630
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) {
1631
+ return PHPExcel_Calculation_Functions::VALUE();
1632
+ }
1633
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
1634
+ return PHPExcel_Calculation_Functions::VALUE();
1635
+ }
1636
+
1637
+ if (($settlement > $maturity) ||
1638
+ (!self::_validFrequency($frequency)) ||
1639
+ (($basis < 0) || ($basis > 4))) {
1640
+ return PHPExcel_Calculation_Functions::NaN();
1641
+ }
1642
+
1643
+ $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
1644
+ $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
1645
+ $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
1646
+ $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
1647
+
1648
+ $baseYF = 1.0 + ($yield / $frequency);
1649
+ $rfp = 100 * ($rate / $frequency);
1650
+ $de = $dsc / $e;
1651
+
1652
+ $result = $redemption / pow($baseYF, (--$n + $de));
1653
+ for($k = 0; $k <= $n; ++$k) {
1654
+ $result += $rfp / (pow($baseYF, ($k + $de)));
1655
+ }
1656
+ $result -= $rfp * ($a / $e);
1657
+
1658
+ return $result;
1659
+ } // function PRICE()
1660
+
1661
+
1662
+ /**
1663
+ * PRICEDISC
1664
+ *
1665
+ * Returns the price per $100 face value of a discounted security.
1666
+ *
1667
+ * @param mixed settlement The security's settlement date.
1668
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1669
+ * @param mixed maturity The security's maturity date.
1670
+ * The maturity date is the date when the security expires.
1671
+ * @param int discount The security's discount rate.
1672
+ * @param int redemption The security's redemption value per $100 face value.
1673
+ * @param int basis The type of day count to use.
1674
+ * 0 or omitted US (NASD) 30/360
1675
+ * 1 Actual/actual
1676
+ * 2 Actual/360
1677
+ * 3 Actual/365
1678
+ * 4 European 30/360
1679
+ * @return float
1680
+ */
1681
+ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) {
1682
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1683
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1684
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
1685
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1686
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1687
+
1688
+ // Validate
1689
+ if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1690
+ if (($discount <= 0) || ($redemption <= 0)) {
1691
+ return PHPExcel_Calculation_Functions::NaN();
1692
+ }
1693
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1694
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1695
+ // return date error
1696
+ return $daysBetweenSettlementAndMaturity;
1697
+ }
1698
+
1699
+ return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
1700
+ }
1701
+ return PHPExcel_Calculation_Functions::VALUE();
1702
+ } // function PRICEDISC()
1703
+
1704
+
1705
+ /**
1706
+ * PRICEMAT
1707
+ *
1708
+ * Returns the price per $100 face value of a security that pays interest at maturity.
1709
+ *
1710
+ * @param mixed settlement The security's settlement date.
1711
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
1712
+ * @param mixed maturity The security's maturity date.
1713
+ * The maturity date is the date when the security expires.
1714
+ * @param mixed issue The security's issue date.
1715
+ * @param int rate The security's interest rate at date of issue.
1716
+ * @param int yield The security's annual yield.
1717
+ * @param int basis The type of day count to use.
1718
+ * 0 or omitted US (NASD) 30/360
1719
+ * 1 Actual/actual
1720
+ * 2 Actual/360
1721
+ * 3 Actual/365
1722
+ * 4 European 30/360
1723
+ * @return float
1724
+ */
1725
+ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) {
1726
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1727
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1728
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
1729
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1730
+ $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield);
1731
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1732
+
1733
+ // Validate
1734
+ if (is_numeric($rate) && is_numeric($yield)) {
1735
+ if (($rate <= 0) || ($yield <= 0)) {
1736
+ return PHPExcel_Calculation_Functions::NaN();
1737
+ }
1738
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
1739
+ if (!is_numeric($daysPerYear)) {
1740
+ return $daysPerYear;
1741
+ }
1742
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
1743
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
1744
+ // return date error
1745
+ return $daysBetweenIssueAndSettlement;
1746
+ }
1747
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
1748
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
1749
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
1750
+ // return date error
1751
+ return $daysBetweenIssueAndMaturity;
1752
+ }
1753
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
1754
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1755
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1756
+ // return date error
1757
+ return $daysBetweenSettlementAndMaturity;
1758
+ }
1759
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
1760
+
1761
+ return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
1762
+ (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
1763
+ (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
1764
+ }
1765
+ return PHPExcel_Calculation_Functions::VALUE();
1766
+ } // function PRICEMAT()
1767
+
1768
+
1769
+ /**
1770
+ * PV
1771
+ *
1772
+ * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
1773
+ *
1774
+ * @param float $rate Interest rate per period
1775
+ * @param int $nper Number of periods
1776
+ * @param float $pmt Periodic payment (annuity)
1777
+ * @param float $fv Future Value
1778
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1779
+ * @return float
1780
+ */
1781
+ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) {
1782
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1783
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1784
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1785
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1786
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1787
+
1788
+ // Validate parameters
1789
+ if ($type != 0 && $type != 1) {
1790
+ return PHPExcel_Calculation_Functions::NaN();
1791
+ }
1792
+
1793
+ // Calculate
1794
+ if (!is_null($rate) && $rate != 0) {
1795
+ return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
1796
+ } else {
1797
+ return -$fv - $pmt * $nper;
1798
+ }
1799
+ } // function PV()
1800
+
1801
+
1802
+ /**
1803
+ * RATE
1804
+ *
1805
+ * Returns the interest rate per period of an annuity.
1806
+ * RATE is calculated by iteration and can have zero or more solutions.
1807
+ * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
1808
+ * RATE returns the #NUM! error value.
1809
+ *
1810
+ * Excel Function:
1811
+ * RATE(nper,pmt,pv[,fv[,type[,guess]]])
1812
+ *
1813
+ * @access public
1814
+ * @category Financial Functions
1815
+ * @param float nper The total number of payment periods in an annuity.
1816
+ * @param float pmt The payment made each period and cannot change over the life
1817
+ * of the annuity.
1818
+ * Typically, pmt includes principal and interest but no other
1819
+ * fees or taxes.
1820
+ * @param float pv The present value - the total amount that a series of future
1821
+ * payments is worth now.
1822
+ * @param float fv The future value, or a cash balance you want to attain after
1823
+ * the last payment is made. If fv is omitted, it is assumed
1824
+ * to be 0 (the future value of a loan, for example, is 0).
1825
+ * @param integer type A number 0 or 1 and indicates when payments are due:
1826
+ * 0 or omitted At the end of the period.
1827
+ * 1 At the beginning of the period.
1828
+ * @param float guess Your guess for what the rate will be.
1829
+ * If you omit guess, it is assumed to be 10 percent.
1830
+ * @return float
1831
+ **/
1832
+ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
1833
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1834
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1835
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1836
+ $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1837
+ $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1838
+ $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess);
1839
+
1840
+ $rate = $guess;
1841
+ if (abs($rate) < FINANCIAL_PRECISION) {
1842
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
1843
+ } else {
1844
+ $f = exp($nper * log(1 + $rate));
1845
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1846
+ }
1847
+ $y0 = $pv + $pmt * $nper + $fv;
1848
+ $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1849
+
1850
+ // find root by secant method
1851
+ $i = $x0 = 0.0;
1852
+ $x1 = $rate;
1853
+ while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
1854
+ $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
1855
+ $x0 = $x1;
1856
+ $x1 = $rate;
1857
+ if (($nper * abs($pmt)) > ($pv - $fv))
1858
+ $x1 = abs($x1);
1859
+
1860
+ if (abs($rate) < FINANCIAL_PRECISION) {
1861
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
1862
+ } else {
1863
+ $f = exp($nper * log(1 + $rate));
1864
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1865
+ }
1866
+
1867
+ $y0 = $y1;
1868
+ $y1 = $y;
1869
+ ++$i;
1870
+ }
1871
+ return $rate;
1872
+ } // function RATE()
1873
+
1874
+
1875
+ /**
1876
+ * RECEIVED
1877
+ *
1878
+ * Returns the price per $100 face value of a discounted security.
1879
+ *
1880
+ * @param mixed settlement The security's settlement date.
1881
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1882
+ * @param mixed maturity The security's maturity date.
1883
+ * The maturity date is the date when the security expires.
1884
+ * @param int investment The amount invested in the security.
1885
+ * @param int discount The security's discount rate.
1886
+ * @param int basis The type of day count to use.
1887
+ * 0 or omitted US (NASD) 30/360
1888
+ * 1 Actual/actual
1889
+ * 2 Actual/360
1890
+ * 3 Actual/365
1891
+ * 4 European 30/360
1892
+ * @return float
1893
+ */
1894
+ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) {
1895
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1896
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1897
+ $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment);
1898
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
1899
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1900
+
1901
+ // Validate
1902
+ if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
1903
+ if (($investment <= 0) || ($discount <= 0)) {
1904
+ return PHPExcel_Calculation_Functions::NaN();
1905
+ }
1906
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1907
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1908
+ // return date error
1909
+ return $daysBetweenSettlementAndMaturity;
1910
+ }
1911
+
1912
+ return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
1913
+ }
1914
+ return PHPExcel_Calculation_Functions::VALUE();
1915
+ } // function RECEIVED()
1916
+
1917
+
1918
+ /**
1919
+ * SLN
1920
+ *
1921
+ * Returns the straight-line depreciation of an asset for one period
1922
+ *
1923
+ * @param cost Initial cost of the asset
1924
+ * @param salvage Value at the end of the depreciation
1925
+ * @param life Number of periods over which the asset is depreciated
1926
+ * @return float
1927
+ */
1928
+ public static function SLN($cost, $salvage, $life) {
1929
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
1930
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
1931
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
1932
+
1933
+ // Calculate
1934
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
1935
+ if ($life < 0) {
1936
+ return PHPExcel_Calculation_Functions::NaN();
1937
+ }
1938
+ return ($cost - $salvage) / $life;
1939
+ }
1940
+ return PHPExcel_Calculation_Functions::VALUE();
1941
+ } // function SLN()
1942
+
1943
+
1944
+ /**
1945
+ * SYD
1946
+ *
1947
+ * Returns the sum-of-years' digits depreciation of an asset for a specified period.
1948
+ *
1949
+ * @param cost Initial cost of the asset
1950
+ * @param salvage Value at the end of the depreciation
1951
+ * @param life Number of periods over which the asset is depreciated
1952
+ * @param period Period
1953
+ * @return float
1954
+ */
1955
+ public static function SYD($cost, $salvage, $life, $period) {
1956
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
1957
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
1958
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
1959
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
1960
+
1961
+ // Calculate
1962
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
1963
+ if (($life < 1) || ($period > $life)) {
1964
+ return PHPExcel_Calculation_Functions::NaN();
1965
+ }
1966
+ return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
1967
+ }
1968
+ return PHPExcel_Calculation_Functions::VALUE();
1969
+ } // function SYD()
1970
+
1971
+
1972
+ /**
1973
+ * TBILLEQ
1974
+ *
1975
+ * Returns the bond-equivalent yield for a Treasury bill.
1976
+ *
1977
+ * @param mixed settlement The Treasury bill's settlement date.
1978
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
1979
+ * @param mixed maturity The Treasury bill's maturity date.
1980
+ * The maturity date is the date when the Treasury bill expires.
1981
+ * @param int discount The Treasury bill's discount rate.
1982
+ * @return float
1983
+ */
1984
+ public static function TBILLEQ($settlement, $maturity, $discount) {
1985
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1986
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1987
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
1988
+
1989
+ // Use TBILLPRICE for validation
1990
+ $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
1991
+ if (is_string($testValue)) {
1992
+ return $testValue;
1993
+ }
1994
+
1995
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
1996
+ return PHPExcel_Calculation_Functions::VALUE();
1997
+ }
1998
+
1999
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2000
+ ++$maturity;
2001
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2002
+ } else {
2003
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
2004
+ }
2005
+
2006
+ return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
2007
+ } // function TBILLEQ()
2008
+
2009
+
2010
+ /**
2011
+ * TBILLPRICE
2012
+ *
2013
+ * Returns the yield for a Treasury bill.
2014
+ *
2015
+ * @param mixed settlement The Treasury bill's settlement date.
2016
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
2017
+ * @param mixed maturity The Treasury bill's maturity date.
2018
+ * The maturity date is the date when the Treasury bill expires.
2019
+ * @param int discount The Treasury bill's discount rate.
2020
+ * @return float
2021
+ */
2022
+ public static function TBILLPRICE($settlement, $maturity, $discount) {
2023
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2024
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2025
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
2026
+
2027
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) {
2028
+ return PHPExcel_Calculation_Functions::VALUE();
2029
+ }
2030
+
2031
+ // Validate
2032
+ if (is_numeric($discount)) {
2033
+ if ($discount <= 0) {
2034
+ return PHPExcel_Calculation_Functions::NaN();
2035
+ }
2036
+
2037
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2038
+ ++$maturity;
2039
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2040
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2041
+ // return date error
2042
+ return $daysBetweenSettlementAndMaturity;
2043
+ }
2044
+ } else {
2045
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
2046
+ }
2047
+
2048
+ if ($daysBetweenSettlementAndMaturity > 360) {
2049
+ return PHPExcel_Calculation_Functions::NaN();
2050
+ }
2051
+
2052
+ $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
2053
+ if ($price <= 0) {
2054
+ return PHPExcel_Calculation_Functions::NaN();
2055
+ }
2056
+ return $price;
2057
+ }
2058
+ return PHPExcel_Calculation_Functions::VALUE();
2059
+ } // function TBILLPRICE()
2060
+
2061
+
2062
+ /**
2063
+ * TBILLYIELD
2064
+ *
2065
+ * Returns the yield for a Treasury bill.
2066
+ *
2067
+ * @param mixed settlement The Treasury bill's settlement date.
2068
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
2069
+ * @param mixed maturity The Treasury bill's maturity date.
2070
+ * The maturity date is the date when the Treasury bill expires.
2071
+ * @param int price The Treasury bill's price per $100 face value.
2072
+ * @return float
2073
+ */
2074
+ public static function TBILLYIELD($settlement, $maturity, $price) {
2075
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2076
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2077
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2078
+
2079
+ // Validate
2080
+ if (is_numeric($price)) {
2081
+ if ($price <= 0) {
2082
+ return PHPExcel_Calculation_Functions::NaN();
2083
+ }
2084
+
2085
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2086
+ ++$maturity;
2087
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2088
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2089
+ // return date error
2090
+ return $daysBetweenSettlementAndMaturity;
2091
+ }
2092
+ } else {
2093
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement));
2094
+ }
2095
+
2096
+ if ($daysBetweenSettlementAndMaturity > 360) {
2097
+ return PHPExcel_Calculation_Functions::NaN();
2098
+ }
2099
+
2100
+ return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
2101
+ }
2102
+ return PHPExcel_Calculation_Functions::VALUE();
2103
+ } // function TBILLYIELD()
2104
+
2105
+
2106
+ public static function XIRR($values, $dates, $guess = 0.1) {
2107
+ if ((!is_array($values)) && (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE();
2108
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
2109
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
2110
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
2111
+ if (count($values) != count($dates)) return PHPExcel_Calculation_Functions::NaN();
2112
+
2113
+ // create an initial range, with a root somewhere between 0 and guess
2114
+ $x1 = 0.0;
2115
+ $x2 = $guess;
2116
+ $f1 = self::XNPV($x1, $values, $dates);
2117
+ $f2 = self::XNPV($x2, $values, $dates);
2118
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
2119
+ if (($f1 * $f2) < 0.0) break;
2120
+ if (abs($f1) < abs($f2)) {
2121
+ $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
2122
+ } else {
2123
+ $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
2124
+ }
2125
+ }
2126
+ if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE();
2127
+
2128
+ $f = self::XNPV($x1, $values, $dates);
2129
+ if ($f < 0.0) {
2130
+ $rtb = $x1;
2131
+ $dx = $x2 - $x1;
2132
+ } else {
2133
+ $rtb = $x2;
2134
+ $dx = $x1 - $x2;
2135
+ }
2136
+
2137
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
2138
+ $dx *= 0.5;
2139
+ $x_mid = $rtb + $dx;
2140
+ $f_mid = self::XNPV($x_mid, $values, $dates);
2141
+ if ($f_mid <= 0.0) $rtb = $x_mid;
2142
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
2143
+ }
2144
+ return PHPExcel_Calculation_Functions::VALUE();
2145
+ }
2146
+
2147
+
2148
+ /**
2149
+ * XNPV
2150
+ *
2151
+ * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
2152
+ * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
2153
+ *
2154
+ * Excel Function:
2155
+ * =XNPV(rate,values,dates)
2156
+ *
2157
+ * @param float $rate The discount rate to apply to the cash flows.
2158
+ * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. 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. The series of values must contain at least one positive value and one negative value.
2159
+ * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order.
2160
+ * @return float
2161
+ */
2162
+ public static function XNPV($rate, $values, $dates) {
2163
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
2164
+ if (!is_numeric($rate)) return PHPExcel_Calculation_Functions::VALUE();
2165
+ if ((!is_array($values)) || (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE();
2166
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
2167
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
2168
+ $valCount = count($values);
2169
+ if ($valCount != count($dates)) return PHPExcel_Calculation_Functions::NaN();
2170
+ if ((min($values) > 0) || (max($values) < 0)) return PHPExcel_Calculation_Functions::VALUE();
2171
+
2172
+ $xnpv = 0.0;
2173
+ for ($i = 0; $i < $valCount; ++$i) {
2174
+ if (!is_numeric($values[$i])) return PHPExcel_Calculation_Functions::VALUE();
2175
+ $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0],$dates[$i],'d') / 365);
2176
+ }
2177
+ return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE();
2178
+ } // function XNPV()
2179
+
2180
+
2181
+ /**
2182
+ * YIELDDISC
2183
+ *
2184
+ * Returns the annual yield of a security that pays interest at maturity.
2185
+ *
2186
+ * @param mixed settlement The security's settlement date.
2187
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
2188
+ * @param mixed maturity The security's maturity date.
2189
+ * The maturity date is the date when the security expires.
2190
+ * @param int price The security's price per $100 face value.
2191
+ * @param int redemption The security's redemption value per $100 face value.
2192
+ * @param int basis The type of day count to use.
2193
+ * 0 or omitted US (NASD) 30/360
2194
+ * 1 Actual/actual
2195
+ * 2 Actual/360
2196
+ * 3 Actual/365
2197
+ * 4 European 30/360
2198
+ * @return float
2199
+ */
2200
+ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) {
2201
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2202
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2203
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2204
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
2205
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
2206
+
2207
+ // Validate
2208
+ if (is_numeric($price) && is_numeric($redemption)) {
2209
+ if (($price <= 0) || ($redemption <= 0)) {
2210
+ return PHPExcel_Calculation_Functions::NaN();
2211
+ }
2212
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
2213
+ if (!is_numeric($daysPerYear)) {
2214
+ return $daysPerYear;
2215
+ }
2216
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity,$basis);
2217
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2218
+ // return date error
2219
+ return $daysBetweenSettlementAndMaturity;
2220
+ }
2221
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
2222
+
2223
+ return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
2224
+ }
2225
+ return PHPExcel_Calculation_Functions::VALUE();
2226
+ } // function YIELDDISC()
2227
+
2228
+
2229
+ /**
2230
+ * YIELDMAT
2231
+ *
2232
+ * Returns the annual yield of a security that pays interest at maturity.
2233
+ *
2234
+ * @param mixed settlement The security's settlement date.
2235
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
2236
+ * @param mixed maturity The security's maturity date.
2237
+ * The maturity date is the date when the security expires.
2238
+ * @param mixed issue The security's issue date.
2239
+ * @param int rate The security's interest rate at date of issue.
2240
+ * @param int price The security's price per $100 face value.
2241
+ * @param int basis The type of day count to use.
2242
+ * 0 or omitted US (NASD) 30/360
2243
+ * 1 Actual/actual
2244
+ * 2 Actual/360
2245
+ * 3 Actual/365
2246
+ * 4 European 30/360
2247
+ * @return float
2248
+ */
2249
+ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) {
2250
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2251
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2252
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
2253
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
2254
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2255
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
2256
+
2257
+ // Validate
2258
+ if (is_numeric($rate) && is_numeric($price)) {
2259
+ if (($rate <= 0) || ($price <= 0)) {
2260
+ return PHPExcel_Calculation_Functions::NaN();
2261
+ }
2262
+ $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis);
2263
+ if (!is_numeric($daysPerYear)) {
2264
+ return $daysPerYear;
2265
+ }
2266
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
2267
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
2268
+ // return date error
2269
+ return $daysBetweenIssueAndSettlement;
2270
+ }
2271
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
2272
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
2273
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
2274
+ // return date error
2275
+ return $daysBetweenIssueAndMaturity;
2276
+ }
2277
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
2278
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
2279
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2280
+ // return date error
2281
+ return $daysBetweenSettlementAndMaturity;
2282
+ }
2283
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
2284
+
2285
+ return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
2286
+ (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
2287
+ ($daysPerYear / $daysBetweenSettlementAndMaturity);
2288
+ }
2289
+ return PHPExcel_Calculation_Functions::VALUE();
2290
+ } // function YIELDMAT()
2291
+
2292
+ } // class PHPExcel_Calculation_Financial
libraries/PHPExcel/Calculation/FormulaParser.php ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /*
30
+ PARTLY BASED ON:
31
+ Copyright (c) 2007 E. W. Bachtal, Inc.
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
34
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
35
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
36
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
37
+ subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all copies or substantial
40
+ portions of the Software.
41
+
42
+ The software is provided "as is", without warranty of any kind, express or implied, including but not
43
+ limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
44
+ no event shall the authors or copyright holders be liable for any claim, damages or other liability,
45
+ whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
46
+ software or the use or other dealings in the software.
47
+
48
+ http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
49
+ http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
50
+ */
51
+
52
+ /**
53
+ * PHPExcel_Calculation_FormulaParser
54
+ *
55
+ * @category PHPExcel
56
+ * @package PHPExcel_Calculation
57
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
58
+ */
59
+ class PHPExcel_Calculation_FormulaParser {
60
+ /* Character constants */
61
+ const QUOTE_DOUBLE = '"';
62
+ const QUOTE_SINGLE = '\'';
63
+ const BRACKET_CLOSE = ']';
64
+ const BRACKET_OPEN = '[';
65
+ const BRACE_OPEN = '{';
66
+ const BRACE_CLOSE = '}';
67
+ const PAREN_OPEN = '(';
68
+ const PAREN_CLOSE = ')';
69
+ const SEMICOLON = ';';
70
+ const WHITESPACE = ' ';
71
+ const COMMA = ',';
72
+ const ERROR_START = '#';
73
+
74
+ const OPERATORS_SN = "+-";
75
+ const OPERATORS_INFIX = "+-*/^&=><";
76
+ const OPERATORS_POSTFIX = "%";
77
+
78
+ /**
79
+ * Formula
80
+ *
81
+ * @var string
82
+ */
83
+ private $_formula;
84
+
85
+ /**
86
+ * Tokens
87
+ *
88
+ * @var PHPExcel_Calculation_FormulaToken[]
89
+ */
90
+ private $_tokens = array();
91
+
92
+ /**
93
+ * Create a new PHPExcel_Calculation_FormulaParser
94
+ *
95
+ * @param string $pFormula Formula to parse
96
+ * @throws PHPExcel_Calculation_Exception
97
+ */
98
+ public function __construct($pFormula = '')
99
+ {
100
+ // Check parameters
101
+ if (is_null($pFormula)) {
102
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula");
103
+ }
104
+
105
+ // Initialise values
106
+ $this->_formula = trim($pFormula);
107
+ // Parse!
108
+ $this->_parseToTokens();
109
+ }
110
+
111
+ /**
112
+ * Get Formula
113
+ *
114
+ * @return string
115
+ */
116
+ public function getFormula() {
117
+ return $this->_formula;
118
+ }
119
+
120
+ /**
121
+ * Get Token
122
+ *
123
+ * @param int $pId Token id
124
+ * @return string
125
+ * @throws PHPExcel_Calculation_Exception
126
+ */
127
+ public function getToken($pId = 0) {
128
+ if (isset($this->_tokens[$pId])) {
129
+ return $this->_tokens[$pId];
130
+ } else {
131
+ throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist.");
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Get Token count
137
+ *
138
+ * @return string
139
+ */
140
+ public function getTokenCount() {
141
+ return count($this->_tokens);
142
+ }
143
+
144
+ /**
145
+ * Get Tokens
146
+ *
147
+ * @return PHPExcel_Calculation_FormulaToken[]
148
+ */
149
+ public function getTokens() {
150
+ return $this->_tokens;
151
+ }
152
+
153
+ /**
154
+ * Parse to tokens
155
+ */
156
+ private function _parseToTokens() {
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} != '=') return;
163
+
164
+ // Helper variables
165
+ $tokens1 = $tokens2 = $stack = array();
166
+ $inString = $inPath = $inRange = $inError = false;
167
+ $token = $previousToken = $nextToken = null;
168
+
169
+ $index = 1;
170
+ $value = '';
171
+
172
+ $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
173
+ $COMPARATORS_MULTI = array(">=", "<=", "<>");
174
+
175
+ while ($index < $formulaLength) {
176
+ // state-dependent character evaluation (order is important)
177
+
178
+ // double-quoted strings
179
+ // embeds are doubled
180
+ // end marks token
181
+ if ($inString) {
182
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
183
+ if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) {
184
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE;
185
+ ++$index;
186
+ } else {
187
+ $inString = false;
188
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
189
+ $value = "";
190
+ }
191
+ } else {
192
+ $value .= $this->_formula{$index};
193
+ }
194
+ ++$index;
195
+ continue;
196
+ }
197
+
198
+ // single-quoted strings (links)
199
+ // embeds are double
200
+ // end does not mark a token
201
+ if ($inPath) {
202
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
203
+ if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) {
204
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE;
205
+ ++$index;
206
+ } else {
207
+ $inPath = false;
208
+ }
209
+ } else {
210
+ $value .= $this->_formula{$index};
211
+ }
212
+ ++$index;
213
+ continue;
214
+ }
215
+
216
+ // bracked strings (R1C1 range index or linked workbook name)
217
+ // no embeds (changed to "()" by Excel)
218
+ // end does not mark a token
219
+ if ($inRange) {
220
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) {
221
+ $inRange = false;
222
+ }
223
+ $value .= $this->_formula{$index};
224
+ ++$index;
225
+ continue;
226
+ }
227
+
228
+ // error values
229
+ // end marks a token, determined from absolute list of values
230
+ if ($inError) {
231
+ $value .= $this->_formula{$index};
232
+ ++$index;
233
+ if (in_array($value, $ERRORS)) {
234
+ $inError = false;
235
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
236
+ $value = "";
237
+ }
238
+ continue;
239
+ }
240
+
241
+ // scientific notation check
242
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->_formula{$index}) !== false) {
243
+ if (strlen($value) > 1) {
244
+ if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->_formula{$index}) != 0) {
245
+ $value .= $this->_formula{$index};
246
+ ++$index;
247
+ continue;
248
+ }
249
+ }
250
+ }
251
+
252
+ // independent character evaluation (order not important)
253
+
254
+ // establish state-dependent character evaluations
255
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
256
+ if (strlen($value > 0)) { // unexpected
257
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
258
+ $value = "";
259
+ }
260
+ $inString = true;
261
+ ++$index;
262
+ continue;
263
+ }
264
+
265
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
266
+ if (strlen($value) > 0) { // unexpected
267
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
268
+ $value = "";
269
+ }
270
+ $inPath = true;
271
+ ++$index;
272
+ continue;
273
+ }
274
+
275
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) {
276
+ $inRange = true;
277
+ $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN;
278
+ ++$index;
279
+ continue;
280
+ }
281
+
282
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) {
283
+ if (strlen($value) > 0) { // unexpected
284
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
285
+ $value = "";
286
+ }
287
+ $inError = true;
288
+ $value .= PHPExcel_Calculation_FormulaParser::ERROR_START;
289
+ ++$index;
290
+ continue;
291
+ }
292
+
293
+ // mark start and end of arrays and array rows
294
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) {
295
+ if (strlen($value) > 0) { // unexpected
296
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
297
+ $value = "";
298
+ }
299
+
300
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
301
+ $tokens1[] = $tmp;
302
+ $stack[] = clone $tmp;
303
+
304
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
305
+ $tokens1[] = $tmp;
306
+ $stack[] = clone $tmp;
307
+
308
+ ++$index;
309
+ continue;
310
+ }
311
+
312
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) {
313
+ if (strlen($value) > 0) {
314
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
315
+ $value = "";
316
+ }
317
+
318
+ $tmp = array_pop($stack);
319
+ $tmp->setValue("");
320
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
321
+ $tokens1[] = $tmp;
322
+
323
+ $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
324
+ $tokens1[] = $tmp;
325
+
326
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
327
+ $tokens1[] = $tmp;
328
+ $stack[] = clone $tmp;
329
+
330
+ ++$index;
331
+ continue;
332
+ }
333
+
334
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) {
335
+ if (strlen($value) > 0) {
336
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
337
+ $value = "";
338
+ }
339
+
340
+ $tmp = array_pop($stack);
341
+ $tmp->setValue("");
342
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
343
+ $tokens1[] = $tmp;
344
+
345
+ $tmp = array_pop($stack);
346
+ $tmp->setValue("");
347
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
348
+ $tokens1[] = $tmp;
349
+
350
+ ++$index;
351
+ continue;
352
+ }
353
+
354
+ // trim white-space
355
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) {
356
+ if (strlen($value) > 0) {
357
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
358
+ $value = "";
359
+ }
360
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
361
+ ++$index;
362
+ while (($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
363
+ ++$index;
364
+ }
365
+ continue;
366
+ }
367
+
368
+ // multi-character comparators
369
+ if (($index + 2) <= $formulaLength) {
370
+ if (in_array(substr($this->_formula, $index, 2), $COMPARATORS_MULTI)) {
371
+ if (strlen($value) > 0) {
372
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
373
+ $value = "";
374
+ }
375
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->_formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
376
+ $index += 2;
377
+ continue;
378
+ }
379
+ }
380
+
381
+ // standard infix operators
382
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->_formula{$index}) !== false) {
383
+ if (strlen($value) > 0) {
384
+ $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
385
+ $value = "";
386
+ }
387
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
388
+ ++$index;
389
+ continue;
390
+ }
391
+
392
+ // standard postfix operators (only one)
393
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->_formula{$index}) !== false) {
394
+ if (strlen($value) > 0) {
395
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
396
+ $value = "";
397
+ }
398
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
399
+ ++$index;
400
+ continue;
401
+ }
402
+
403
+ // start subexpression or function
404
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) {
405
+ if (strlen($value) > 0) {
406
+ $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
407
+ $tokens1[] = $tmp;
408
+ $stack[] = clone $tmp;
409
+ $value = "";
410
+ } else {
411
+ $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
412
+ $tokens1[] = $tmp;
413
+ $stack[] = clone $tmp;
414
+ }
415
+ ++$index;
416
+ continue;
417
+ }
418
+
419
+ // function, subexpression, or array parameters, or operand unions
420
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) {
421
+ if (strlen($value) > 0) {
422
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
423
+ $value = "";
424
+ }
425
+
426
+ $tmp = array_pop($stack);
427
+ $tmp->setValue("");
428
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
429
+ $stack[] = $tmp;
430
+
431
+ if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
432
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
433
+ } else {
434
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
435
+ }
436
+ ++$index;
437
+ continue;
438
+ }
439
+
440
+ // stop subexpression
441
+ if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) {
442
+ if (strlen($value) > 0) {
443
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
444
+ $value = "";
445
+ }
446
+
447
+ $tmp = array_pop($stack);
448
+ $tmp->setValue("");
449
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
450
+ $tokens1[] = $tmp;
451
+
452
+ ++$index;
453
+ continue;
454
+ }
455
+
456
+ // token accumulation
457
+ $value .= $this->_formula{$index};
458
+ ++$index;
459
+ }
460
+
461
+ // dump remaining accumulation
462
+ if (strlen($value) > 0) {
463
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
464
+ }
465
+
466
+ // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
467
+ $tokenCount = count($tokens1);
468
+ for ($i = 0; $i < $tokenCount; ++$i) {
469
+ $token = $tokens1[$i];
470
+ if (isset($tokens1[$i - 1])) {
471
+ $previousToken = $tokens1[$i - 1];
472
+ } else {
473
+ $previousToken = null;
474
+ }
475
+ if (isset($tokens1[$i + 1])) {
476
+ $nextToken = $tokens1[$i + 1];
477
+ } else {
478
+ $nextToken = null;
479
+ }
480
+
481
+ if (is_null($token)) {
482
+ continue;
483
+ }
484
+
485
+ if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
486
+ $tokens2[] = $token;
487
+ continue;
488
+ }
489
+
490
+ if (is_null($previousToken)) {
491
+ continue;
492
+ }
493
+
494
+ if (! (
495
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
496
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
497
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
498
+ ) ) {
499
+ continue;
500
+ }
501
+
502
+ if (is_null($nextToken)) {
503
+ continue;
504
+ }
505
+
506
+ if (! (
507
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
508
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
509
+ ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
510
+ ) ) {
511
+ continue;
512
+ }
513
+
514
+ $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
515
+ }
516
+
517
+ // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
518
+ // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
519
+ $this->_tokens = array();
520
+
521
+ $tokenCount = count($tokens2);
522
+ for ($i = 0; $i < $tokenCount; ++$i) {
523
+ $token = $tokens2[$i];
524
+ if (isset($tokens2[$i - 1])) {
525
+ $previousToken = $tokens2[$i - 1];
526
+ } else {
527
+ $previousToken = null;
528
+ }
529
+ if (isset($tokens2[$i + 1])) {
530
+ $nextToken = $tokens2[$i + 1];
531
+ } else {
532
+ $nextToken = null;
533
+ }
534
+
535
+ if (is_null($token)) {
536
+ continue;
537
+ }
538
+
539
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
540
+ if ($i == 0) {
541
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
542
+ } else if (
543
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
544
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
545
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
546
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
547
+ ) {
548
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
549
+ } else {
550
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
551
+ }
552
+
553
+ $this->_tokens[] = $token;
554
+ continue;
555
+ }
556
+
557
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
558
+ if ($i == 0) {
559
+ continue;
560
+ } else if (
561
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
562
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
563
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
564
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
565
+ ) {
566
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
567
+ } else {
568
+ continue;
569
+ }
570
+
571
+ $this->_tokens[] = $token;
572
+ continue;
573
+ }
574
+
575
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
576
+ if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
577
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
578
+ } else if ($token->getValue() == "&") {
579
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
580
+ } else {
581
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
582
+ }
583
+
584
+ $this->_tokens[] = $token;
585
+ continue;
586
+ }
587
+
588
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
589
+ if (!is_numeric($token->getValue())) {
590
+ if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
591
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
592
+ } else {
593
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
594
+ }
595
+ } else {
596
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
597
+ }
598
+
599
+ $this->_tokens[] = $token;
600
+ continue;
601
+ }
602
+
603
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
604
+ if (strlen($token->getValue() > 0)) {
605
+ if (substr($token->getValue(), 0, 1) == "@") {
606
+ $token->setValue(substr($token->getValue(), 1));
607
+ }
608
+ }
609
+ }
610
+
611
+ $this->_tokens[] = $token;
612
+ }
613
+ }
614
+ }
libraries/PHPExcel/Calculation/FormulaToken.php ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /*
30
+ PARTLY BASED ON:
31
+ Copyright (c) 2007 E. W. Bachtal, Inc.
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
34
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
35
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
36
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
37
+ subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in all copies or substantial
40
+ portions of the Software.
41
+
42
+ The software is provided "as is", without warranty of any kind, express or implied, including but not
43
+ limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
44
+ no event shall the authors or copyright holders be liable for any claim, damages or other liability,
45
+ whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
46
+ software or the use or other dealings in the software.
47
+
48
+ http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
49
+ http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
50
+ */
51
+
52
+
53
+ /**
54
+ * PHPExcel_Calculation_FormulaToken
55
+ *
56
+ * @category PHPExcel
57
+ * @package PHPExcel_Calculation
58
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
59
+ */
60
+ class PHPExcel_Calculation_FormulaToken {
61
+ /* Token types */
62
+ const TOKEN_TYPE_NOOP = 'Noop';
63
+ const TOKEN_TYPE_OPERAND = 'Operand';
64
+ const TOKEN_TYPE_FUNCTION = 'Function';
65
+ const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression';
66
+ const TOKEN_TYPE_ARGUMENT = 'Argument';
67
+ const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix';
68
+ const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix';
69
+ const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix';
70
+ const TOKEN_TYPE_WHITESPACE = 'Whitespace';
71
+ const TOKEN_TYPE_UNKNOWN = 'Unknown';
72
+
73
+ /* Token subtypes */
74
+ const TOKEN_SUBTYPE_NOTHING = 'Nothing';
75
+ const TOKEN_SUBTYPE_START = 'Start';
76
+ const TOKEN_SUBTYPE_STOP = 'Stop';
77
+ const TOKEN_SUBTYPE_TEXT = 'Text';
78
+ const TOKEN_SUBTYPE_NUMBER = 'Number';
79
+ const TOKEN_SUBTYPE_LOGICAL = 'Logical';
80
+ const TOKEN_SUBTYPE_ERROR = 'Error';
81
+ const TOKEN_SUBTYPE_RANGE = 'Range';
82
+ const TOKEN_SUBTYPE_MATH = 'Math';
83
+ const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation';
84
+ const TOKEN_SUBTYPE_INTERSECTION = 'Intersection';
85
+ const TOKEN_SUBTYPE_UNION = 'Union';
86
+
87
+ /**
88
+ * Value
89
+ *
90
+ * @var string
91
+ */
92
+ private $_value;
93
+
94
+ /**
95
+ * Token Type (represented by TOKEN_TYPE_*)
96
+ *
97
+ * @var string
98
+ */
99
+ private $_tokenType;
100
+
101
+ /**
102
+ * Token SubType (represented by TOKEN_SUBTYPE_*)
103
+ *
104
+ * @var string
105
+ */
106
+ private $_tokenSubType;
107
+
108
+ /**
109
+ * Create a new PHPExcel_Calculation_FormulaToken
110
+ *
111
+ * @param string $pValue
112
+ * @param string $pTokenType Token type (represented by TOKEN_TYPE_*)
113
+ * @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
114
+ */
115
+ public function __construct($pValue, $pTokenType = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN, $pTokenSubType = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING)
116
+ {
117
+ // Initialise values
118
+ $this->_value = $pValue;
119
+ $this->_tokenType = $pTokenType;
120
+ $this->_tokenSubType = $pTokenSubType;
121
+ }
122
+
123
+ /**
124
+ * Get Value
125
+ *
126
+ * @return string
127
+ */
128
+ public function getValue() {
129
+ return $this->_value;
130
+ }
131
+
132
+ /**
133
+ * Set Value
134
+ *
135
+ * @param string $value
136
+ */
137
+ public function setValue($value) {
138
+ $this->_value = $value;
139
+ }
140
+
141
+ /**
142
+ * Get Token Type (represented by TOKEN_TYPE_*)
143
+ *
144
+ * @return string
145
+ */
146
+ public function getTokenType() {
147
+ return $this->_tokenType;
148
+ }
149
+
150
+ /**
151
+ * Set Token Type
152
+ *
153
+ * @param string $value
154
+ */
155
+ public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) {
156
+ $this->_tokenType = $value;
157
+ }
158
+
159
+ /**
160
+ * Get Token SubType (represented by TOKEN_SUBTYPE_*)
161
+ *
162
+ * @return string
163
+ */
164
+ public function getTokenSubType() {
165
+ return $this->_tokenSubType;
166
+ }
167
+
168
+ /**
169
+ * Set Token SubType
170
+ *
171
+ * @param string $value
172
+ */
173
+ public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
174
+ $this->_tokenSubType = $value;
175
+ }
176
+ }
libraries/PHPExcel/Calculation/Function.php ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Calculation_Function
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Calculation
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Calculation_Function {
37
+ /* Function categories */
38
+ const CATEGORY_CUBE = 'Cube';
39
+ const CATEGORY_DATABASE = 'Database';
40
+ const CATEGORY_DATE_AND_TIME = 'Date and Time';
41
+ const CATEGORY_ENGINEERING = 'Engineering';
42
+ const CATEGORY_FINANCIAL = 'Financial';
43
+ const CATEGORY_INFORMATION = 'Information';
44
+ const CATEGORY_LOGICAL = 'Logical';
45
+ const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference';
46
+ const CATEGORY_MATH_AND_TRIG = 'Math and Trig';
47
+ const CATEGORY_STATISTICAL = 'Statistical';
48
+ const CATEGORY_TEXT_AND_DATA = 'Text and Data';
49
+
50
+ /**
51
+ * Category (represented by CATEGORY_*)
52
+ *
53
+ * @var string
54
+ */
55
+ private $_category;
56
+
57
+ /**
58
+ * Excel name
59
+ *
60
+ * @var string
61
+ */
62
+ private $_excelName;
63
+
64
+ /**
65
+ * PHPExcel name
66
+ *
67
+ * @var string
68
+ */
69
+ private $_phpExcelName;
70
+
71
+ /**
72
+ * Create a new PHPExcel_Calculation_Function
73
+ *
74
+ * @param string $pCategory Category (represented by CATEGORY_*)
75
+ * @param string $pExcelName Excel function name
76
+ * @param string $pPHPExcelName PHPExcel function mapping
77
+ * @throws PHPExcel_Calculation_Exception
78
+ */
79
+ public function __construct($pCategory = NULL, $pExcelName = NULL, $pPHPExcelName = NULL)
80
+ {
81
+ if (($pCategory !== NULL) && ($pExcelName !== NULL) && ($pPHPExcelName !== NULL)) {
82
+ // Initialise values
83
+ $this->_category = $pCategory;
84
+ $this->_excelName = $pExcelName;
85
+ $this->_phpExcelName = $pPHPExcelName;
86
+ } else {
87
+ throw new PHPExcel_Calculation_Exception("Invalid parameters passed.");
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Get Category (represented by CATEGORY_*)
93
+ *
94
+ * @return string
95
+ */
96
+ public function getCategory() {
97
+ return $this->_category;
98
+ }
99
+
100
+ /**
101
+ * Set Category (represented by CATEGORY_*)
102
+ *
103
+ * @param string $value
104
+ * @throws PHPExcel_Calculation_Exception
105
+ */
106
+ public function setCategory($value = null) {
107
+ if (!is_null($value)) {
108
+ $this->_category = $value;
109
+ } else {
110
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed.");
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Get Excel name
116
+ *
117
+ * @return string
118
+ */
119
+ public function getExcelName() {
120
+ return $this->_excelName;
121
+ }
122
+
123
+ /**
124
+ * Set Excel name
125
+ *
126
+ * @param string $value
127
+ */
128
+ public function setExcelName($value) {
129
+ $this->_excelName = $value;
130
+ }
131
+
132
+ /**
133
+ * Get PHPExcel name
134
+ *
135
+ * @return string
136
+ */
137
+ public function getPHPExcelName() {
138
+ return $this->_phpExcelName;
139
+ }
140
+
141
+ /**
142
+ * Set PHPExcel name
143
+ *
144
+ * @param string $value
145
+ */
146
+ public function setPHPExcelName($value) {
147
+ $this->_phpExcelName = $value;
148
+ }
149
+ }
libraries/PHPExcel/Calculation/Functions.php ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /** MAX_VALUE */
40
+ define('MAX_VALUE', 1.2e308);
41
+
42
+ /** 2 / PI */
43
+ define('M_2DIVPI', 0.63661977236758134307553505349006);
44
+
45
+ /** MAX_ITERATIONS */
46
+ define('MAX_ITERATIONS', 256);
47
+
48
+ /** PRECISION */
49
+ define('PRECISION', 8.88E-016);
50
+
51
+
52
+ /**
53
+ * PHPExcel_Calculation_Functions
54
+ *
55
+ * @category PHPExcel
56
+ * @package PHPExcel_Calculation
57
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
58
+ */
59
+ class PHPExcel_Calculation_Functions {
60
+
61
+ /** constants */
62
+ const COMPATIBILITY_EXCEL = 'Excel';
63
+ const COMPATIBILITY_GNUMERIC = 'Gnumeric';
64
+ const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
65
+
66
+ const RETURNDATE_PHP_NUMERIC = 'P';
67
+ const RETURNDATE_PHP_OBJECT = 'O';
68
+ const RETURNDATE_EXCEL = 'E';
69
+
70
+
71
+ /**
72
+ * Compatibility mode to use for error checking and responses
73
+ *
74
+ * @access private
75
+ * @var string
76
+ */
77
+ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
78
+
79
+ /**
80
+ * Data Type to use when returning date values
81
+ *
82
+ * @access private
83
+ * @var string
84
+ */
85
+ protected static $ReturnDateType = self::RETURNDATE_EXCEL;
86
+
87
+ /**
88
+ * List of error codes
89
+ *
90
+ * @access private
91
+ * @var array
92
+ */
93
+ protected static $_errorCodes = array( 'null' => '#NULL!',
94
+ 'divisionbyzero' => '#DIV/0!',
95
+ 'value' => '#VALUE!',
96
+ 'reference' => '#REF!',
97
+ 'name' => '#NAME?',
98
+ 'num' => '#NUM!',
99
+ 'na' => '#N/A',
100
+ 'gettingdata' => '#GETTING_DATA'
101
+ );
102
+
103
+
104
+ /**
105
+ * Set the Compatibility Mode
106
+ *
107
+ * @access public
108
+ * @category Function Configuration
109
+ * @param string $compatibilityMode Compatibility Mode
110
+ * Permitted values are:
111
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
112
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
113
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
114
+ * @return boolean (Success or Failure)
115
+ */
116
+ public static function setCompatibilityMode($compatibilityMode) {
117
+ if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
118
+ ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
119
+ ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
120
+ self::$compatibilityMode = $compatibilityMode;
121
+ return True;
122
+ }
123
+ return False;
124
+ } // function setCompatibilityMode()
125
+
126
+
127
+ /**
128
+ * Return the current Compatibility Mode
129
+ *
130
+ * @access public
131
+ * @category Function Configuration
132
+ * @return string Compatibility Mode
133
+ * Possible Return values are:
134
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
135
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
136
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
137
+ */
138
+ public static function getCompatibilityMode() {
139
+ return self::$compatibilityMode;
140
+ } // function getCompatibilityMode()
141
+
142
+
143
+ /**
144
+ * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
145
+ *
146
+ * @access public
147
+ * @category Function Configuration
148
+ * @param string $returnDateType Return Date Format
149
+ * Permitted values are:
150
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
151
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
152
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
153
+ * @return boolean Success or failure
154
+ */
155
+ public static function setReturnDateType($returnDateType) {
156
+ if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
157
+ ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
158
+ ($returnDateType == self::RETURNDATE_EXCEL)) {
159
+ self::$ReturnDateType = $returnDateType;
160
+ return True;
161
+ }
162
+ return False;
163
+ } // function setReturnDateType()
164
+
165
+
166
+ /**
167
+ * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
168
+ *
169
+ * @access public
170
+ * @category Function Configuration
171
+ * @return string Return Date Format
172
+ * Possible Return values are:
173
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
174
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
175
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
176
+ */
177
+ public static function getReturnDateType() {
178
+ return self::$ReturnDateType;
179
+ } // function getReturnDateType()
180
+
181
+
182
+ /**
183
+ * DUMMY
184
+ *
185
+ * @access public
186
+ * @category Error Returns
187
+ * @return string #Not Yet Implemented
188
+ */
189
+ public static function DUMMY() {
190
+ return '#Not Yet Implemented';
191
+ } // function DUMMY()
192
+
193
+
194
+ /**
195
+ * DIV0
196
+ *
197
+ * @access public
198
+ * @category Error Returns
199
+ * @return string #Not Yet Implemented
200
+ */
201
+ public static function DIV0() {
202
+ return self::$_errorCodes['divisionbyzero'];
203
+ } // function DIV0()
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
+ return self::$_errorCodes['na'];
221
+ } // function NA()
222
+
223
+
224
+ /**
225
+ * NaN
226
+ *
227
+ * Returns the error value #NUM!
228
+ *
229
+ * @access public
230
+ * @category Error Returns
231
+ * @return string #NUM!
232
+ */
233
+ public static function NaN() {
234
+ return self::$_errorCodes['num'];
235
+ } // function NaN()
236
+
237
+
238
+ /**
239
+ * NAME
240
+ *
241
+ * Returns the error value #NAME?
242
+ *
243
+ * @access public
244
+ * @category Error Returns
245
+ * @return string #NAME?
246
+ */
247
+ public static function NAME() {
248
+ return self::$_errorCodes['name'];
249
+ } // function NAME()
250
+
251
+
252
+ /**
253
+ * REF
254
+ *
255
+ * Returns the error value #REF!
256
+ *
257
+ * @access public
258
+ * @category Error Returns
259
+ * @return string #REF!
260
+ */
261
+ public static function REF() {
262
+ return self::$_errorCodes['reference'];
263
+ } // function REF()
264
+
265
+
266
+ /**
267
+ * NULL
268
+ *
269
+ * Returns the error value #NULL!
270
+ *
271
+ * @access public
272
+ * @category Error Returns
273
+ * @return string #NULL!
274
+ */
275
+ public static function NULL() {
276
+ return self::$_errorCodes['null'];
277
+ } // function NULL()
278
+
279
+
280
+ /**
281
+ * VALUE
282
+ *
283
+ * Returns the error value #VALUE!
284
+ *
285
+ * @access public
286
+ * @category Error Returns
287
+ * @return string #VALUE!
288
+ */
289
+ public static function VALUE() {
290
+ return self::$_errorCodes['value'];
291
+ } // function VALUE()
292
+
293
+
294
+ public static function isMatrixValue($idx) {
295
+ return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0));
296
+ }
297
+
298
+
299
+ public static function isValue($idx) {
300
+ return (substr_count($idx,'.') == 0);
301
+ }
302
+
303
+
304
+ public static function isCellValue($idx) {
305
+ return (substr_count($idx,'.') > 1);
306
+ }
307
+
308
+
309
+ public static function _ifCondition($condition) {
310
+ $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition);
311
+ if (!isset($condition{0}))
312
+ $condition = '=""';
313
+ if (!in_array($condition{0},array('>', '<', '='))) {
314
+ if (!is_numeric($condition)) { $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition)); }
315
+ return '='.$condition;
316
+ } else {
317
+ preg_match('/([<>=]+)(.*)/',$condition,$matches);
318
+ list(,$operator,$operand) = $matches;
319
+
320
+ if (!is_numeric($operand)) {
321
+ $operand = str_replace('"', '""', $operand);
322
+ $operand = PHPExcel_Calculation::_wrapResult(strtoupper($operand));
323
+ }
324
+
325
+ return $operator.$operand;
326
+ }
327
+ } // function _ifCondition()
328
+
329
+
330
+ /**
331
+ * ERROR_TYPE
332
+ *
333
+ * @param mixed $value Value to check
334
+ * @return boolean
335
+ */
336
+ public static function ERROR_TYPE($value = '') {
337
+ $value = self::flattenSingleValue($value);
338
+
339
+ $i = 1;
340
+ foreach(self::$_errorCodes as $errorCode) {
341
+ if ($value === $errorCode) {
342
+ return $i;
343
+ }
344
+ ++$i;
345
+ }
346
+ return self::NA();
347
+ } // function ERROR_TYPE()
348
+
349
+
350
+ /**
351
+ * IS_BLANK
352
+ *
353
+ * @param mixed $value Value to check
354
+ * @return boolean
355
+ */
356
+ public static function IS_BLANK($value = NULL) {
357
+ if (!is_null($value)) {
358
+ $value = self::flattenSingleValue($value);
359
+ }
360
+
361
+ return is_null($value);
362
+ } // function IS_BLANK()
363
+
364
+
365
+ /**
366
+ * IS_ERR
367
+ *
368
+ * @param mixed $value Value to check
369
+ * @return boolean
370
+ */
371
+ public static function IS_ERR($value = '') {
372
+ $value = self::flattenSingleValue($value);
373
+
374
+ return self::IS_ERROR($value) && (!self::IS_NA($value));
375
+ } // function IS_ERR()
376
+
377
+
378
+ /**
379
+ * IS_ERROR
380
+ *
381
+ * @param mixed $value Value to check
382
+ * @return boolean
383
+ */
384
+ public static function IS_ERROR($value = '') {
385
+ $value = self::flattenSingleValue($value);
386
+
387
+ if (!is_string($value))
388
+ return false;
389
+ return in_array($value, array_values(self::$_errorCodes));
390
+ } // function IS_ERROR()
391
+
392
+
393
+ /**
394
+ * IS_NA
395
+ *
396
+ * @param mixed $value Value to check
397
+ * @return boolean
398
+ */
399
+ public static function IS_NA($value = '') {
400
+ $value = self::flattenSingleValue($value);
401
+
402
+ return ($value === self::NA());
403
+ } // function IS_NA()
404
+
405
+
406
+ /**
407
+ * IS_EVEN
408
+ *
409
+ * @param mixed $value Value to check
410
+ * @return boolean
411
+ */
412
+ public static function IS_EVEN($value = NULL) {
413
+ $value = self::flattenSingleValue($value);
414
+
415
+ if ($value === NULL)
416
+ return self::NAME();
417
+ if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
418
+ return self::VALUE();
419
+ return ($value % 2 == 0);
420
+ } // function IS_EVEN()
421
+
422
+
423
+ /**
424
+ * IS_ODD
425
+ *
426
+ * @param mixed $value Value to check
427
+ * @return boolean
428
+ */
429
+ public static function IS_ODD($value = NULL) {
430
+ $value = self::flattenSingleValue($value);
431
+
432
+ if ($value === NULL)
433
+ return self::NAME();
434
+ if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value))))
435
+ return self::VALUE();
436
+ return (abs($value) % 2 == 1);
437
+ } // function IS_ODD()
438
+
439
+
440
+ /**
441
+ * IS_NUMBER
442
+ *
443
+ * @param mixed $value Value to check
444
+ * @return boolean
445
+ */
446
+ public static function IS_NUMBER($value = NULL) {
447
+ $value = self::flattenSingleValue($value);
448
+
449
+ if (is_string($value)) {
450
+ return False;
451
+ }
452
+ return is_numeric($value);
453
+ } // function IS_NUMBER()
454
+
455
+
456
+ /**
457
+ * IS_LOGICAL
458
+ *
459
+ * @param mixed $value Value to check
460
+ * @return boolean
461
+ */
462
+ public static function IS_LOGICAL($value = NULL) {
463
+ $value = self::flattenSingleValue($value);
464
+
465
+ return is_bool($value);
466
+ } // function IS_LOGICAL()
467
+
468
+
469
+ /**
470
+ * IS_TEXT
471
+ *
472
+ * @param mixed $value Value to check
473
+ * @return boolean
474
+ */
475
+ public static function IS_TEXT($value = NULL) {
476
+ $value = self::flattenSingleValue($value);
477
+
478
+ return (is_string($value) && !self::IS_ERROR($value));
479
+ } // function IS_TEXT()
480
+
481
+
482
+ /**
483
+ * IS_NONTEXT
484
+ *
485
+ * @param mixed $value Value to check
486
+ * @return boolean
487
+ */
488
+ public static function IS_NONTEXT($value = NULL) {
489
+ return !self::IS_TEXT($value);
490
+ } // function IS_NONTEXT()
491
+
492
+
493
+ /**
494
+ * VERSION
495
+ *
496
+ * @return string Version information
497
+ */
498
+ public static function VERSION() {
499
+ return 'PHPExcel 1.8.1, 2015-04-30';
500
+ } // function VERSION()
501
+
502
+
503
+ /**
504
+ * N
505
+ *
506
+ * Returns a value converted to a number
507
+ *
508
+ * @param value The value you want converted
509
+ * @return number N converts values listed in the following table
510
+ * If value is or refers to N returns
511
+ * A number That number
512
+ * A date The serial number of that date
513
+ * TRUE 1
514
+ * FALSE 0
515
+ * An error value The error value
516
+ * Anything else 0
517
+ */
518
+ public static function N($value = NULL) {
519
+ while (is_array($value)) {
520
+ $value = array_shift($value);
521
+ }
522
+
523
+ switch (gettype($value)) {
524
+ case 'double' :
525
+ case 'float' :
526
+ case 'integer' :
527
+ return $value;
528
+ break;
529
+ case 'boolean' :
530
+ return (integer) $value;
531
+ break;
532
+ case 'string' :
533
+ // Errors
534
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
535
+ return $value;
536
+ }
537
+ break;
538
+ }
539
+ return 0;
540
+ } // function N()
541
+
542
+
543
+ /**
544
+ * TYPE
545
+ *
546
+ * Returns a number that identifies the type of a value
547
+ *
548
+ * @param value The value you want tested
549
+ * @return number N converts values listed in the following table
550
+ * If value is or refers to N returns
551
+ * A number 1
552
+ * Text 2
553
+ * Logical Value 4
554
+ * An error value 16
555
+ * Array or Matrix 64
556
+ */
557
+ public static function TYPE($value = NULL) {
558
+ $value = self::flattenArrayIndexed($value);
559
+ if (is_array($value) && (count($value) > 1)) {
560
+ $a = array_keys($value);
561
+ $a = array_pop($a);
562
+ // Range of cells is an error
563
+ if (self::isCellValue($a)) {
564
+ return 16;
565
+ // Test for Matrix
566
+ } elseif (self::isMatrixValue($a)) {
567
+ return 64;
568
+ }
569
+ } elseif(empty($value)) {
570
+ // Empty Cell
571
+ return 1;
572
+ }
573
+ $value = self::flattenSingleValue($value);
574
+
575
+ if (($value === NULL) || (is_float($value)) || (is_int($value))) {
576
+ return 1;
577
+ } elseif(is_bool($value)) {
578
+ return 4;
579
+ } elseif(is_array($value)) {
580
+ return 64;
581
+ } elseif(is_string($value)) {
582
+ // Errors
583
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
584
+ return 16;
585
+ }
586
+ return 2;
587
+ }
588
+ return 0;
589
+ } // function TYPE()
590
+
591
+
592
+ /**
593
+ * Convert a multi-dimensional array to a simple 1-dimensional array
594
+ *
595
+ * @param array $array Array to be flattened
596
+ * @return array Flattened array
597
+ */
598
+ public static function flattenArray($array) {
599
+ if (!is_array($array)) {
600
+ return (array) $array;
601
+ }
602
+
603
+ $arrayValues = array();
604
+ foreach ($array as $value) {
605
+ if (is_array($value)) {
606
+ foreach ($value as $val) {
607
+ if (is_array($val)) {
608
+ foreach ($val as $v) {
609
+ $arrayValues[] = $v;
610
+ }
611
+ } else {
612
+ $arrayValues[] = $val;
613
+ }
614
+ }
615
+ } else {
616
+ $arrayValues[] = $value;
617
+ }
618
+ }
619
+
620
+ return $arrayValues;
621
+ } // function flattenArray()
622
+
623
+
624
+ /**
625
+ * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
626
+ *
627
+ * @param array $array Array to be flattened
628
+ * @return array Flattened array
629
+ */
630
+ public static function flattenArrayIndexed($array) {
631
+ if (!is_array($array)) {
632
+ return (array) $array;
633
+ }
634
+
635
+ $arrayValues = array();
636
+ foreach ($array as $k1 => $value) {
637
+ if (is_array($value)) {
638
+ foreach ($value as $k2 => $val) {
639
+ if (is_array($val)) {
640
+ foreach ($val as $k3 => $v) {
641
+ $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
642
+ }
643
+ } else {
644
+ $arrayValues[$k1.'.'.$k2] = $val;
645
+ }
646
+ }
647
+ } else {
648
+ $arrayValues[$k1] = $value;
649
+ }
650
+ }
651
+
652
+ return $arrayValues;
653
+ } // function flattenArrayIndexed()
654
+
655
+
656
+ /**
657
+ * Convert an array to a single scalar value by extracting the first element
658
+ *
659
+ * @param mixed $value Array or scalar value
660
+ * @return mixed
661
+ */
662
+ public static function flattenSingleValue($value = '') {
663
+ while (is_array($value)) {
664
+ $value = array_pop($value);
665
+ }
666
+
667
+ return $value;
668
+ } // function flattenSingleValue()
669
+
670
+ } // class PHPExcel_Calculation_Functions
671
+
672
+
673
+ //
674
+ // There are a few mathematical functions that aren't available on all versions of PHP for all platforms
675
+ // These functions aren't available in Windows implementations of PHP prior to version 5.3.0
676
+ // So we test if they do exist for this version of PHP/operating platform; and if not we create them
677
+ //
678
+ if (!function_exists('acosh')) {
679
+ function acosh($x) {
680
+ return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
681
+ } // function acosh()
682
+ }
683
+
684
+ if (!function_exists('asinh')) {
685
+ function asinh($x) {
686
+ return log($x + sqrt(1 + $x * $x));
687
+ } // function asinh()
688
+ }
689
+
690
+ if (!function_exists('atanh')) {
691
+ function atanh($x) {
692
+ return (log(1 + $x) - log(1 - $x)) / 2;
693
+ } // function atanh()
694
+ }
695
+
696
+
697
+ //
698
+ // Strangely, PHP doesn't have a mb_str_replace multibyte function
699
+ // As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
700
+ //
701
+ if ((!function_exists('mb_str_replace')) &&
702
+ (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
703
+ function mb_str_replace($search, $replace, $subject) {
704
+ if(is_array($subject)) {
705
+ $ret = array();
706
+ foreach($subject as $key => $val) {
707
+ $ret[$key] = mb_str_replace($search, $replace, $val);
708
+ }
709
+ return $ret;
710
+ }
711
+
712
+ foreach((array) $search as $key => $s) {
713
+ if($s == '' && $s !== 0) {
714
+ continue;
715
+ }
716
+ $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
717
+ $pos = mb_strpos($subject, $s, 0, 'UTF-8');
718
+ while($pos !== false) {
719
+ $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
720
+ $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
721
+ }
722
+ }
723
+ return $subject;
724
+ }
725
+ }
libraries/PHPExcel/Calculation/Logical.php ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_Logical
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_Logical {
47
+
48
+ /**
49
+ * TRUE
50
+ *
51
+ * Returns the boolean TRUE.
52
+ *
53
+ * Excel Function:
54
+ * =TRUE()
55
+ *
56
+ * @access public
57
+ * @category Logical Functions
58
+ * @return boolean True
59
+ */
60
+ public static function TRUE() {
61
+ return TRUE;
62
+ } // function TRUE()
63
+
64
+
65
+ /**
66
+ * FALSE
67
+ *
68
+ * Returns the boolean FALSE.
69
+ *
70
+ * Excel Function:
71
+ * =FALSE()
72
+ *
73
+ * @access public
74
+ * @category Logical Functions
75
+ * @return boolean False
76
+ */
77
+ public static function FALSE() {
78
+ return FALSE;
79
+ } // function FALSE()
80
+
81
+
82
+ /**
83
+ * LOGICAL_AND
84
+ *
85
+ * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE.
86
+ *
87
+ * Excel Function:
88
+ * =AND(logical1[,logical2[, ...]])
89
+ *
90
+ * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
91
+ * or references that contain logical values.
92
+ *
93
+ * Boolean arguments are treated as True or False as appropriate
94
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
95
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
96
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
97
+ *
98
+ * @access public
99
+ * @category Logical Functions
100
+ * @param mixed $arg,... Data values
101
+ * @return boolean The logical AND of the arguments.
102
+ */
103
+ public static function LOGICAL_AND() {
104
+ // Return value
105
+ $returnValue = TRUE;
106
+
107
+ // Loop through the arguments
108
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
109
+ $argCount = -1;
110
+ foreach ($aArgs as $argCount => $arg) {
111
+ // Is it a boolean value?
112
+ if (is_bool($arg)) {
113
+ $returnValue = $returnValue && $arg;
114
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
115
+ $returnValue = $returnValue && ($arg != 0);
116
+ } elseif (is_string($arg)) {
117
+ $arg = strtoupper($arg);
118
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
119
+ $arg = TRUE;
120
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
121
+ $arg = FALSE;
122
+ } else {
123
+ return PHPExcel_Calculation_Functions::VALUE();
124
+ }
125
+ $returnValue = $returnValue && ($arg != 0);
126
+ }
127
+ }
128
+
129
+ // Return
130
+ if ($argCount < 0) {
131
+ return PHPExcel_Calculation_Functions::VALUE();
132
+ }
133
+ return $returnValue;
134
+ } // function LOGICAL_AND()
135
+
136
+
137
+ /**
138
+ * LOGICAL_OR
139
+ *
140
+ * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
141
+ *
142
+ * Excel Function:
143
+ * =OR(logical1[,logical2[, ...]])
144
+ *
145
+ * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
146
+ * or references that contain logical values.
147
+ *
148
+ * Boolean arguments are treated as True or False as appropriate
149
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
150
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
151
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
152
+ *
153
+ * @access public
154
+ * @category Logical Functions
155
+ * @param mixed $arg,... Data values
156
+ * @return boolean The logical OR of the arguments.
157
+ */
158
+ public static function LOGICAL_OR() {
159
+ // Return value
160
+ $returnValue = FALSE;
161
+
162
+ // Loop through the arguments
163
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
164
+ $argCount = -1;
165
+ foreach ($aArgs as $argCount => $arg) {
166
+ // Is it a boolean value?
167
+ if (is_bool($arg)) {
168
+ $returnValue = $returnValue || $arg;
169
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
170
+ $returnValue = $returnValue || ($arg != 0);
171
+ } elseif (is_string($arg)) {
172
+ $arg = strtoupper($arg);
173
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
174
+ $arg = TRUE;
175
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
176
+ $arg = FALSE;
177
+ } else {
178
+ return PHPExcel_Calculation_Functions::VALUE();
179
+ }
180
+ $returnValue = $returnValue || ($arg != 0);
181
+ }
182
+ }
183
+
184
+ // Return
185
+ if ($argCount < 0) {
186
+ return PHPExcel_Calculation_Functions::VALUE();
187
+ }
188
+ return $returnValue;
189
+ } // function LOGICAL_OR()
190
+
191
+
192
+ /**
193
+ * NOT
194
+ *
195
+ * Returns the boolean inverse of the argument.
196
+ *
197
+ * Excel Function:
198
+ * =NOT(logical)
199
+ *
200
+ * The argument must evaluate to a logical value such as TRUE or FALSE
201
+ *
202
+ * Boolean arguments are treated as True or False as appropriate
203
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
204
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
205
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
206
+ *
207
+ * @access public
208
+ * @category Logical Functions
209
+ * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
210
+ * @return boolean The boolean inverse of the argument.
211
+ */
212
+ public static function NOT($logical=FALSE) {
213
+ $logical = PHPExcel_Calculation_Functions::flattenSingleValue($logical);
214
+ if (is_string($logical)) {
215
+ $logical = strtoupper($logical);
216
+ if (($logical == 'TRUE') || ($logical == PHPExcel_Calculation::getTRUE())) {
217
+ return FALSE;
218
+ } elseif (($logical == 'FALSE') || ($logical == PHPExcel_Calculation::getFALSE())) {
219
+ return TRUE;
220
+ } else {
221
+ return PHPExcel_Calculation_Functions::VALUE();
222
+ }
223
+ }
224
+
225
+ return !$logical;
226
+ } // function NOT()
227
+
228
+ /**
229
+ * STATEMENT_IF
230
+ *
231
+ * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
232
+ *
233
+ * Excel Function:
234
+ * =IF(condition[,returnIfTrue[,returnIfFalse]])
235
+ *
236
+ * Condition is any value or expression that can be evaluated to TRUE or FALSE.
237
+ * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
238
+ * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
239
+ * This argument can use any comparison calculation operator.
240
+ * ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
241
+ * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
242
+ * then the IF function returns the text "Within budget"
243
+ * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
244
+ * the logical value TRUE for this argument.
245
+ * ReturnIfTrue can be another formula.
246
+ * ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
247
+ * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
248
+ * then the IF function returns the text "Over budget".
249
+ * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
250
+ * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
251
+ * ReturnIfFalse can be another formula.
252
+ *
253
+ * @access public
254
+ * @category Logical Functions
255
+ * @param mixed $condition Condition to evaluate
256
+ * @param mixed $returnIfTrue Value to return when condition is true
257
+ * @param mixed $returnIfFalse Optional value to return when condition is false
258
+ * @return mixed The value of returnIfTrue or returnIfFalse determined by condition
259
+ */
260
+ public static function STATEMENT_IF($condition = TRUE, $returnIfTrue = 0, $returnIfFalse = FALSE) {
261
+ $condition = (is_null($condition)) ? TRUE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition);
262
+ $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue);
263
+ $returnIfFalse = (is_null($returnIfFalse)) ? FALSE : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse);
264
+
265
+ return ($condition) ? $returnIfTrue : $returnIfFalse;
266
+ } // function STATEMENT_IF()
267
+
268
+
269
+ /**
270
+ * IFERROR
271
+ *
272
+ * Excel Function:
273
+ * =IFERROR(testValue,errorpart)
274
+ *
275
+ * @access public
276
+ * @category Logical Functions
277
+ * @param mixed $testValue Value to check, is also the value returned when no error
278
+ * @param mixed $errorpart Value to return when testValue is an error condition
279
+ * @return mixed The value of errorpart or testValue determined by error condition
280
+ */
281
+ public static function IFERROR($testValue = '', $errorpart = '') {
282
+ $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue);
283
+ $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart);
284
+
285
+ return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
286
+ } // function IFERROR()
287
+
288
+ } // class PHPExcel_Calculation_Logical
libraries/PHPExcel/Calculation/LookupRef.php ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_LookupRef
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_LookupRef {
47
+
48
+
49
+ /**
50
+ * CELL_ADDRESS
51
+ *
52
+ * Creates a cell address as text, given specified row and column numbers.
53
+ *
54
+ * Excel Function:
55
+ * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
56
+ *
57
+ * @param row Row number to use in the cell reference
58
+ * @param column Column number to use in the cell reference
59
+ * @param relativity Flag indicating the type of reference to return
60
+ * 1 or omitted Absolute
61
+ * 2 Absolute row; relative column
62
+ * 3 Relative row; absolute column
63
+ * 4 Relative
64
+ * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
65
+ * TRUE or omitted CELL_ADDRESS returns an A1-style reference
66
+ * FALSE CELL_ADDRESS returns an R1C1-style reference
67
+ * @param sheetText Optional Name of worksheet to use
68
+ * @return string
69
+ */
70
+ public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
71
+ $row = PHPExcel_Calculation_Functions::flattenSingleValue($row);
72
+ $column = PHPExcel_Calculation_Functions::flattenSingleValue($column);
73
+ $relativity = PHPExcel_Calculation_Functions::flattenSingleValue($relativity);
74
+ $sheetText = PHPExcel_Calculation_Functions::flattenSingleValue($sheetText);
75
+
76
+ if (($row < 1) || ($column < 1)) {
77
+ return PHPExcel_Calculation_Functions::VALUE();
78
+ }
79
+
80
+ if ($sheetText > '') {
81
+ if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
82
+ $sheetText .='!';
83
+ }
84
+ if ((!is_bool($referenceStyle)) || $referenceStyle) {
85
+ $rowRelative = $columnRelative = '$';
86
+ $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
87
+ if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
88
+ if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
89
+ return $sheetText.$columnRelative.$column.$rowRelative.$row;
90
+ } else {
91
+ if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
92
+ if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
93
+ return $sheetText.'R'.$row.'C'.$column;
94
+ }
95
+ } // function CELL_ADDRESS()
96
+
97
+
98
+ /**
99
+ * COLUMN
100
+ *
101
+ * Returns the column number of the given cell reference
102
+ * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
103
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
104
+ * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
105
+ *
106
+ * Excel Function:
107
+ * =COLUMN([cellAddress])
108
+ *
109
+ * @param cellAddress A reference to a range of cells for which you want the column numbers
110
+ * @return integer or array of integer
111
+ */
112
+ public static function COLUMN($cellAddress=Null) {
113
+ if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
114
+
115
+ if (is_array($cellAddress)) {
116
+ foreach($cellAddress as $columnKey => $value) {
117
+ $columnKey = preg_replace('/[^a-z]/i','',$columnKey);
118
+ return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
119
+ }
120
+ } else {
121
+ if (strpos($cellAddress,'!') !== false) {
122
+ list($sheet,$cellAddress) = explode('!',$cellAddress);
123
+ }
124
+ if (strpos($cellAddress,':') !== false) {
125
+ list($startAddress,$endAddress) = explode(':',$cellAddress);
126
+ $startAddress = preg_replace('/[^a-z]/i','',$startAddress);
127
+ $endAddress = preg_replace('/[^a-z]/i','',$endAddress);
128
+ $returnValue = array();
129
+ do {
130
+ $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
131
+ } while ($startAddress++ != $endAddress);
132
+ return $returnValue;
133
+ } else {
134
+ $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
135
+ return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
136
+ }
137
+ }
138
+ } // function COLUMN()
139
+
140
+
141
+ /**
142
+ * COLUMNS
143
+ *
144
+ * Returns the number of columns in an array or reference.
145
+ *
146
+ * Excel Function:
147
+ * =COLUMNS(cellAddress)
148
+ *
149
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
150
+ * @return integer The number of columns in cellAddress
151
+ */
152
+ public static function COLUMNS($cellAddress=Null) {
153
+ if (is_null($cellAddress) || $cellAddress === '') {
154
+ return 1;
155
+ } elseif (!is_array($cellAddress)) {
156
+ return PHPExcel_Calculation_Functions::VALUE();
157
+ }
158
+
159
+ $x = array_keys($cellAddress);
160
+ $x = array_shift($x);
161
+ $isMatrix = (is_numeric($x));
162
+ list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
163
+
164
+ if ($isMatrix) {
165
+ return $rows;
166
+ } else {
167
+ return $columns;
168
+ }
169
+ } // function COLUMNS()
170
+
171
+
172
+ /**
173
+ * ROW
174
+ *
175
+ * Returns the row number of the given cell reference
176
+ * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
177
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
178
+ * reference of the cell in which the ROW function appears; otherwise this function returns 0.
179
+ *
180
+ * Excel Function:
181
+ * =ROW([cellAddress])
182
+ *
183
+ * @param cellAddress A reference to a range of cells for which you want the row numbers
184
+ * @return integer or array of integer
185
+ */
186
+ public static function ROW($cellAddress=Null) {
187
+ if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
188
+
189
+ if (is_array($cellAddress)) {
190
+ foreach($cellAddress as $columnKey => $rowValue) {
191
+ foreach($rowValue as $rowKey => $cellValue) {
192
+ return (integer) preg_replace('/[^0-9]/i','',$rowKey);
193
+ }
194
+ }
195
+ } else {
196
+ if (strpos($cellAddress,'!') !== false) {
197
+ list($sheet,$cellAddress) = explode('!',$cellAddress);
198
+ }
199
+ if (strpos($cellAddress,':') !== false) {
200
+ list($startAddress,$endAddress) = explode(':',$cellAddress);
201
+ $startAddress = preg_replace('/[^0-9]/','',$startAddress);
202
+ $endAddress = preg_replace('/[^0-9]/','',$endAddress);
203
+ $returnValue = array();
204
+ do {
205
+ $returnValue[][] = (integer) $startAddress;
206
+ } while ($startAddress++ != $endAddress);
207
+ return $returnValue;
208
+ } else {
209
+ list($cellAddress) = explode(':',$cellAddress);
210
+ return (integer) preg_replace('/[^0-9]/','',$cellAddress);
211
+ }
212
+ }
213
+ } // function ROW()
214
+
215
+
216
+ /**
217
+ * ROWS
218
+ *
219
+ * Returns the number of rows in an array or reference.
220
+ *
221
+ * Excel Function:
222
+ * =ROWS(cellAddress)
223
+ *
224
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
225
+ * @return integer The number of rows in cellAddress
226
+ */
227
+ public static function ROWS($cellAddress=Null) {
228
+ if (is_null($cellAddress) || $cellAddress === '') {
229
+ return 1;
230
+ } elseif (!is_array($cellAddress)) {
231
+ return PHPExcel_Calculation_Functions::VALUE();
232
+ }
233
+
234
+ $i = array_keys($cellAddress);
235
+ $isMatrix = (is_numeric(array_shift($i)));
236
+ list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
237
+
238
+ if ($isMatrix) {
239
+ return $columns;
240
+ } else {
241
+ return $rows;
242
+ }
243
+ } // function ROWS()
244
+
245
+
246
+ /**
247
+ * HYPERLINK
248
+ *
249
+ * Excel Function:
250
+ * =HYPERLINK(linkURL,displayName)
251
+ *
252
+ * @access public
253
+ * @category Logical Functions
254
+ * @param string $linkURL Value to check, is also the value returned when no error
255
+ * @param string $displayName Value to return when testValue is an error condition
256
+ * @param PHPExcel_Cell $pCell The cell to set the hyperlink in
257
+ * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
258
+ */
259
+ public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null) {
260
+ $args = func_get_args();
261
+ $pCell = array_pop($args);
262
+
263
+ $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
264
+ $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
265
+
266
+ if ((!is_object($pCell)) || (trim($linkURL) == '')) {
267
+ return PHPExcel_Calculation_Functions::REF();
268
+ }
269
+
270
+ if ((is_object($displayName)) || trim($displayName) == '') {
271
+ $displayName = $linkURL;
272
+ }
273
+
274
+ $pCell->getHyperlink()->setUrl($linkURL);
275
+
276
+ return $displayName;
277
+ } // function HYPERLINK()
278
+
279
+
280
+ /**
281
+ * INDIRECT
282
+ *
283
+ * Returns the reference specified by a text string.
284
+ * References are immediately evaluated to display their contents.
285
+ *
286
+ * Excel Function:
287
+ * =INDIRECT(cellAddress)
288
+ *
289
+ * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
290
+ *
291
+ * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
292
+ * @param PHPExcel_Cell $pCell The current cell (containing this formula)
293
+ * @return mixed The cells referenced by cellAddress
294
+ *
295
+ * @todo Support for the optional a1 parameter introduced in Excel 2010
296
+ *
297
+ */
298
+ public static function INDIRECT($cellAddress = NULL, PHPExcel_Cell $pCell = NULL) {
299
+ $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
300
+ if (is_null($cellAddress) || $cellAddress === '') {
301
+ return PHPExcel_Calculation_Functions::REF();
302
+ }
303
+
304
+ $cellAddress1 = $cellAddress;
305
+ $cellAddress2 = NULL;
306
+ if (strpos($cellAddress,':') !== false) {
307
+ list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
308
+ }
309
+
310
+ if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
311
+ ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
312
+ if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
313
+ return PHPExcel_Calculation_Functions::REF();
314
+ }
315
+
316
+ if (strpos($cellAddress,'!') !== FALSE) {
317
+ list($sheetName, $cellAddress) = explode('!',$cellAddress);
318
+ $sheetName = trim($sheetName, "'");
319
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
320
+ } else {
321
+ $pSheet = $pCell->getWorksheet();
322
+ }
323
+
324
+ return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, FALSE);
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()->extractCellRange($cellAddress, $pSheet, FALSE);
336
+ } // function INDIRECT()
337
+
338
+
339
+ /**
340
+ * OFFSET
341
+ *
342
+ * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
343
+ * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
344
+ * the number of columns to be returned.
345
+ *
346
+ * Excel Function:
347
+ * =OFFSET(cellAddress, rows, cols, [height], [width])
348
+ *
349
+ * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
350
+ * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
351
+ * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
352
+ * Using 5 as the rows argument specifies that the upper-left cell in the reference is
353
+ * five rows below reference. Rows can be positive (which means below the starting reference)
354
+ * or negative (which means above the starting reference).
355
+ * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
356
+ * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
357
+ * reference is five columns to the right of reference. Cols can be positive (which means
358
+ * to the right of the starting reference) or negative (which means to the left of the
359
+ * starting reference).
360
+ * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
361
+ * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
362
+ * @return string A reference to a cell or range of cells
363
+ */
364
+ public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) {
365
+ $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows);
366
+ $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns);
367
+ $height = PHPExcel_Calculation_Functions::flattenSingleValue($height);
368
+ $width = PHPExcel_Calculation_Functions::flattenSingleValue($width);
369
+ if ($cellAddress == Null) {
370
+ return 0;
371
+ }
372
+
373
+ $args = func_get_args();
374
+ $pCell = array_pop($args);
375
+ if (!is_object($pCell)) {
376
+ return PHPExcel_Calculation_Functions::REF();
377
+ }
378
+
379
+ $sheetName = NULL;
380
+ if (strpos($cellAddress,"!")) {
381
+ list($sheetName,$cellAddress) = explode("!",$cellAddress);
382
+ $sheetName = trim($sheetName, "'");
383
+ }
384
+ if (strpos($cellAddress,":")) {
385
+ list($startCell,$endCell) = explode(":",$cellAddress);
386
+ } else {
387
+ $startCell = $endCell = $cellAddress;
388
+ }
389
+ list($startCellColumn,$startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
390
+ list($endCellColumn,$endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
391
+
392
+ $startCellRow += $rows;
393
+ $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
394
+ $startCellColumn += $columns;
395
+
396
+ if (($startCellRow <= 0) || ($startCellColumn < 0)) {
397
+ return PHPExcel_Calculation_Functions::REF();
398
+ }
399
+ $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
400
+ if (($width != null) && (!is_object($width))) {
401
+ $endCellColumn = $startCellColumn + $width - 1;
402
+ } else {
403
+ $endCellColumn += $columns;
404
+ }
405
+ $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
406
+
407
+ if (($height != null) && (!is_object($height))) {
408
+ $endCellRow = $startCellRow + $height - 1;
409
+ } else {
410
+ $endCellRow += $rows;
411
+ }
412
+
413
+ if (($endCellRow <= 0) || ($endCellColumn < 0)) {
414
+ return PHPExcel_Calculation_Functions::REF();
415
+ }
416
+ $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
417
+
418
+ $cellAddress = $startCellColumn.$startCellRow;
419
+ if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
420
+ $cellAddress .= ':'.$endCellColumn.$endCellRow;
421
+ }
422
+
423
+ if ($sheetName !== NULL) {
424
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
425
+ } else {
426
+ $pSheet = $pCell->getWorksheet();
427
+ }
428
+
429
+ return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
430
+ } // function OFFSET()
431
+
432
+
433
+ /**
434
+ * CHOOSE
435
+ *
436
+ * Uses lookup_value to return a value from the list of value arguments.
437
+ * Use CHOOSE to select one of up to 254 values based on the lookup_value.
438
+ *
439
+ * Excel Function:
440
+ * =CHOOSE(index_num, value1, [value2], ...)
441
+ *
442
+ * @param index_num Specifies which value argument is selected.
443
+ * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
444
+ * between 1 and 254.
445
+ * @param value1... Value1 is required, subsequent values are optional.
446
+ * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
447
+ * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
448
+ * text.
449
+ * @return mixed The selected value
450
+ */
451
+ public static function CHOOSE() {
452
+ $chooseArgs = func_get_args();
453
+ $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
454
+ $entryCount = count($chooseArgs) - 1;
455
+
456
+ if(is_array($chosenEntry)) {
457
+ $chosenEntry = array_shift($chosenEntry);
458
+ }
459
+ if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
460
+ --$chosenEntry;
461
+ } else {
462
+ return PHPExcel_Calculation_Functions::VALUE();
463
+ }
464
+ $chosenEntry = floor($chosenEntry);
465
+ if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
466
+ return PHPExcel_Calculation_Functions::VALUE();
467
+ }
468
+
469
+ if (is_array($chooseArgs[$chosenEntry])) {
470
+ return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
471
+ } else {
472
+ return $chooseArgs[$chosenEntry];
473
+ }
474
+ } // function CHOOSE()
475
+
476
+
477
+ /**
478
+ * MATCH
479
+ *
480
+ * The MATCH function searches for a specified item in a range of cells
481
+ *
482
+ * Excel Function:
483
+ * =MATCH(lookup_value, lookup_array, [match_type])
484
+ *
485
+ * @param lookup_value The value that you want to match in lookup_array
486
+ * @param lookup_array The range of cells being searched
487
+ * @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.
488
+ * @return integer The relative position of the found item
489
+ */
490
+ public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
491
+ $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
492
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
493
+ $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
494
+ // MATCH is not case sensitive
495
+ $lookup_value = strtolower($lookup_value);
496
+
497
+ // lookup_value type has to be number, text, or logical values
498
+ if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
499
+ return PHPExcel_Calculation_Functions::NA();
500
+ }
501
+
502
+ // match_type is 0, 1 or -1
503
+ if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
504
+ return PHPExcel_Calculation_Functions::NA();
505
+ }
506
+
507
+ // lookup_array should not be empty
508
+ $lookupArraySize = count($lookup_array);
509
+ if ($lookupArraySize <= 0) {
510
+ return PHPExcel_Calculation_Functions::NA();
511
+ }
512
+
513
+ // lookup_array should contain only number, text, or logical values, or empty (null) cells
514
+ foreach($lookup_array as $i => $lookupArrayValue) {
515
+ // check the type of the value
516
+ if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
517
+ (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
518
+ return PHPExcel_Calculation_Functions::NA();
519
+ }
520
+ // convert strings to lowercase for case-insensitive testing
521
+ if (is_string($lookupArrayValue)) {
522
+ $lookup_array[$i] = strtolower($lookupArrayValue);
523
+ }
524
+ if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
525
+ $lookup_array = array_slice($lookup_array,0,$i-1);
526
+ }
527
+ }
528
+
529
+ // if match_type is 1 or -1, the list has to be ordered
530
+ if ($match_type == 1) {
531
+ asort($lookup_array);
532
+ $keySet = array_keys($lookup_array);
533
+ } elseif($match_type == -1) {
534
+ arsort($lookup_array);
535
+ $keySet = array_keys($lookup_array);
536
+ }
537
+
538
+ // **
539
+ // find the match
540
+ // **
541
+ // loop on the cells
542
+ // var_dump($lookup_array);
543
+ // echo '<br />';
544
+ foreach($lookup_array as $i => $lookupArrayValue) {
545
+ if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
546
+ // exact match
547
+ return ++$i;
548
+ } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
549
+ // echo '$i = '.$i.' => ';
550
+ // var_dump($lookupArrayValue);
551
+ // echo '<br />';
552
+ // echo 'Keyset = ';
553
+ // var_dump($keySet);
554
+ // echo '<br />';
555
+ $i = array_search($i,$keySet);
556
+ // echo '$i='.$i.'<br />';
557
+ // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
558
+ if ($i < 1){
559
+ // 1st cell was allready smaller than the lookup_value
560
+ break;
561
+ } else {
562
+ // the previous cell was the match
563
+ return $keySet[$i-1]+1;
564
+ }
565
+ } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
566
+ // echo '$i = '.$i.' => ';
567
+ // var_dump($lookupArrayValue);
568
+ // echo '<br />';
569
+ // echo 'Keyset = ';
570
+ // var_dump($keySet);
571
+ // echo '<br />';
572
+ $i = array_search($i,$keySet);
573
+ // echo '$i='.$i.'<br />';
574
+ // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
575
+ if ($i < 1){
576
+ // 1st cell was allready bigger than the lookup_value
577
+ break;
578
+ } else {
579
+ // the previous cell was the match
580
+ return $keySet[$i-1]+1;
581
+ }
582
+ }
583
+ }
584
+
585
+ // unsuccessful in finding a match, return #N/A error value
586
+ return PHPExcel_Calculation_Functions::NA();
587
+ } // function MATCH()
588
+
589
+
590
+ /**
591
+ * INDEX
592
+ *
593
+ * Uses an index to choose a value from a reference or array
594
+ *
595
+ * Excel Function:
596
+ * =INDEX(range_array, row_num, [column_num])
597
+ *
598
+ * @param range_array A range of cells or an array constant
599
+ * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
600
+ * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
601
+ * @return mixed the value of a specified cell or array of cells
602
+ */
603
+ public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
604
+
605
+ if (($rowNum < 0) || ($columnNum < 0)) {
606
+ return PHPExcel_Calculation_Functions::VALUE();
607
+ }
608
+
609
+ if (!is_array($arrayValues)) {
610
+ return PHPExcel_Calculation_Functions::REF();
611
+ }
612
+
613
+ $rowKeys = array_keys($arrayValues);
614
+ $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
615
+
616
+ if ($columnNum > count($columnKeys)) {
617
+ return PHPExcel_Calculation_Functions::VALUE();
618
+ } elseif ($columnNum == 0) {
619
+ if ($rowNum == 0) {
620
+ return $arrayValues;
621
+ }
622
+ $rowNum = $rowKeys[--$rowNum];
623
+ $returnArray = array();
624
+ foreach($arrayValues as $arrayColumn) {
625
+ if (is_array($arrayColumn)) {
626
+ if (isset($arrayColumn[$rowNum])) {
627
+ $returnArray[] = $arrayColumn[$rowNum];
628
+ } else {
629
+ return $arrayValues[$rowNum];
630
+ }
631
+ } else {
632
+ return $arrayValues[$rowNum];
633
+ }
634
+ }
635
+ return $returnArray;
636
+ }
637
+ $columnNum = $columnKeys[--$columnNum];
638
+ if ($rowNum > count($rowKeys)) {
639
+ return PHPExcel_Calculation_Functions::VALUE();
640
+ } elseif ($rowNum == 0) {
641
+ return $arrayValues[$columnNum];
642
+ }
643
+ $rowNum = $rowKeys[--$rowNum];
644
+
645
+ return $arrayValues[$rowNum][$columnNum];
646
+ } // function INDEX()
647
+
648
+
649
+ /**
650
+ * TRANSPOSE
651
+ *
652
+ * @param array $matrixData A matrix of values
653
+ * @return array
654
+ *
655
+ * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
656
+ */
657
+ public static function TRANSPOSE($matrixData) {
658
+ $returnMatrix = array();
659
+ if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
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
+ } // function TRANSPOSE()
672
+
673
+
674
+ private static function _vlookupSort($a,$b) {
675
+ $f = array_keys($a);
676
+ $firstColumn = array_shift($f);
677
+ if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
678
+ return 0;
679
+ }
680
+ return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
681
+ } // function _vlookupSort()
682
+
683
+
684
+ /**
685
+ * VLOOKUP
686
+ * 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.
687
+ * @param lookup_value The value that you want to match in lookup_array
688
+ * @param lookup_array The range of cells being searched
689
+ * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
690
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
691
+ * @return mixed The value of the found cell
692
+ */
693
+ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
694
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
695
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
696
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
697
+
698
+ // index_number must be greater than or equal to 1
699
+ if ($index_number < 1) {
700
+ return PHPExcel_Calculation_Functions::VALUE();
701
+ }
702
+
703
+ // index_number must be less than or equal to the number of columns in lookup_array
704
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
705
+ return PHPExcel_Calculation_Functions::REF();
706
+ } else {
707
+ $f = array_keys($lookup_array);
708
+ $firstRow = array_pop($f);
709
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
710
+ return PHPExcel_Calculation_Functions::REF();
711
+ } else {
712
+ $columnKeys = array_keys($lookup_array[$firstRow]);
713
+ $returnColumn = $columnKeys[--$index_number];
714
+ $firstColumn = array_shift($columnKeys);
715
+ }
716
+ }
717
+
718
+ if (!$not_exact_match) {
719
+ uasort($lookup_array,array('self','_vlookupSort'));
720
+ }
721
+
722
+ $rowNumber = $rowValue = False;
723
+ foreach($lookup_array as $rowKey => $rowData) {
724
+ if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
725
+ (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
726
+ break;
727
+ }
728
+ $rowNumber = $rowKey;
729
+ $rowValue = $rowData[$firstColumn];
730
+ }
731
+
732
+ if ($rowNumber !== false) {
733
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
734
+ // if an exact match is required, we have what we need to return an appropriate response
735
+ return PHPExcel_Calculation_Functions::NA();
736
+ } else {
737
+ // otherwise return the appropriate value
738
+ return $lookup_array[$rowNumber][$returnColumn];
739
+ }
740
+ }
741
+
742
+ return PHPExcel_Calculation_Functions::NA();
743
+ } // function VLOOKUP()
744
+
745
+
746
+ /**
747
+ * HLOOKUP
748
+ * 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.
749
+ * @param lookup_value The value that you want to match in lookup_array
750
+ * @param lookup_array The range of cells being searched
751
+ * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1.
752
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
753
+ * @return mixed The value of the found cell
754
+ */
755
+ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
756
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
757
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
758
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
759
+
760
+ // index_number must be greater than or equal to 1
761
+ if ($index_number < 1) {
762
+ return PHPExcel_Calculation_Functions::VALUE();
763
+ }
764
+
765
+ // index_number must be less than or equal to the number of columns in lookup_array
766
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
767
+ return PHPExcel_Calculation_Functions::REF();
768
+ } else {
769
+ $f = array_keys($lookup_array);
770
+ $firstRow = array_pop($f);
771
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
772
+ return PHPExcel_Calculation_Functions::REF();
773
+ } else {
774
+ $columnKeys = array_keys($lookup_array[$firstRow]);
775
+ $firstkey = $f[0] - 1;
776
+ $returnColumn = $firstkey + $index_number;
777
+ $firstColumn = array_shift($f);
778
+ }
779
+ }
780
+
781
+ if (!$not_exact_match) {
782
+ $firstRowH = asort($lookup_array[$firstColumn]);
783
+ }
784
+
785
+ $rowNumber = $rowValue = False;
786
+ foreach($lookup_array[$firstColumn] as $rowKey => $rowData) {
787
+ if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
788
+ (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
789
+ break;
790
+ }
791
+ $rowNumber = $rowKey;
792
+ $rowValue = $rowData;
793
+ }
794
+
795
+ if ($rowNumber !== false) {
796
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
797
+ // if an exact match is required, we have what we need to return an appropriate response
798
+ return PHPExcel_Calculation_Functions::NA();
799
+ } else {
800
+ // otherwise return the appropriate value
801
+ return $lookup_array[$returnColumn][$rowNumber];
802
+ }
803
+ }
804
+
805
+ return PHPExcel_Calculation_Functions::NA();
806
+ } // function HLOOKUP()
807
+
808
+
809
+ /**
810
+ * LOOKUP
811
+ * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
812
+ * @param lookup_value The value that you want to match in lookup_array
813
+ * @param lookup_vector The range of cells being searched
814
+ * @param result_vector The column from which the matching value must be returned
815
+ * @return mixed The value of the found cell
816
+ */
817
+ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
818
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
819
+
820
+ if (!is_array($lookup_vector)) {
821
+ return PHPExcel_Calculation_Functions::NA();
822
+ }
823
+ $lookupRows = count($lookup_vector);
824
+ $l = array_keys($lookup_vector);
825
+ $l = array_shift($l);
826
+ $lookupColumns = count($lookup_vector[$l]);
827
+ if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
828
+ $lookup_vector = self::TRANSPOSE($lookup_vector);
829
+ $lookupRows = count($lookup_vector);
830
+ $l = array_keys($lookup_vector);
831
+ $lookupColumns = count($lookup_vector[array_shift($l)]);
832
+ }
833
+
834
+ if (is_null($result_vector)) {
835
+ $result_vector = $lookup_vector;
836
+ }
837
+ $resultRows = count($result_vector);
838
+ $l = array_keys($result_vector);
839
+ $l = array_shift($l);
840
+ $resultColumns = count($result_vector[$l]);
841
+ if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
842
+ $result_vector = self::TRANSPOSE($result_vector);
843
+ $resultRows = count($result_vector);
844
+ $r = array_keys($result_vector);
845
+ $resultColumns = count($result_vector[array_shift($r)]);
846
+ }
847
+
848
+ if ($lookupRows == 2) {
849
+ $result_vector = array_pop($lookup_vector);
850
+ $lookup_vector = array_shift($lookup_vector);
851
+ }
852
+ if ($lookupColumns != 2) {
853
+ foreach($lookup_vector as &$value) {
854
+ if (is_array($value)) {
855
+ $k = array_keys($value);
856
+ $key1 = $key2 = array_shift($k);
857
+ $key2++;
858
+ $dataValue1 = $value[$key1];
859
+ } else {
860
+ $key1 = 0;
861
+ $key2 = 1;
862
+ $dataValue1 = $value;
863
+ }
864
+ $dataValue2 = array_shift($result_vector);
865
+ if (is_array($dataValue2)) {
866
+ $dataValue2 = array_shift($dataValue2);
867
+ }
868
+ $value = array($key1 => $dataValue1, $key2 => $dataValue2);
869
+ }
870
+ unset($value);
871
+ }
872
+
873
+ return self::VLOOKUP($lookup_value,$lookup_vector,2);
874
+ } // function LOOKUP()
875
+
876
+ } // class PHPExcel_Calculation_LookupRef
libraries/PHPExcel/Calculation/MathTrig.php ADDED
@@ -0,0 +1,1376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_MathTrig
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_MathTrig {
47
+
48
+ //
49
+ // Private method to return an array of the factors of the input value
50
+ //
51
+ private static function _factors($value) {
52
+ $startVal = floor(sqrt($value));
53
+
54
+ $factorArray = array();
55
+ for ($i = $startVal; $i > 1; --$i) {
56
+ if (($value % $i) == 0) {
57
+ $factorArray = array_merge($factorArray,self::_factors($value / $i));
58
+ $factorArray = array_merge($factorArray,self::_factors($i));
59
+ if ($i <= sqrt($value)) {
60
+ break;
61
+ }
62
+ }
63
+ }
64
+ if (!empty($factorArray)) {
65
+ rsort($factorArray);
66
+ return $factorArray;
67
+ } else {
68
+ return array((integer) $value);
69
+ }
70
+ } // function _factors()
71
+
72
+
73
+ private static function _romanCut($num, $n) {
74
+ return ($num - ($num % $n ) ) / $n;
75
+ } // function _romanCut()
76
+
77
+
78
+ /**
79
+ * ATAN2
80
+ *
81
+ * This function calculates the arc tangent of the two variables x and y. It is similar to
82
+ * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
83
+ * to determine the quadrant of the result.
84
+ * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
85
+ * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
86
+ * -pi and pi, excluding -pi.
87
+ *
88
+ * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
89
+ * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
90
+ *
91
+ * Excel Function:
92
+ * ATAN2(xCoordinate,yCoordinate)
93
+ *
94
+ * @access public
95
+ * @category Mathematical and Trigonometric Functions
96
+ * @param float $xCoordinate The x-coordinate of the point.
97
+ * @param float $yCoordinate The y-coordinate of the point.
98
+ * @return float The inverse tangent of the specified x- and y-coordinates.
99
+ */
100
+ public static function ATAN2($xCoordinate = NULL, $yCoordinate = NULL) {
101
+ $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate);
102
+ $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate);
103
+
104
+ $xCoordinate = ($xCoordinate !== NULL) ? $xCoordinate : 0.0;
105
+ $yCoordinate = ($yCoordinate !== NULL) ? $yCoordinate : 0.0;
106
+
107
+ if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
108
+ ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
109
+ $xCoordinate = (float) $xCoordinate;
110
+ $yCoordinate = (float) $yCoordinate;
111
+
112
+ if (($xCoordinate == 0) && ($yCoordinate == 0)) {
113
+ return PHPExcel_Calculation_Functions::DIV0();
114
+ }
115
+
116
+ return atan2($yCoordinate, $xCoordinate);
117
+ }
118
+ return PHPExcel_Calculation_Functions::VALUE();
119
+ } // function ATAN2()
120
+
121
+
122
+ /**
123
+ * CEILING
124
+ *
125
+ * Returns number rounded up, away from zero, to the nearest multiple of significance.
126
+ * For example, if you want to avoid using pennies in your prices and your product is
127
+ * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
128
+ * nearest nickel.
129
+ *
130
+ * Excel Function:
131
+ * CEILING(number[,significance])
132
+ *
133
+ * @access public
134
+ * @category Mathematical and Trigonometric Functions
135
+ * @param float $number The number you want to round.
136
+ * @param float $significance The multiple to which you want to round.
137
+ * @return float Rounded Number
138
+ */
139
+ public static function CEILING($number, $significance = NULL) {
140
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
141
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
142
+
143
+ if ((is_null($significance)) &&
144
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
145
+ $significance = $number/abs($number);
146
+ }
147
+
148
+ if ((is_numeric($number)) && (is_numeric($significance))) {
149
+ if (($number == 0.0 ) || ($significance == 0.0)) {
150
+ return 0.0;
151
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
152
+ return ceil($number / $significance) * $significance;
153
+ } else {
154
+ return PHPExcel_Calculation_Functions::NaN();
155
+ }
156
+ }
157
+ return PHPExcel_Calculation_Functions::VALUE();
158
+ } // function CEILING()
159
+
160
+
161
+ /**
162
+ * COMBIN
163
+ *
164
+ * Returns the number of combinations for a given number of items. Use COMBIN to
165
+ * determine the total possible number of groups for a given number of items.
166
+ *
167
+ * Excel Function:
168
+ * COMBIN(numObjs,numInSet)
169
+ *
170
+ * @access public
171
+ * @category Mathematical and Trigonometric Functions
172
+ * @param int $numObjs Number of different objects
173
+ * @param int $numInSet Number of objects in each combination
174
+ * @return int Number of combinations
175
+ */
176
+ public static function COMBIN($numObjs, $numInSet) {
177
+ $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
178
+ $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
179
+
180
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
181
+ if ($numObjs < $numInSet) {
182
+ return PHPExcel_Calculation_Functions::NaN();
183
+ } elseif ($numInSet < 0) {
184
+ return PHPExcel_Calculation_Functions::NaN();
185
+ }
186
+ return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
187
+ }
188
+ return PHPExcel_Calculation_Functions::VALUE();
189
+ } // function COMBIN()
190
+
191
+
192
+ /**
193
+ * EVEN
194
+ *
195
+ * Returns number rounded up to the nearest even integer.
196
+ * You can use this function for processing items that come in twos. For example,
197
+ * a packing crate accepts rows of one or two items. The crate is full when
198
+ * the number of items, rounded up to the nearest two, matches the crate's
199
+ * capacity.
200
+ *
201
+ * Excel Function:
202
+ * EVEN(number)
203
+ *
204
+ * @access public
205
+ * @category Mathematical and Trigonometric Functions
206
+ * @param float $number Number to round
207
+ * @return int Rounded Number
208
+ */
209
+ public static function EVEN($number) {
210
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
211
+
212
+ if (is_null($number)) {
213
+ return 0;
214
+ } elseif (is_bool($number)) {
215
+ $number = (int) $number;
216
+ }
217
+
218
+ if (is_numeric($number)) {
219
+ $significance = 2 * self::SIGN($number);
220
+ return (int) self::CEILING($number,$significance);
221
+ }
222
+ return PHPExcel_Calculation_Functions::VALUE();
223
+ } // function EVEN()
224
+
225
+
226
+ /**
227
+ * FACT
228
+ *
229
+ * Returns the factorial of a number.
230
+ * The factorial of a number is equal to 1*2*3*...* number.
231
+ *
232
+ * Excel Function:
233
+ * FACT(factVal)
234
+ *
235
+ * @access public
236
+ * @category Mathematical and Trigonometric Functions
237
+ * @param float $factVal Factorial Value
238
+ * @return int Factorial
239
+ */
240
+ public static function FACT($factVal) {
241
+ $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
242
+
243
+ if (is_numeric($factVal)) {
244
+ if ($factVal < 0) {
245
+ return PHPExcel_Calculation_Functions::NaN();
246
+ }
247
+ $factLoop = floor($factVal);
248
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
249
+ if ($factVal > $factLoop) {
250
+ return PHPExcel_Calculation_Functions::NaN();
251
+ }
252
+ }
253
+
254
+ $factorial = 1;
255
+ while ($factLoop > 1) {
256
+ $factorial *= $factLoop--;
257
+ }
258
+ return $factorial ;
259
+ }
260
+ return PHPExcel_Calculation_Functions::VALUE();
261
+ } // function FACT()
262
+
263
+
264
+ /**
265
+ * FACTDOUBLE
266
+ *
267
+ * Returns the double factorial of a number.
268
+ *
269
+ * Excel Function:
270
+ * FACTDOUBLE(factVal)
271
+ *
272
+ * @access public
273
+ * @category Mathematical and Trigonometric Functions
274
+ * @param float $factVal Factorial Value
275
+ * @return int Double Factorial
276
+ */
277
+ public static function FACTDOUBLE($factVal) {
278
+ $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
279
+
280
+ if (is_numeric($factLoop)) {
281
+ $factLoop = floor($factLoop);
282
+ if ($factVal < 0) {
283
+ return PHPExcel_Calculation_Functions::NaN();
284
+ }
285
+ $factorial = 1;
286
+ while ($factLoop > 1) {
287
+ $factorial *= $factLoop--;
288
+ --$factLoop;
289
+ }
290
+ return $factorial ;
291
+ }
292
+ return PHPExcel_Calculation_Functions::VALUE();
293
+ } // function FACTDOUBLE()
294
+
295
+
296
+ /**
297
+ * FLOOR
298
+ *
299
+ * Rounds number down, toward zero, to the nearest multiple of significance.
300
+ *
301
+ * Excel Function:
302
+ * FLOOR(number[,significance])
303
+ *
304
+ * @access public
305
+ * @category Mathematical and Trigonometric Functions
306
+ * @param float $number Number to round
307
+ * @param float $significance Significance
308
+ * @return float Rounded Number
309
+ */
310
+ public static function FLOOR($number, $significance = NULL) {
311
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
312
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
313
+
314
+ if ((is_null($significance)) && (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
315
+ $significance = $number/abs($number);
316
+ }
317
+
318
+ if ((is_numeric($number)) && (is_numeric($significance))) {
319
+ if ($significance == 0.0) {
320
+ return PHPExcel_Calculation_Functions::DIV0();
321
+ } elseif ($number == 0.0) {
322
+ return 0.0;
323
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
324
+ return floor($number / $significance) * $significance;
325
+ } else {
326
+ return PHPExcel_Calculation_Functions::NaN();
327
+ }
328
+ } else
329
+
330
+ return PHPExcel_Calculation_Functions::VALUE();
331
+ } // function FLOOR()
332
+
333
+
334
+ /**
335
+ * GCD
336
+ *
337
+ * Returns the greatest common divisor of a series of numbers.
338
+ * The greatest common divisor is the largest integer that divides both
339
+ * number1 and number2 without a remainder.
340
+ *
341
+ * Excel Function:
342
+ * GCD(number1[,number2[, ...]])
343
+ *
344
+ * @access public
345
+ * @category Mathematical and Trigonometric Functions
346
+ * @param mixed $arg,... Data values
347
+ * @return integer Greatest Common Divisor
348
+ */
349
+ public static function GCD() {
350
+ $returnValue = 1;
351
+ $allValuesFactors = array();
352
+ // Loop through arguments
353
+ foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
354
+ if (!is_numeric($value)) {
355
+ return PHPExcel_Calculation_Functions::VALUE();
356
+ } elseif ($value == 0) {
357
+ continue;
358
+ } elseif($value < 0) {
359
+ return PHPExcel_Calculation_Functions::NaN();
360
+ }
361
+ $myFactors = self::_factors($value);
362
+ $myCountedFactors = array_count_values($myFactors);
363
+ $allValuesFactors[] = $myCountedFactors;
364
+ }
365
+ $allValuesCount = count($allValuesFactors);
366
+ if ($allValuesCount == 0) {
367
+ return 0;
368
+ }
369
+
370
+ $mergedArray = $allValuesFactors[0];
371
+ for ($i=1;$i < $allValuesCount; ++$i) {
372
+ $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]);
373
+ }
374
+ $mergedArrayValues = count($mergedArray);
375
+ if ($mergedArrayValues == 0) {
376
+ return $returnValue;
377
+ } elseif ($mergedArrayValues > 1) {
378
+ foreach($mergedArray as $mergedKey => $mergedValue) {
379
+ foreach($allValuesFactors as $highestPowerTest) {
380
+ foreach($highestPowerTest as $testKey => $testValue) {
381
+ if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
382
+ $mergedArray[$mergedKey] = $testValue;
383
+ $mergedValue = $testValue;
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ $returnValue = 1;
390
+ foreach($mergedArray as $key => $value) {
391
+ $returnValue *= pow($key,$value);
392
+ }
393
+ return $returnValue;
394
+ } else {
395
+ $keys = array_keys($mergedArray);
396
+ $key = $keys[0];
397
+ $value = $mergedArray[$key];
398
+ foreach($allValuesFactors as $testValue) {
399
+ foreach($testValue as $mergedKey => $mergedValue) {
400
+ if (($mergedKey == $key) && ($mergedValue < $value)) {
401
+ $value = $mergedValue;
402
+ }
403
+ }
404
+ }
405
+ return pow($key,$value);
406
+ }
407
+ } // function GCD()
408
+
409
+
410
+ /**
411
+ * INT
412
+ *
413
+ * Casts a floating point value to an integer
414
+ *
415
+ * Excel Function:
416
+ * INT(number)
417
+ *
418
+ * @access public
419
+ * @category Mathematical and Trigonometric Functions
420
+ * @param float $number Number to cast to an integer
421
+ * @return integer Integer value
422
+ */
423
+ public static function INT($number) {
424
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
425
+
426
+ if (is_null($number)) {
427
+ return 0;
428
+ } elseif (is_bool($number)) {
429
+ return (int) $number;
430
+ }
431
+ if (is_numeric($number)) {
432
+ return (int) floor($number);
433
+ }
434
+ return PHPExcel_Calculation_Functions::VALUE();
435
+ } // function INT()
436
+
437
+
438
+ /**
439
+ * LCM
440
+ *
441
+ * Returns the lowest common multiplier of a series of numbers
442
+ * The least common multiple is the smallest positive integer that is a multiple
443
+ * of all integer arguments number1, number2, and so on. Use LCM to add fractions
444
+ * with different denominators.
445
+ *
446
+ * Excel Function:
447
+ * LCM(number1[,number2[, ...]])
448
+ *
449
+ * @access public
450
+ * @category Mathematical and Trigonometric Functions
451
+ * @param mixed $arg,... Data values
452
+ * @return int Lowest Common Multiplier
453
+ */
454
+ public static function LCM() {
455
+ $returnValue = 1;
456
+ $allPoweredFactors = array();
457
+ // Loop through arguments
458
+ foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
459
+ if (!is_numeric($value)) {
460
+ return PHPExcel_Calculation_Functions::VALUE();
461
+ }
462
+ if ($value == 0) {
463
+ return 0;
464
+ } elseif ($value < 0) {
465
+ return PHPExcel_Calculation_Functions::NaN();
466
+ }
467
+ $myFactors = self::_factors(floor($value));
468
+ $myCountedFactors = array_count_values($myFactors);
469
+ $myPoweredFactors = array();
470
+ foreach($myCountedFactors as $myCountedFactor => $myCountedPower) {
471
+ $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower);
472
+ }
473
+ foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
474
+ if (array_key_exists($myPoweredValue,$allPoweredFactors)) {
475
+ if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
476
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
477
+ }
478
+ } else {
479
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
480
+ }
481
+ }
482
+ }
483
+ foreach($allPoweredFactors as $allPoweredFactor) {
484
+ $returnValue *= (integer) $allPoweredFactor;
485
+ }
486
+ return $returnValue;
487
+ } // function LCM()
488
+
489
+
490
+ /**
491
+ * LOG_BASE
492
+ *
493
+ * Returns the logarithm of a number to a specified base. The default base is 10.
494
+ *
495
+ * Excel Function:
496
+ * LOG(number[,base])
497
+ *
498
+ * @access public
499
+ * @category Mathematical and Trigonometric Functions
500
+ * @param float $number The positive real number for which you want the logarithm
501
+ * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
502
+ * @return float
503
+ */
504
+ public static function LOG_BASE($number = NULL, $base = 10) {
505
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
506
+ $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base);
507
+
508
+ if ((!is_numeric($base)) || (!is_numeric($number)))
509
+ return PHPExcel_Calculation_Functions::VALUE();
510
+ if (($base <= 0) || ($number <= 0))
511
+ return PHPExcel_Calculation_Functions::NaN();
512
+ return log($number, $base);
513
+ } // function LOG_BASE()
514
+
515
+
516
+ /**
517
+ * MDETERM
518
+ *
519
+ * Returns the matrix determinant of an array.
520
+ *
521
+ * Excel Function:
522
+ * MDETERM(array)
523
+ *
524
+ * @access public
525
+ * @category Mathematical and Trigonometric Functions
526
+ * @param array $matrixValues A matrix of values
527
+ * @return float
528
+ */
529
+ public static function MDETERM($matrixValues) {
530
+ $matrixData = array();
531
+ if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
532
+
533
+ $row = $maxColumn = 0;
534
+ foreach($matrixValues as $matrixRow) {
535
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
536
+ $column = 0;
537
+ foreach($matrixRow as $matrixCell) {
538
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
539
+ return PHPExcel_Calculation_Functions::VALUE();
540
+ }
541
+ $matrixData[$column][$row] = $matrixCell;
542
+ ++$column;
543
+ }
544
+ if ($column > $maxColumn) { $maxColumn = $column; }
545
+ ++$row;
546
+ }
547
+ if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); }
548
+
549
+ try {
550
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
551
+ return $matrix->det();
552
+ } catch (PHPExcel_Exception $ex) {
553
+ return PHPExcel_Calculation_Functions::VALUE();
554
+ }
555
+ } // function MDETERM()
556
+
557
+
558
+ /**
559
+ * MINVERSE
560
+ *
561
+ * Returns the inverse matrix for the matrix stored in an array.
562
+ *
563
+ * Excel Function:
564
+ * MINVERSE(array)
565
+ *
566
+ * @access public
567
+ * @category Mathematical and Trigonometric Functions
568
+ * @param array $matrixValues A matrix of values
569
+ * @return array
570
+ */
571
+ public static function MINVERSE($matrixValues) {
572
+ $matrixData = array();
573
+ if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
574
+
575
+ $row = $maxColumn = 0;
576
+ foreach($matrixValues as $matrixRow) {
577
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
578
+ $column = 0;
579
+ foreach($matrixRow as $matrixCell) {
580
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
581
+ return PHPExcel_Calculation_Functions::VALUE();
582
+ }
583
+ $matrixData[$column][$row] = $matrixCell;
584
+ ++$column;
585
+ }
586
+ if ($column > $maxColumn) { $maxColumn = $column; }
587
+ ++$row;
588
+ }
589
+ if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); }
590
+
591
+ try {
592
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
593
+ return $matrix->inverse()->getArray();
594
+ } catch (PHPExcel_Exception $ex) {
595
+ return PHPExcel_Calculation_Functions::VALUE();
596
+ }
597
+ } // function MINVERSE()
598
+
599
+
600
+ /**
601
+ * MMULT
602
+ *
603
+ * @param array $matrixData1 A matrix of values
604
+ * @param array $matrixData2 A matrix of values
605
+ * @return array
606
+ */
607
+ public static function MMULT($matrixData1,$matrixData2) {
608
+ $matrixAData = $matrixBData = array();
609
+ if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); }
610
+ if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); }
611
+
612
+ try {
613
+ $rowA = 0;
614
+ foreach($matrixData1 as $matrixRow) {
615
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
616
+ $columnA = 0;
617
+ foreach($matrixRow as $matrixCell) {
618
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
619
+ return PHPExcel_Calculation_Functions::VALUE();
620
+ }
621
+ $matrixAData[$rowA][$columnA] = $matrixCell;
622
+ ++$columnA;
623
+ }
624
+ ++$rowA;
625
+ }
626
+ $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData);
627
+ $rowB = 0;
628
+ foreach($matrixData2 as $matrixRow) {
629
+ if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); }
630
+ $columnB = 0;
631
+ foreach($matrixRow as $matrixCell) {
632
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
633
+ return PHPExcel_Calculation_Functions::VALUE();
634
+ }
635
+ $matrixBData[$rowB][$columnB] = $matrixCell;
636
+ ++$columnB;
637
+ }
638
+ ++$rowB;
639
+ }
640
+ $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData);
641
+
642
+ if ($columnA != $rowB) {
643
+ return PHPExcel_Calculation_Functions::VALUE();
644
+ }
645
+
646
+ return $matrixA->times($matrixB)->getArray();
647
+ } catch (PHPExcel_Exception $ex) {
648
+ var_dump($ex->getMessage());
649
+ return PHPExcel_Calculation_Functions::VALUE();
650
+ }
651
+ } // function MMULT()
652
+
653
+
654
+ /**
655
+ * MOD
656
+ *
657
+ * @param int $a Dividend
658
+ * @param int $b Divisor
659
+ * @return int Remainder
660
+ */
661
+ public static function MOD($a = 1, $b = 1) {
662
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
663
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
664
+
665
+ if ($b == 0.0) {
666
+ return PHPExcel_Calculation_Functions::DIV0();
667
+ } elseif (($a < 0.0) && ($b > 0.0)) {
668
+ return $b - fmod(abs($a),$b);
669
+ } elseif (($a > 0.0) && ($b < 0.0)) {
670
+ return $b + fmod($a,abs($b));
671
+ }
672
+
673
+ return fmod($a,$b);
674
+ } // function MOD()
675
+
676
+
677
+ /**
678
+ * MROUND
679
+ *
680
+ * Rounds a number to the nearest multiple of a specified value
681
+ *
682
+ * @param float $number Number to round
683
+ * @param int $multiple Multiple to which you want to round $number
684
+ * @return float Rounded Number
685
+ */
686
+ public static function MROUND($number,$multiple) {
687
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
688
+ $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple);
689
+
690
+ if ((is_numeric($number)) && (is_numeric($multiple))) {
691
+ if ($multiple == 0) {
692
+ return 0;
693
+ }
694
+ if ((self::SIGN($number)) == (self::SIGN($multiple))) {
695
+ $multiplier = 1 / $multiple;
696
+ return round($number * $multiplier) / $multiplier;
697
+ }
698
+ return PHPExcel_Calculation_Functions::NaN();
699
+ }
700
+ return PHPExcel_Calculation_Functions::VALUE();
701
+ } // function MROUND()
702
+
703
+
704
+ /**
705
+ * MULTINOMIAL
706
+ *
707
+ * Returns the ratio of the factorial of a sum of values to the product of factorials.
708
+ *
709
+ * @param array of mixed Data Series
710
+ * @return float
711
+ */
712
+ public static function MULTINOMIAL() {
713
+ $summer = 0;
714
+ $divisor = 1;
715
+ // Loop through arguments
716
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
717
+ // Is it a numeric value?
718
+ if (is_numeric($arg)) {
719
+ if ($arg < 1) {
720
+ return PHPExcel_Calculation_Functions::NaN();
721
+ }
722
+ $summer += floor($arg);
723
+ $divisor *= self::FACT($arg);
724
+ } else {
725
+ return PHPExcel_Calculation_Functions::VALUE();
726
+ }
727
+ }
728
+
729
+ // Return
730
+ if ($summer > 0) {
731
+ $summer = self::FACT($summer);
732
+ return $summer / $divisor;
733
+ }
734
+ return 0;
735
+ } // function MULTINOMIAL()
736
+
737
+
738
+ /**
739
+ * ODD
740
+ *
741
+ * Returns number rounded up to the nearest odd integer.
742
+ *
743
+ * @param float $number Number to round
744
+ * @return int Rounded Number
745
+ */
746
+ public static function ODD($number) {
747
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
748
+
749
+ if (is_null($number)) {
750
+ return 1;
751
+ } elseif (is_bool($number)) {
752
+ $number = (int) $number;
753
+ }
754
+
755
+ if (is_numeric($number)) {
756
+ $significance = self::SIGN($number);
757
+ if ($significance == 0) {
758
+ return 1;
759
+ }
760
+
761
+ $result = self::CEILING($number,$significance);
762
+ if ($result == self::EVEN($result)) {
763
+ $result += $significance;
764
+ }
765
+
766
+ return (int) $result;
767
+ }
768
+ return PHPExcel_Calculation_Functions::VALUE();
769
+ } // function ODD()
770
+
771
+
772
+ /**
773
+ * POWER
774
+ *
775
+ * Computes x raised to the power y.
776
+ *
777
+ * @param float $x
778
+ * @param float $y
779
+ * @return float
780
+ */
781
+ public static function POWER($x = 0, $y = 2) {
782
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
783
+ $y = PHPExcel_Calculation_Functions::flattenSingleValue($y);
784
+
785
+ // Validate parameters
786
+ if ($x == 0.0 && $y == 0.0) {
787
+ return PHPExcel_Calculation_Functions::NaN();
788
+ } elseif ($x == 0.0 && $y < 0.0) {
789
+ return PHPExcel_Calculation_Functions::DIV0();
790
+ }
791
+
792
+ // Return
793
+ $result = pow($x, $y);
794
+ return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN();
795
+ } // function POWER()
796
+
797
+
798
+ /**
799
+ * PRODUCT
800
+ *
801
+ * PRODUCT returns the product of all the values and cells referenced in the argument list.
802
+ *
803
+ * Excel Function:
804
+ * PRODUCT(value1[,value2[, ...]])
805
+ *
806
+ * @access public
807
+ * @category Mathematical and Trigonometric Functions
808
+ * @param mixed $arg,... Data values
809
+ * @return float
810
+ */
811
+ public static function PRODUCT() {
812
+ // Return value
813
+ $returnValue = null;
814
+
815
+ // Loop through arguments
816
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
817
+ // Is it a numeric value?
818
+ if ((is_numeric($arg)) && (!is_string($arg))) {
819
+ if (is_null($returnValue)) {
820
+ $returnValue = $arg;
821
+ } else {
822
+ $returnValue *= $arg;
823
+ }
824
+ }
825
+ }
826
+
827
+ // Return
828
+ if (is_null($returnValue)) {
829
+ return 0;
830
+ }
831
+ return $returnValue;
832
+ } // function PRODUCT()
833
+
834
+
835
+ /**
836
+ * QUOTIENT
837
+ *
838
+ * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
839
+ * and denominator is the divisor.
840
+ *
841
+ * Excel Function:
842
+ * QUOTIENT(value1[,value2[, ...]])
843
+ *
844
+ * @access public
845
+ * @category Mathematical and Trigonometric Functions
846
+ * @param mixed $arg,... Data values
847
+ * @return float
848
+ */
849
+ public static function QUOTIENT() {
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 == 0) ? 0 : $arg;
859
+ } else {
860
+ if (($returnValue == 0) || ($arg == 0)) {
861
+ $returnValue = 0;
862
+ } else {
863
+ $returnValue /= $arg;
864
+ }
865
+ }
866
+ }
867
+ }
868
+
869
+ // Return
870
+ return intval($returnValue);
871
+ } // function QUOTIENT()
872
+
873
+
874
+ /**
875
+ * RAND
876
+ *
877
+ * @param int $min Minimal value
878
+ * @param int $max Maximal value
879
+ * @return int Random number
880
+ */
881
+ public static function RAND($min = 0, $max = 0) {
882
+ $min = PHPExcel_Calculation_Functions::flattenSingleValue($min);
883
+ $max = PHPExcel_Calculation_Functions::flattenSingleValue($max);
884
+
885
+ if ($min == 0 && $max == 0) {
886
+ return (mt_rand(0,10000000)) / 10000000;
887
+ } else {
888
+ return mt_rand($min, $max);
889
+ }
890
+ } // function RAND()
891
+
892
+
893
+ public static function ROMAN($aValue, $style=0) {
894
+ $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue);
895
+ $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style);
896
+ if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
897
+ return PHPExcel_Calculation_Functions::VALUE();
898
+ }
899
+ $aValue = (integer) $aValue;
900
+ if ($aValue == 0) {
901
+ return '';
902
+ }
903
+
904
+ $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
905
+ $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
906
+ $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
907
+ $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
908
+
909
+ $roman = '';
910
+ while ($aValue > 5999) {
911
+ $roman .= 'M';
912
+ $aValue -= 1000;
913
+ }
914
+ $m = self::_romanCut($aValue, 1000); $aValue %= 1000;
915
+ $c = self::_romanCut($aValue, 100); $aValue %= 100;
916
+ $t = self::_romanCut($aValue, 10); $aValue %= 10;
917
+
918
+ return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
919
+ } // function ROMAN()
920
+
921
+
922
+ /**
923
+ * ROUNDUP
924
+ *
925
+ * Rounds a number up to a specified number of decimal places
926
+ *
927
+ * @param float $number Number to round
928
+ * @param int $digits Number of digits to which you want to round $number
929
+ * @return float Rounded Number
930
+ */
931
+ public static function ROUNDUP($number,$digits) {
932
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
933
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
934
+
935
+ if ((is_numeric($number)) && (is_numeric($digits))) {
936
+ $significance = pow(10,(int) $digits);
937
+ if ($number < 0.0) {
938
+ return floor($number * $significance) / $significance;
939
+ } else {
940
+ return ceil($number * $significance) / $significance;
941
+ }
942
+ }
943
+ return PHPExcel_Calculation_Functions::VALUE();
944
+ } // function ROUNDUP()
945
+
946
+
947
+ /**
948
+ * ROUNDDOWN
949
+ *
950
+ * Rounds a number down to a specified number of decimal places
951
+ *
952
+ * @param float $number Number to round
953
+ * @param int $digits Number of digits to which you want to round $number
954
+ * @return float Rounded Number
955
+ */
956
+ public static function ROUNDDOWN($number,$digits) {
957
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
958
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
959
+
960
+ if ((is_numeric($number)) && (is_numeric($digits))) {
961
+ $significance = pow(10,(int) $digits);
962
+ if ($number < 0.0) {
963
+ return ceil($number * $significance) / $significance;
964
+ } else {
965
+ return floor($number * $significance) / $significance;
966
+ }
967
+ }
968
+ return PHPExcel_Calculation_Functions::VALUE();
969
+ } // function ROUNDDOWN()
970
+
971
+
972
+ /**
973
+ * SERIESSUM
974
+ *
975
+ * Returns the sum of a power series
976
+ *
977
+ * @param float $x Input value to the power series
978
+ * @param float $n Initial power to which you want to raise $x
979
+ * @param float $m Step by which to increase $n for each term in the series
980
+ * @param array of mixed Data Series
981
+ * @return float
982
+ */
983
+ public static function SERIESSUM() {
984
+ // Return value
985
+ $returnValue = 0;
986
+
987
+ // Loop through arguments
988
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
989
+
990
+ $x = array_shift($aArgs);
991
+ $n = array_shift($aArgs);
992
+ $m = array_shift($aArgs);
993
+
994
+ if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
995
+ // Calculate
996
+ $i = 0;
997
+ foreach($aArgs as $arg) {
998
+ // Is it a numeric value?
999
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1000
+ $returnValue += $arg * pow($x,$n + ($m * $i++));
1001
+ } else {
1002
+ return PHPExcel_Calculation_Functions::VALUE();
1003
+ }
1004
+ }
1005
+ // Return
1006
+ return $returnValue;
1007
+ }
1008
+ return PHPExcel_Calculation_Functions::VALUE();
1009
+ } // function SERIESSUM()
1010
+
1011
+
1012
+ /**
1013
+ * SIGN
1014
+ *
1015
+ * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
1016
+ * if the number is 0, and -1 if the number is negative.
1017
+ *
1018
+ * @param float $number Number to round
1019
+ * @return int sign value
1020
+ */
1021
+ public static function SIGN($number) {
1022
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
1023
+
1024
+ if (is_bool($number))
1025
+ return (int) $number;
1026
+ if (is_numeric($number)) {
1027
+ if ($number == 0.0) {
1028
+ return 0;
1029
+ }
1030
+ return $number / abs($number);
1031
+ }
1032
+ return PHPExcel_Calculation_Functions::VALUE();
1033
+ } // function SIGN()
1034
+
1035
+
1036
+ /**
1037
+ * SQRTPI
1038
+ *
1039
+ * Returns the square root of (number * pi).
1040
+ *
1041
+ * @param float $number Number
1042
+ * @return float Square Root of Number * Pi
1043
+ */
1044
+ public static function SQRTPI($number) {
1045
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
1046
+
1047
+ if (is_numeric($number)) {
1048
+ if ($number < 0) {
1049
+ return PHPExcel_Calculation_Functions::NaN();
1050
+ }
1051
+ return sqrt($number * M_PI) ;
1052
+ }
1053
+ return PHPExcel_Calculation_Functions::VALUE();
1054
+ } // function SQRTPI()
1055
+
1056
+
1057
+ /**
1058
+ * SUBTOTAL
1059
+ *
1060
+ * Returns a subtotal in a list or database.
1061
+ *
1062
+ * @param int the number 1 to 11 that specifies which function to
1063
+ * use in calculating subtotals within a list.
1064
+ * @param array of mixed Data Series
1065
+ * @return float
1066
+ */
1067
+ public static function SUBTOTAL() {
1068
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1069
+
1070
+ // Calculate
1071
+ $subtotal = array_shift($aArgs);
1072
+
1073
+ if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
1074
+ switch($subtotal) {
1075
+ case 1 :
1076
+ return PHPExcel_Calculation_Statistical::AVERAGE($aArgs);
1077
+ break;
1078
+ case 2 :
1079
+ return PHPExcel_Calculation_Statistical::COUNT($aArgs);
1080
+ break;
1081
+ case 3 :
1082
+ return PHPExcel_Calculation_Statistical::COUNTA($aArgs);
1083
+ break;
1084
+ case 4 :
1085
+ return PHPExcel_Calculation_Statistical::MAX($aArgs);
1086
+ break;
1087
+ case 5 :
1088
+ return PHPExcel_Calculation_Statistical::MIN($aArgs);
1089
+ break;
1090
+ case 6 :
1091
+ return self::PRODUCT($aArgs);
1092
+ break;
1093
+ case 7 :
1094
+ return PHPExcel_Calculation_Statistical::STDEV($aArgs);
1095
+ break;
1096
+ case 8 :
1097
+ return PHPExcel_Calculation_Statistical::STDEVP($aArgs);
1098
+ break;
1099
+ case 9 :
1100
+ return self::SUM($aArgs);
1101
+ break;
1102
+ case 10 :
1103
+ return PHPExcel_Calculation_Statistical::VARFunc($aArgs);
1104
+ break;
1105
+ case 11 :
1106
+ return PHPExcel_Calculation_Statistical::VARP($aArgs);
1107
+ break;
1108
+ }
1109
+ }
1110
+ return PHPExcel_Calculation_Functions::VALUE();
1111
+ } // function SUBTOTAL()
1112
+
1113
+
1114
+ /**
1115
+ * SUM
1116
+ *
1117
+ * SUM computes the sum of all the values and cells referenced in the argument list.
1118
+ *
1119
+ * Excel Function:
1120
+ * SUM(value1[,value2[, ...]])
1121
+ *
1122
+ * @access public
1123
+ * @category Mathematical and Trigonometric Functions
1124
+ * @param mixed $arg,... Data values
1125
+ * @return float
1126
+ */
1127
+ public static function SUM() {
1128
+ // Return value
1129
+ $returnValue = 0;
1130
+
1131
+ // Loop through the arguments
1132
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
1133
+ // Is it a numeric value?
1134
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1135
+ $returnValue += $arg;
1136
+ }
1137
+ }
1138
+
1139
+ // Return
1140
+ return $returnValue;
1141
+ } // function SUM()
1142
+
1143
+
1144
+ /**
1145
+ * SUMIF
1146
+ *
1147
+ * Counts the number of cells that contain numbers within the list of arguments
1148
+ *
1149
+ * Excel Function:
1150
+ * SUMIF(value1[,value2[, ...]],condition)
1151
+ *
1152
+ * @access public
1153
+ * @category Mathematical and Trigonometric Functions
1154
+ * @param mixed $arg,... Data values
1155
+ * @param string $condition The criteria that defines which cells will be summed.
1156
+ * @return float
1157
+ */
1158
+ public static function SUMIF($aArgs,$condition,$sumArgs = array()) {
1159
+ // Return value
1160
+ $returnValue = 0;
1161
+
1162
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
1163
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
1164
+ if (empty($sumArgs)) {
1165
+ $sumArgs = $aArgs;
1166
+ }
1167
+ $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
1168
+ // Loop through arguments
1169
+ foreach ($aArgs as $key => $arg) {
1170
+ if (!is_numeric($arg)) {
1171
+ $arg = str_replace('"', '""', $arg);
1172
+ $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg));
1173
+ }
1174
+
1175
+ $testCondition = '='.$arg.$condition;
1176
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
1177
+ // Is it a value within our criteria
1178
+ $returnValue += $sumArgs[$key];
1179
+ }
1180
+ }
1181
+
1182
+ // Return
1183
+ return $returnValue;
1184
+ } // function SUMIF()
1185
+
1186
+
1187
+ /**
1188
+ * SUMPRODUCT
1189
+ *
1190
+ * Excel Function:
1191
+ * SUMPRODUCT(value1[,value2[, ...]])
1192
+ *
1193
+ * @access public
1194
+ * @category Mathematical and Trigonometric Functions
1195
+ * @param mixed $arg,... Data values
1196
+ * @return float
1197
+ */
1198
+ public static function SUMPRODUCT() {
1199
+ $arrayList = func_get_args();
1200
+
1201
+ $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
1202
+ $wrkCellCount = count($wrkArray);
1203
+
1204
+ for ($i=0; $i< $wrkCellCount; ++$i) {
1205
+ if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
1206
+ $wrkArray[$i] = 0;
1207
+ }
1208
+ }
1209
+
1210
+ foreach($arrayList as $matrixData) {
1211
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData);
1212
+ $count = count($array2);
1213
+ if ($wrkCellCount != $count) {
1214
+ return PHPExcel_Calculation_Functions::VALUE();
1215
+ }
1216
+
1217
+ foreach ($array2 as $i => $val) {
1218
+ if ((!is_numeric($val)) || (is_string($val))) {
1219
+ $val = 0;
1220
+ }
1221
+ $wrkArray[$i] *= $val;
1222
+ }
1223
+ }
1224
+
1225
+ return array_sum($wrkArray);
1226
+ } // function SUMPRODUCT()
1227
+
1228
+
1229
+ /**
1230
+ * SUMSQ
1231
+ *
1232
+ * SUMSQ returns the sum of the squares of the arguments
1233
+ *
1234
+ * Excel Function:
1235
+ * SUMSQ(value1[,value2[, ...]])
1236
+ *
1237
+ * @access public
1238
+ * @category Mathematical and Trigonometric Functions
1239
+ * @param mixed $arg,... Data values
1240
+ * @return float
1241
+ */
1242
+ public static function SUMSQ() {
1243
+ // Return value
1244
+ $returnValue = 0;
1245
+
1246
+ // Loop through arguments
1247
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
1248
+ // Is it a numeric value?
1249
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1250
+ $returnValue += ($arg * $arg);
1251
+ }
1252
+ }
1253
+
1254
+ // Return
1255
+ return $returnValue;
1256
+ } // function SUMSQ()
1257
+
1258
+
1259
+ /**
1260
+ * SUMX2MY2
1261
+ *
1262
+ * @param mixed[] $matrixData1 Matrix #1
1263
+ * @param mixed[] $matrixData2 Matrix #2
1264
+ * @return float
1265
+ */
1266
+ public static function SUMX2MY2($matrixData1,$matrixData2) {
1267
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1268
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1269
+ $count1 = count($array1);
1270
+ $count2 = count($array2);
1271
+ if ($count1 < $count2) {
1272
+ $count = $count1;
1273
+ } else {
1274
+ $count = $count2;
1275
+ }
1276
+
1277
+ $result = 0;
1278
+ for ($i = 0; $i < $count; ++$i) {
1279
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1280
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1281
+ $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
1282
+ }
1283
+ }
1284
+
1285
+ return $result;
1286
+ } // function SUMX2MY2()
1287
+
1288
+
1289
+ /**
1290
+ * SUMX2PY2
1291
+ *
1292
+ * @param mixed[] $matrixData1 Matrix #1
1293
+ * @param mixed[] $matrixData2 Matrix #2
1294
+ * @return float
1295
+ */
1296
+ public static function SUMX2PY2($matrixData1,$matrixData2) {
1297
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1298
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1299
+ $count1 = count($array1);
1300
+ $count2 = count($array2);
1301
+ if ($count1 < $count2) {
1302
+ $count = $count1;
1303
+ } else {
1304
+ $count = $count2;
1305
+ }
1306
+
1307
+ $result = 0;
1308
+ for ($i = 0; $i < $count; ++$i) {
1309
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1310
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1311
+ $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
1312
+ }
1313
+ }
1314
+
1315
+ return $result;
1316
+ } // function SUMX2PY2()
1317
+
1318
+
1319
+ /**
1320
+ * SUMXMY2
1321
+ *
1322
+ * @param mixed[] $matrixData1 Matrix #1
1323
+ * @param mixed[] $matrixData2 Matrix #2
1324
+ * @return float
1325
+ */
1326
+ public static function SUMXMY2($matrixData1,$matrixData2) {
1327
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1328
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1329
+ $count1 = count($array1);
1330
+ $count2 = count($array2);
1331
+ if ($count1 < $count2) {
1332
+ $count = $count1;
1333
+ } else {
1334
+ $count = $count2;
1335
+ }
1336
+
1337
+ $result = 0;
1338
+ for ($i = 0; $i < $count; ++$i) {
1339
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1340
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1341
+ $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
1342
+ }
1343
+ }
1344
+
1345
+ return $result;
1346
+ } // function SUMXMY2()
1347
+
1348
+
1349
+ /**
1350
+ * TRUNC
1351
+ *
1352
+ * Truncates value to the number of fractional digits by number_digits.
1353
+ *
1354
+ * @param float $value
1355
+ * @param int $digits
1356
+ * @return float Truncated value
1357
+ */
1358
+ public static function TRUNC($value = 0, $digits = 0) {
1359
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1360
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
1361
+
1362
+ // Validate parameters
1363
+ if ((!is_numeric($value)) || (!is_numeric($digits)))
1364
+ return PHPExcel_Calculation_Functions::VALUE();
1365
+ $digits = floor($digits);
1366
+
1367
+ // Truncate
1368
+ $adjust = pow(10, $digits);
1369
+
1370
+ if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust),'0') < $adjust/10))
1371
+ return $value;
1372
+
1373
+ return (intval($value * $adjust)) / $adjust;
1374
+ } // function TRUNC()
1375
+
1376
+ } // class PHPExcel_Calculation_MathTrig
libraries/PHPExcel/Calculation/Statistical.php ADDED
@@ -0,0 +1,3651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/trendClass.php';
40
+
41
+
42
+ /** LOG_GAMMA_X_MAX_VALUE */
43
+ define('LOG_GAMMA_X_MAX_VALUE', 2.55e305);
44
+
45
+ /** XMININ */
46
+ define('XMININ', 2.23e-308);
47
+
48
+ /** EPS */
49
+ define('EPS', 2.22e-16);
50
+
51
+ /** SQRT2PI */
52
+ define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099);
53
+
54
+
55
+ /**
56
+ * PHPExcel_Calculation_Statistical
57
+ *
58
+ * @category PHPExcel
59
+ * @package PHPExcel_Calculation
60
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
61
+ */
62
+ class PHPExcel_Calculation_Statistical {
63
+
64
+
65
+ private static function _checkTrendArrays(&$array1,&$array2) {
66
+ if (!is_array($array1)) { $array1 = array($array1); }
67
+ if (!is_array($array2)) { $array2 = array($array2); }
68
+
69
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($array1);
70
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($array2);
71
+ foreach($array1 as $key => $value) {
72
+ if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
73
+ unset($array1[$key]);
74
+ unset($array2[$key]);
75
+ }
76
+ }
77
+ foreach($array2 as $key => $value) {
78
+ if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
79
+ unset($array1[$key]);
80
+ unset($array2[$key]);
81
+ }
82
+ }
83
+ $array1 = array_merge($array1);
84
+ $array2 = array_merge($array2);
85
+
86
+ return True;
87
+ } // function _checkTrendArrays()
88
+
89
+
90
+ /**
91
+ * Beta function.
92
+ *
93
+ * @author Jaco van Kooten
94
+ *
95
+ * @param p require p>0
96
+ * @param q require q>0
97
+ * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
98
+ */
99
+ private static function _beta($p, $q) {
100
+ if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) {
101
+ return 0.0;
102
+ } else {
103
+ return exp(self::_logBeta($p, $q));
104
+ }
105
+ } // function _beta()
106
+
107
+
108
+ /**
109
+ * Incomplete beta function
110
+ *
111
+ * @author Jaco van Kooten
112
+ * @author Paul Meagher
113
+ *
114
+ * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
115
+ * @param x require 0<=x<=1
116
+ * @param p require p>0
117
+ * @param q require q>0
118
+ * @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
119
+ */
120
+ private static function _incompleteBeta($x, $p, $q) {
121
+ if ($x <= 0.0) {
122
+ return 0.0;
123
+ } elseif ($x >= 1.0) {
124
+ return 1.0;
125
+ } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
126
+ return 0.0;
127
+ }
128
+ $beta_gam = exp((0 - self::_logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
129
+ if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
130
+ return $beta_gam * self::_betaFraction($x, $p, $q) / $p;
131
+ } else {
132
+ return 1.0 - ($beta_gam * self::_betaFraction(1 - $x, $q, $p) / $q);
133
+ }
134
+ } // function _incompleteBeta()
135
+
136
+
137
+ // Function cache for _logBeta function
138
+ private static $_logBetaCache_p = 0.0;
139
+ private static $_logBetaCache_q = 0.0;
140
+ private static $_logBetaCache_result = 0.0;
141
+
142
+ /**
143
+ * The natural logarithm of the beta function.
144
+ *
145
+ * @param p require p>0
146
+ * @param q require q>0
147
+ * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
148
+ * @author Jaco van Kooten
149
+ */
150
+ private static function _logBeta($p, $q) {
151
+ if ($p != self::$_logBetaCache_p || $q != self::$_logBetaCache_q) {
152
+ self::$_logBetaCache_p = $p;
153
+ self::$_logBetaCache_q = $q;
154
+ if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
155
+ self::$_logBetaCache_result = 0.0;
156
+ } else {
157
+ self::$_logBetaCache_result = self::_logGamma($p) + self::_logGamma($q) - self::_logGamma($p + $q);
158
+ }
159
+ }
160
+ return self::$_logBetaCache_result;
161
+ } // function _logBeta()
162
+
163
+
164
+ /**
165
+ * Evaluates of continued fraction part of incomplete beta function.
166
+ * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
167
+ * @author Jaco van Kooten
168
+ */
169
+ private static function _betaFraction($x, $p, $q) {
170
+ $c = 1.0;
171
+ $sum_pq = $p + $q;
172
+ $p_plus = $p + 1.0;
173
+ $p_minus = $p - 1.0;
174
+ $h = 1.0 - $sum_pq * $x / $p_plus;
175
+ if (abs($h) < XMININ) {
176
+ $h = XMININ;
177
+ }
178
+ $h = 1.0 / $h;
179
+ $frac = $h;
180
+ $m = 1;
181
+ $delta = 0.0;
182
+ while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION ) {
183
+ $m2 = 2 * $m;
184
+ // even index for d
185
+ $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2));
186
+ $h = 1.0 + $d * $h;
187
+ if (abs($h) < XMININ) {
188
+ $h = XMININ;
189
+ }
190
+ $h = 1.0 / $h;
191
+ $c = 1.0 + $d / $c;
192
+ if (abs($c) < XMININ) {
193
+ $c = XMININ;
194
+ }
195
+ $frac *= $h * $c;
196
+ // odd index for d
197
+ $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
198
+ $h = 1.0 + $d * $h;
199
+ if (abs($h) < XMININ) {
200
+ $h = XMININ;
201
+ }
202
+ $h = 1.0 / $h;
203
+ $c = 1.0 + $d / $c;
204
+ if (abs($c) < XMININ) {
205
+ $c = XMININ;
206
+ }
207
+ $delta = $h * $c;
208
+ $frac *= $delta;
209
+ ++$m;
210
+ }
211
+ return $frac;
212
+ } // function _betaFraction()
213
+
214
+
215
+ /**
216
+ * logGamma function
217
+ *
218
+ * @version 1.1
219
+ * @author Jaco van Kooten
220
+ *
221
+ * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
222
+ *
223
+ * The natural logarithm of the gamma function. <br />
224
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br />
225
+ * Applied Mathematics Division <br />
226
+ * Argonne National Laboratory <br />
227
+ * Argonne, IL 60439 <br />
228
+ * <p>
229
+ * References:
230
+ * <ol>
231
+ * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
232
+ * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li>
233
+ * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li>
234
+ * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li>
235
+ * </ol>
236
+ * </p>
237
+ * <p>
238
+ * From the original documentation:
239
+ * </p>
240
+ * <p>
241
+ * This routine calculates the LOG(GAMMA) function for a positive real argument X.
242
+ * Computation is based on an algorithm outlined in references 1 and 2.
243
+ * The program uses rational functions that theoretically approximate LOG(GAMMA)
244
+ * to at least 18 significant decimal digits. The approximation for X > 12 is from
245
+ * reference 3, while approximations for X < 12.0 are similar to those in reference
246
+ * 1, but are unpublished. The accuracy achieved depends on the arithmetic system,
247
+ * the compiler, the intrinsic functions, and proper selection of the
248
+ * machine-dependent constants.
249
+ * </p>
250
+ * <p>
251
+ * Error returns: <br />
252
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
253
+ * The computation is believed to be free of underflow and overflow.
254
+ * </p>
255
+ * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
256
+ */
257
+
258
+ // Function cache for logGamma
259
+ private static $_logGammaCache_result = 0.0;
260
+ private static $_logGammaCache_x = 0.0;
261
+
262
+ private static function _logGamma($x) {
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( 4.945235359296727046734888,
269
+ 201.8112620856775083915565,
270
+ 2290.838373831346393026739,
271
+ 11319.67205903380828685045,
272
+ 28557.24635671635335736389,
273
+ 38484.96228443793359990269,
274
+ 26377.48787624195437963534,
275
+ 7225.813979700288197698961 );
276
+ static $lg_p2 = array( 4.974607845568932035012064,
277
+ 542.4138599891070494101986,
278
+ 15506.93864978364947665077,
279
+ 184793.2904445632425417223,
280
+ 1088204.76946882876749847,
281
+ 3338152.967987029735917223,
282
+ 5106661.678927352456275255,
283
+ 3074109.054850539556250927 );
284
+ static $lg_p4 = array( 14745.02166059939948905062,
285
+ 2426813.369486704502836312,
286
+ 121475557.4045093227939592,
287
+ 2663432449.630976949898078,
288
+ 29403789566.34553899906876,
289
+ 170266573776.5398868392998,
290
+ 492612579337.743088758812,
291
+ 560625185622.3951465078242 );
292
+
293
+ static $lg_q1 = array( 67.48212550303777196073036,
294
+ 1113.332393857199323513008,
295
+ 7738.757056935398733233834,
296
+ 27639.87074403340708898585,
297
+ 54993.10206226157329794414,
298
+ 61611.22180066002127833352,
299
+ 36351.27591501940507276287,
300
+ 8785.536302431013170870835 );
301
+ static $lg_q2 = array( 183.0328399370592604055942,
302
+ 7765.049321445005871323047,
303
+ 133190.3827966074194402448,
304
+ 1136705.821321969608938755,
305
+ 5267964.117437946917577538,
306
+ 13467014.54311101692290052,
307
+ 17827365.30353274213975932,
308
+ 9533095.591844353613395747 );
309
+ static $lg_q4 = array( 2690.530175870899333379843,
310
+ 639388.5654300092398984238,
311
+ 41355999.30241388052042842,
312
+ 1120872109.61614794137657,
313
+ 14886137286.78813811542398,
314
+ 101680358627.2438228077304,
315
+ 341747634550.7377132798597,
316
+ 446315818741.9713286462081 );
317
+
318
+ static $lg_c = array( -0.001910444077728,
319
+ 8.4171387781295e-4,
320
+ -5.952379913043012e-4,
321
+ 7.93650793500350248e-4,
322
+ -0.002777777777777681622553,
323
+ 0.08333333333333333331554247,
324
+ 0.0057083835261 );
325
+
326
+ // Rough estimate of the fourth root of logGamma_xBig
327
+ static $lg_frtbig = 2.25e76;
328
+ static $pnt68 = 0.6796875;
329
+
330
+
331
+ if ($x == self::$_logGammaCache_x) {
332
+ return self::$_logGammaCache_result;
333
+ }
334
+ $y = $x;
335
+ if ($y > 0.0 && $y <= LOG_GAMMA_X_MAX_VALUE) {
336
+ if ($y <= EPS) {
337
+ $res = -log(y);
338
+ } elseif ($y <= 1.5) {
339
+ // ---------------------
340
+ // EPS .LT. X .LE. 1.5
341
+ // ---------------------
342
+ if ($y < $pnt68) {
343
+ $corr = -log($y);
344
+ $xm1 = $y;
345
+ } else {
346
+ $corr = 0.0;
347
+ $xm1 = $y - 1.0;
348
+ }
349
+ if ($y <= 0.5 || $y >= $pnt68) {
350
+ $xden = 1.0;
351
+ $xnum = 0.0;
352
+ for ($i = 0; $i < 8; ++$i) {
353
+ $xnum = $xnum * $xm1 + $lg_p1[$i];
354
+ $xden = $xden * $xm1 + $lg_q1[$i];
355
+ }
356
+ $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden));
357
+ } else {
358
+ $xm2 = $y - 1.0;
359
+ $xden = 1.0;
360
+ $xnum = 0.0;
361
+ for ($i = 0; $i < 8; ++$i) {
362
+ $xnum = $xnum * $xm2 + $lg_p2[$i];
363
+ $xden = $xden * $xm2 + $lg_q2[$i];
364
+ }
365
+ $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
366
+ }
367
+ } elseif ($y <= 4.0) {
368
+ // ---------------------
369
+ // 1.5 .LT. X .LE. 4.0
370
+ // ---------------------
371
+ $xm2 = $y - 2.0;
372
+ $xden = 1.0;
373
+ $xnum = 0.0;
374
+ for ($i = 0; $i < 8; ++$i) {
375
+ $xnum = $xnum * $xm2 + $lg_p2[$i];
376
+ $xden = $xden * $xm2 + $lg_q2[$i];
377
+ }
378
+ $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
379
+ } elseif ($y <= 12.0) {
380
+ // ----------------------
381
+ // 4.0 .LT. X .LE. 12.0
382
+ // ----------------------
383
+ $xm4 = $y - 4.0;
384
+ $xden = -1.0;
385
+ $xnum = 0.0;
386
+ for ($i = 0; $i < 8; ++$i) {
387
+ $xnum = $xnum * $xm4 + $lg_p4[$i];
388
+ $xden = $xden * $xm4 + $lg_q4[$i];
389
+ }
390
+ $res = $lg_d4 + $xm4 * ($xnum / $xden);
391
+ } else {
392
+ // ---------------------------------
393
+ // Evaluate for argument .GE. 12.0
394
+ // ---------------------------------
395
+ $res = 0.0;
396
+ if ($y <= $lg_frtbig) {
397
+ $res = $lg_c[6];
398
+ $ysq = $y * $y;
399
+ for ($i = 0; $i < 6; ++$i)
400
+ $res = $res / $ysq + $lg_c[$i];
401
+ }
402
+ $res /= $y;
403
+ $corr = log($y);
404
+ $res = $res + log(SQRT2PI) - 0.5 * $corr;
405
+ $res += $y * ($corr - 1.0);
406
+ }
407
+ } else {
408
+ // --------------------------
409
+ // Return for bad arguments
410
+ // --------------------------
411
+ $res = MAX_VALUE;
412
+ }
413
+ // ------------------------------
414
+ // Final adjustments and return
415
+ // ------------------------------
416
+ self::$_logGammaCache_x = $x;
417
+ self::$_logGammaCache_result = $res;
418
+ return $res;
419
+ } // function _logGamma()
420
+
421
+
422
+ //
423
+ // Private implementation of the incomplete Gamma function
424
+ //
425
+ private static function _incompleteGamma($a,$x) {
426
+ static $max = 32;
427
+ $summer = 0;
428
+ for ($n=0; $n<=$max; ++$n) {
429
+ $divisor = $a;
430
+ for ($i=1; $i<=$n; ++$i) {
431
+ $divisor *= ($a + $i);
432
+ }
433
+ $summer += (pow($x,$n) / $divisor);
434
+ }
435
+ return pow($x,$a) * exp(0-$x) * $summer;
436
+ } // function _incompleteGamma()
437
+
438
+
439
+ //
440
+ // Private implementation of the Gamma function
441
+ //
442
+ private static function _gamma($data) {
443
+ if ($data == 0.0) return 0;
444
+
445
+ static $p0 = 1.000000000190015;
446
+ static $p = array ( 1 => 76.18009172947146,
447
+ 2 => -86.50532032941677,
448
+ 3 => 24.01409824083091,
449
+ 4 => -1.231739572450155,
450
+ 5 => 1.208650973866179e-3,
451
+ 6 => -5.395239384953e-6
452
+ );
453
+
454
+ $y = $x = $data;
455
+ $tmp = $x + 5.5;
456
+ $tmp -= ($x + 0.5) * log($tmp);
457
+
458
+ $summer = $p0;
459
+ for ($j=1;$j<=6;++$j) {
460
+ $summer += ($p[$j] / ++$y);
461
+ }
462
+ return exp(0 - $tmp + log(SQRT2PI * $summer / $x));
463
+ } // function _gamma()
464
+
465
+
466
+ /***************************************************************************
467
+ * inverse_ncdf.php
468
+ * -------------------
469
+ * begin : Friday, January 16, 2004
470
+ * copyright : (C) 2004 Michael Nickerson
471
+ * email : nickersonm@yahoo.com
472
+ *
473
+ ***************************************************************************/
474
+ private static function _inverse_ncdf($p) {
475
+ // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to
476
+ // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as
477
+ // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html
478
+ // I have not checked the accuracy of this implementation. Be aware that PHP
479
+ // will truncate the coeficcients to 14 digits.
480
+
481
+ // You have permission to use and distribute this function freely for
482
+ // whatever purpose you want, but please show common courtesy and give credit
483
+ // where credit is due.
484
+
485
+ // Input paramater is $p - probability - where 0 < p < 1.
486
+
487
+ // Coefficients in rational approximations
488
+ static $a = array( 1 => -3.969683028665376e+01,
489
+ 2 => 2.209460984245205e+02,
490
+ 3 => -2.759285104469687e+02,
491
+ 4 => 1.383577518672690e+02,
492
+ 5 => -3.066479806614716e+01,
493
+ 6 => 2.506628277459239e+00
494
+ );
495
+
496
+ static $b = array( 1 => -5.447609879822406e+01,
497
+ 2 => 1.615858368580409e+02,
498
+ 3 => -1.556989798598866e+02,
499
+ 4 => 6.680131188771972e+01,
500
+ 5 => -1.328068155288572e+01
501
+ );
502
+
503
+ static $c = array( 1 => -7.784894002430293e-03,
504
+ 2 => -3.223964580411365e-01,
505
+ 3 => -2.400758277161838e+00,
506
+ 4 => -2.549732539343734e+00,
507
+ 5 => 4.374664141464968e+00,
508
+ 6 => 2.938163982698783e+00
509
+ );
510
+
511
+ static $d = array( 1 => 7.784695709041462e-03,
512
+ 2 => 3.224671290700398e-01,
513
+ 3 => 2.445134137142996e+00,
514
+ 4 => 3.754408661907416e+00
515
+ );
516
+
517
+ // Define lower and upper region break-points.
518
+ $p_low = 0.02425; //Use lower region approx. below this
519
+ $p_high = 1 - $p_low; //Use upper region approx. above this
520
+
521
+ if (0 < $p && $p < $p_low) {
522
+ // Rational approximation for lower region.
523
+ $q = sqrt(-2 * log($p));
524
+ return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
525
+ (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
526
+ } elseif ($p_low <= $p && $p <= $p_high) {
527
+ // Rational approximation for central region.
528
+ $q = $p - 0.5;
529
+ $r = $q * $q;
530
+ return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q /
531
+ ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1);
532
+ } elseif ($p_high < $p && $p < 1) {
533
+ // Rational approximation for upper region.
534
+ $q = sqrt(-2 * log(1 - $p));
535
+ return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
536
+ (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
537
+ }
538
+ // If 0 < p < 1, return a null value
539
+ return PHPExcel_Calculation_Functions::NULL();
540
+ } // function _inverse_ncdf()
541
+
542
+
543
+ private static function _inverse_ncdf2($prob) {
544
+ // Approximation of inverse standard normal CDF developed by
545
+ // B. Moro, "The Full Monte," Risk 8(2), Feb 1995, 57-58.
546
+
547
+ $a1 = 2.50662823884;
548
+ $a2 = -18.61500062529;
549
+ $a3 = 41.39119773534;
550
+ $a4 = -25.44106049637;
551
+
552
+ $b1 = -8.4735109309;
553
+ $b2 = 23.08336743743;
554
+ $b3 = -21.06224101826;
555
+ $b4 = 3.13082909833;
556
+
557
+ $c1 = 0.337475482272615;
558
+ $c2 = 0.976169019091719;
559
+ $c3 = 0.160797971491821;
560
+ $c4 = 2.76438810333863E-02;
561
+ $c5 = 3.8405729373609E-03;
562
+ $c6 = 3.951896511919E-04;
563
+ $c7 = 3.21767881768E-05;
564
+ $c8 = 2.888167364E-07;
565
+ $c9 = 3.960315187E-07;
566
+
567
+ $y = $prob - 0.5;
568
+ if (abs($y) < 0.42) {
569
+ $z = ($y * $y);
570
+ $z = $y * ((($a4 * $z + $a3) * $z + $a2) * $z + $a1) / (((($b4 * $z + $b3) * $z + $b2) * $z + $b1) * $z + 1);
571
+ } else {
572
+ if ($y > 0) {
573
+ $z = log(-log(1 - $prob));
574
+ } else {
575
+ $z = log(-log($prob));
576
+ }
577
+ $z = $c1 + $z * ($c2 + $z * ($c3 + $z * ($c4 + $z * ($c5 + $z * ($c6 + $z * ($c7 + $z * ($c8 + $z * $c9)))))));
578
+ if ($y < 0) {
579
+ $z = -$z;
580
+ }
581
+ }
582
+ return $z;
583
+ } // function _inverse_ncdf2()
584
+
585
+
586
+ private static function _inverse_ncdf3($p) {
587
+ // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3.
588
+ // Produces the normal deviate Z corresponding to a given lower
589
+ // tail area of P; Z is accurate to about 1 part in 10**16.
590
+ //
591
+ // This is a PHP version of the original FORTRAN code that can
592
+ // be found at http://lib.stat.cmu.edu/apstat/
593
+ $split1 = 0.425;
594
+ $split2 = 5;
595
+ $const1 = 0.180625;
596
+ $const2 = 1.6;
597
+
598
+ // coefficients for p close to 0.5
599
+ $a0 = 3.3871328727963666080;
600
+ $a1 = 1.3314166789178437745E+2;
601
+ $a2 = 1.9715909503065514427E+3;
602
+ $a3 = 1.3731693765509461125E+4;
603
+ $a4 = 4.5921953931549871457E+4;
604
+ $a5 = 6.7265770927008700853E+4;
605
+ $a6 = 3.3430575583588128105E+4;
606
+ $a7 = 2.5090809287301226727E+3;
607
+
608
+ $b1 = 4.2313330701600911252E+1;
609
+ $b2 = 6.8718700749205790830E+2;
610
+ $b3 = 5.3941960214247511077E+3;
611
+ $b4 = 2.1213794301586595867E+4;
612
+ $b5 = 3.9307895800092710610E+4;
613
+ $b6 = 2.8729085735721942674E+4;
614
+ $b7 = 5.2264952788528545610E+3;
615
+
616
+ // coefficients for p not close to 0, 0.5 or 1.
617
+ $c0 = 1.42343711074968357734;
618
+ $c1 = 4.63033784615654529590;
619
+ $c2 = 5.76949722146069140550;
620
+ $c3 = 3.64784832476320460504;
621
+ $c4 = 1.27045825245236838258;
622
+ $c5 = 2.41780725177450611770E-1;
623
+ $c6 = 2.27238449892691845833E-2;
624
+ $c7 = 7.74545014278341407640E-4;
625
+
626
+ $d1 = 2.05319162663775882187;
627
+ $d2 = 1.67638483018380384940;
628
+ $d3 = 6.89767334985100004550E-1;
629
+ $d4 = 1.48103976427480074590E-1;
630
+ $d5 = 1.51986665636164571966E-2;
631
+ $d6 = 5.47593808499534494600E-4;
632
+ $d7 = 1.05075007164441684324E-9;
633
+
634
+ // coefficients for p near 0 or 1.
635
+ $e0 = 6.65790464350110377720;
636
+ $e1 = 5.46378491116411436990;
637
+ $e2 = 1.78482653991729133580;
638
+ $e3 = 2.96560571828504891230E-1;
639
+ $e4 = 2.65321895265761230930E-2;
640
+ $e5 = 1.24266094738807843860E-3;
641
+ $e6 = 2.71155556874348757815E-5;
642
+ $e7 = 2.01033439929228813265E-7;
643
+
644
+ $f1 = 5.99832206555887937690E-1;
645
+ $f2 = 1.36929880922735805310E-1;
646
+ $f3 = 1.48753612908506148525E-2;
647
+ $f4 = 7.86869131145613259100E-4;
648
+ $f5 = 1.84631831751005468180E-5;
649
+ $f6 = 1.42151175831644588870E-7;
650
+ $f7 = 2.04426310338993978564E-15;
651
+
652
+ $q = $p - 0.5;
653
+
654
+ // computation for p close to 0.5
655
+ if (abs($q) <= split1) {
656
+ $R = $const1 - $q * $q;
657
+ $z = $q * ((((((($a7 * $R + $a6) * $R + $a5) * $R + $a4) * $R + $a3) * $R + $a2) * $R + $a1) * $R + $a0) /
658
+ ((((((($b7 * $R + $b6) * $R + $b5) * $R + $b4) * $R + $b3) * $R + $b2) * $R + $b1) * $R + 1);
659
+ } else {
660
+ if ($q < 0) {
661
+ $R = $p;
662
+ } else {
663
+ $R = 1 - $p;
664
+ }
665
+ $R = pow(-log($R),2);
666
+
667
+ // computation for p not close to 0, 0.5 or 1.
668
+ If ($R <= $split2) {
669
+ $R = $R - $const2;
670
+ $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) /
671
+ ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1);
672
+ } else {
673
+ // computation for p near 0 or 1.
674
+ $R = $R - $split2;
675
+ $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) /
676
+ ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1);
677
+ }
678
+ if ($q < 0) {
679
+ $z = -$z;
680
+ }
681
+ }
682
+ return $z;
683
+ } // function _inverse_ncdf3()
684
+
685
+
686
+ /**
687
+ * AVEDEV
688
+ *
689
+ * Returns the average of the absolute deviations of data points from their mean.
690
+ * AVEDEV is a measure of the variability in a data set.
691
+ *
692
+ * Excel Function:
693
+ * AVEDEV(value1[,value2[, ...]])
694
+ *
695
+ * @access public
696
+ * @category Statistical Functions
697
+ * @param mixed $arg,... Data values
698
+ * @return float
699
+ */
700
+ public static function AVEDEV() {
701
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
702
+
703
+ // Return value
704
+ $returnValue = null;
705
+
706
+ $aMean = self::AVERAGE($aArgs);
707
+ if ($aMean != PHPExcel_Calculation_Functions::DIV0()) {
708
+ $aCount = 0;
709
+ foreach ($aArgs as $k => $arg) {
710
+ if ((is_bool($arg)) &&
711
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
712
+ $arg = (integer) $arg;
713
+ }
714
+ // Is it a numeric value?
715
+ if ((is_numeric($arg)) && (!is_string($arg))) {
716
+ if (is_null($returnValue)) {
717
+ $returnValue = abs($arg - $aMean);
718
+ } else {
719
+ $returnValue += abs($arg - $aMean);
720
+ }
721
+ ++$aCount;
722
+ }
723
+ }
724
+
725
+ // Return
726
+ if ($aCount == 0) {
727
+ return PHPExcel_Calculation_Functions::DIV0();
728
+ }
729
+ return $returnValue / $aCount;
730
+ }
731
+ return PHPExcel_Calculation_Functions::NaN();
732
+ } // function AVEDEV()
733
+
734
+
735
+ /**
736
+ * AVERAGE
737
+ *
738
+ * Returns the average (arithmetic mean) of the arguments
739
+ *
740
+ * Excel Function:
741
+ * AVERAGE(value1[,value2[, ...]])
742
+ *
743
+ * @access public
744
+ * @category Statistical Functions
745
+ * @param mixed $arg,... Data values
746
+ * @return float
747
+ */
748
+ public static function AVERAGE() {
749
+ $returnValue = $aCount = 0;
750
+
751
+ // Loop through arguments
752
+ foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
753
+ if ((is_bool($arg)) &&
754
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
755
+ $arg = (integer) $arg;
756
+ }
757
+ // Is it a numeric value?
758
+ if ((is_numeric($arg)) && (!is_string($arg))) {
759
+ if (is_null($returnValue)) {
760
+ $returnValue = $arg;
761
+ } else {
762
+ $returnValue += $arg;
763
+ }
764
+ ++$aCount;
765
+ }
766
+ }
767
+
768
+ // Return
769
+ if ($aCount > 0) {
770
+ return $returnValue / $aCount;
771
+ } else {
772
+ return PHPExcel_Calculation_Functions::DIV0();
773
+ }
774
+ } // function AVERAGE()
775
+
776
+
777
+ /**
778
+ * AVERAGEA
779
+ *
780
+ * Returns the average of its arguments, including numbers, text, and logical values
781
+ *
782
+ * Excel Function:
783
+ * AVERAGEA(value1[,value2[, ...]])
784
+ *
785
+ * @access public
786
+ * @category Statistical Functions
787
+ * @param mixed $arg,... Data values
788
+ * @return float
789
+ */
790
+ public static function AVERAGEA() {
791
+ // Return value
792
+ $returnValue = null;
793
+
794
+ $aCount = 0;
795
+ // Loop through arguments
796
+ foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
797
+ if ((is_bool($arg)) &&
798
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
799
+ } else {
800
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
801
+ if (is_bool($arg)) {
802
+ $arg = (integer) $arg;
803
+ } elseif (is_string($arg)) {
804
+ $arg = 0;
805
+ }
806
+ if (is_null($returnValue)) {
807
+ $returnValue = $arg;
808
+ } else {
809
+ $returnValue += $arg;
810
+ }
811
+ ++$aCount;
812
+ }
813
+ }
814
+ }
815
+
816
+ // Return
817
+ if ($aCount > 0) {
818
+ return $returnValue / $aCount;
819
+ } else {
820
+ return PHPExcel_Calculation_Functions::DIV0();
821
+ }
822
+ } // function AVERAGEA()
823
+
824
+
825
+ /**
826
+ * AVERAGEIF
827
+ *
828
+ * Returns the average value from a range of cells that contain numbers within the list of arguments
829
+ *
830
+ * Excel Function:
831
+ * AVERAGEIF(value1[,value2[, ...]],condition)
832
+ *
833
+ * @access public
834
+ * @category Mathematical and Trigonometric Functions
835
+ * @param mixed $arg,... Data values
836
+ * @param string $condition The criteria that defines which cells will be checked.
837
+ * @param mixed[] $averageArgs Data values
838
+ * @return float
839
+ */
840
+ public static function AVERAGEIF($aArgs,$condition,$averageArgs = array()) {
841
+ // Return value
842
+ $returnValue = 0;
843
+
844
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
845
+ $averageArgs = PHPExcel_Calculation_Functions::flattenArray($averageArgs);
846
+ if (empty($averageArgs)) {
847
+ $averageArgs = $aArgs;
848
+ }
849
+ $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
850
+ // Loop through arguments
851
+ $aCount = 0;
852
+ foreach ($aArgs as $key => $arg) {
853
+ if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
854
+ $testCondition = '='.$arg.$condition;
855
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
856
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
857
+ $returnValue += $arg;
858
+ ++$aCount;
859
+ }
860
+ }
861
+ }
862
+
863
+ // Return
864
+ if ($aCount > 0) {
865
+ return $returnValue / $aCount;
866
+ } else {
867
+ return PHPExcel_Calculation_Functions::DIV0();
868
+ }
869
+ } // function AVERAGEIF()
870
+
871
+
872
+ /**
873
+ * BETADIST
874
+ *
875
+ * Returns the beta distribution.
876
+ *
877
+ * @param float $value Value at which you want to evaluate the distribution
878
+ * @param float $alpha Parameter to the distribution
879
+ * @param float $beta Parameter to the distribution
880
+ * @param boolean $cumulative
881
+ * @return float
882
+ *
883
+ */
884
+ public static function BETADIST($value,$alpha,$beta,$rMin=0,$rMax=1) {
885
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
886
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
887
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
888
+ $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin);
889
+ $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax);
890
+
891
+ if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
892
+ if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
893
+ return PHPExcel_Calculation_Functions::NaN();
894
+ }
895
+ if ($rMin > $rMax) {
896
+ $tmp = $rMin;
897
+ $rMin = $rMax;
898
+ $rMax = $tmp;
899
+ }
900
+ $value -= $rMin;
901
+ $value /= ($rMax - $rMin);
902
+ return self::_incompleteBeta($value,$alpha,$beta);
903
+ }
904
+ return PHPExcel_Calculation_Functions::VALUE();
905
+ } // function BETADIST()
906
+
907
+
908
+ /**
909
+ * BETAINV
910
+ *
911
+ * Returns the inverse of the beta distribution.
912
+ *
913
+ * @param float $probability Probability at which you want to evaluate the distribution
914
+ * @param float $alpha Parameter to the distribution
915
+ * @param float $beta Parameter to the distribution
916
+ * @param float $rMin Minimum value
917
+ * @param float $rMax Maximum value
918
+ * @param boolean $cumulative
919
+ * @return float
920
+ *
921
+ */
922
+ public static function BETAINV($probability,$alpha,$beta,$rMin=0,$rMax=1) {
923
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
924
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
925
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
926
+ $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin);
927
+ $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax);
928
+
929
+ if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
930
+ if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) {
931
+ return PHPExcel_Calculation_Functions::NaN();
932
+ }
933
+ if ($rMin > $rMax) {
934
+ $tmp = $rMin;
935
+ $rMin = $rMax;
936
+ $rMax = $tmp;
937
+ }
938
+ $a = 0;
939
+ $b = 2;
940
+
941
+ $i = 0;
942
+ while ((($b - $a) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
943
+ $guess = ($a + $b) / 2;
944
+ $result = self::BETADIST($guess, $alpha, $beta);
945
+ if (($result == $probability) || ($result == 0)) {
946
+ $b = $a;
947
+ } elseif ($result > $probability) {
948
+ $b = $guess;
949
+ } else {
950
+ $a = $guess;
951
+ }
952
+ }
953
+ if ($i == MAX_ITERATIONS) {
954
+ return PHPExcel_Calculation_Functions::NA();
955
+ }
956
+ return round($rMin + $guess * ($rMax - $rMin),12);
957
+ }
958
+ return PHPExcel_Calculation_Functions::VALUE();
959
+ } // function BETAINV()
960
+
961
+
962
+ /**
963
+ * BINOMDIST
964
+ *
965
+ * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with
966
+ * a fixed number of tests or trials, when the outcomes of any trial are only success or failure,
967
+ * when trials are independent, and when the probability of success is constant throughout the
968
+ * experiment. For example, BINOMDIST can calculate the probability that two of the next three
969
+ * babies born are male.
970
+ *
971
+ * @param float $value Number of successes in trials
972
+ * @param float $trials Number of trials
973
+ * @param float $probability Probability of success on each trial
974
+ * @param boolean $cumulative
975
+ * @return float
976
+ *
977
+ * @todo Cumulative distribution function
978
+ *
979
+ */
980
+ public static function BINOMDIST($value, $trials, $probability, $cumulative) {
981
+ $value = floor(PHPExcel_Calculation_Functions::flattenSingleValue($value));
982
+ $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials));
983
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
984
+
985
+ if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) {
986
+ if (($value < 0) || ($value > $trials)) {
987
+ return PHPExcel_Calculation_Functions::NaN();
988
+ }
989
+ if (($probability < 0) || ($probability > 1)) {
990
+ return PHPExcel_Calculation_Functions::NaN();
991
+ }
992
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
993
+ if ($cumulative) {
994
+ $summer = 0;
995
+ for ($i = 0; $i <= $value; ++$i) {
996
+ $summer += PHPExcel_Calculation_MathTrig::COMBIN($trials,$i) * pow($probability,$i) * pow(1 - $probability,$trials - $i);
997
+ }
998
+ return $summer;
999
+ } else {
1000
+ return PHPExcel_Calculation_MathTrig::COMBIN($trials,$value) * pow($probability,$value) * pow(1 - $probability,$trials - $value) ;
1001
+ }
1002
+ }
1003
+ }
1004
+ return PHPExcel_Calculation_Functions::VALUE();
1005
+ } // function BINOMDIST()
1006
+
1007
+
1008
+ /**
1009
+ * CHIDIST
1010
+ *
1011
+ * Returns the one-tailed probability of the chi-squared distribution.
1012
+ *
1013
+ * @param float $value Value for the function
1014
+ * @param float $degrees degrees of freedom
1015
+ * @return float
1016
+ */
1017
+ public static function CHIDIST($value, $degrees) {
1018
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1019
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
1020
+
1021
+ if ((is_numeric($value)) && (is_numeric($degrees))) {
1022
+ if ($degrees < 1) {
1023
+ return PHPExcel_Calculation_Functions::NaN();
1024
+ }
1025
+ if ($value < 0) {
1026
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1027
+ return 1;
1028
+ }
1029
+ return PHPExcel_Calculation_Functions::NaN();
1030
+ }
1031
+ return 1 - (self::_incompleteGamma($degrees/2,$value/2) / self::_gamma($degrees/2));
1032
+ }
1033
+ return PHPExcel_Calculation_Functions::VALUE();
1034
+ } // function CHIDIST()
1035
+
1036
+
1037
+ /**
1038
+ * CHIINV
1039
+ *
1040
+ * Returns the one-tailed probability of the chi-squared distribution.
1041
+ *
1042
+ * @param float $probability Probability for the function
1043
+ * @param float $degrees degrees of freedom
1044
+ * @return float
1045
+ */
1046
+ public static function CHIINV($probability, $degrees) {
1047
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1048
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
1049
+
1050
+ if ((is_numeric($probability)) && (is_numeric($degrees))) {
1051
+
1052
+ $xLo = 100;
1053
+ $xHi = 0;
1054
+
1055
+ $x = $xNew = 1;
1056
+ $dx = 1;
1057
+ $i = 0;
1058
+
1059
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
1060
+ // Apply Newton-Raphson step
1061
+ $result = self::CHIDIST($x, $degrees);
1062
+ $error = $result - $probability;
1063
+ if ($error == 0.0) {
1064
+ $dx = 0;
1065
+ } elseif ($error < 0.0) {
1066
+ $xLo = $x;
1067
+ } else {
1068
+ $xHi = $x;
1069
+ }
1070
+ // Avoid division by zero
1071
+ if ($result != 0.0) {
1072
+ $dx = $error / $result;
1073
+ $xNew = $x - $dx;
1074
+ }
1075
+ // If the NR fails to converge (which for example may be the
1076
+ // case if the initial guess is too rough) we apply a bisection
1077
+ // step to determine a more narrow interval around the root.
1078
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
1079
+ $xNew = ($xLo + $xHi) / 2;
1080
+ $dx = $xNew - $x;
1081
+ }
1082
+ $x = $xNew;
1083
+ }
1084
+ if ($i == MAX_ITERATIONS) {
1085
+ return PHPExcel_Calculation_Functions::NA();
1086
+ }
1087
+ return round($x,12);
1088
+ }
1089
+ return PHPExcel_Calculation_Functions::VALUE();
1090
+ } // function CHIINV()
1091
+
1092
+
1093
+ /**
1094
+ * CONFIDENCE
1095
+ *
1096
+ * Returns the confidence interval for a population mean
1097
+ *
1098
+ * @param float $alpha
1099
+ * @param float $stdDev Standard Deviation
1100
+ * @param float $size
1101
+ * @return float
1102
+ *
1103
+ */
1104
+ public static function CONFIDENCE($alpha,$stdDev,$size) {
1105
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1106
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
1107
+ $size = floor(PHPExcel_Calculation_Functions::flattenSingleValue($size));
1108
+
1109
+ if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) {
1110
+ if (($alpha <= 0) || ($alpha >= 1)) {
1111
+ return PHPExcel_Calculation_Functions::NaN();
1112
+ }
1113
+ if (($stdDev <= 0) || ($size < 1)) {
1114
+ return PHPExcel_Calculation_Functions::NaN();
1115
+ }
1116
+ return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size);
1117
+ }
1118
+ return PHPExcel_Calculation_Functions::VALUE();
1119
+ } // function CONFIDENCE()
1120
+
1121
+
1122
+ /**
1123
+ * CORREL
1124
+ *
1125
+ * Returns covariance, the average of the products of deviations for each data point pair.
1126
+ *
1127
+ * @param array of mixed Data Series Y
1128
+ * @param array of mixed Data Series X
1129
+ * @return float
1130
+ */
1131
+ public static function CORREL($yValues,$xValues=null) {
1132
+ if ((is_null($xValues)) || (!is_array($yValues)) || (!is_array($xValues))) {
1133
+ return PHPExcel_Calculation_Functions::VALUE();
1134
+ }
1135
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
1136
+ return PHPExcel_Calculation_Functions::VALUE();
1137
+ }
1138
+ $yValueCount = count($yValues);
1139
+ $xValueCount = count($xValues);
1140
+
1141
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1142
+ return PHPExcel_Calculation_Functions::NA();
1143
+ } elseif ($yValueCount == 1) {
1144
+ return PHPExcel_Calculation_Functions::DIV0();
1145
+ }
1146
+
1147
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
1148
+ return $bestFitLinear->getCorrelation();
1149
+ } // function CORREL()
1150
+
1151
+
1152
+ /**
1153
+ * COUNT
1154
+ *
1155
+ * Counts the number of cells that contain numbers within the list of arguments
1156
+ *
1157
+ * Excel Function:
1158
+ * COUNT(value1[,value2[, ...]])
1159
+ *
1160
+ * @access public
1161
+ * @category Statistical Functions
1162
+ * @param mixed $arg,... Data values
1163
+ * @return int
1164
+ */
1165
+ public static function COUNT() {
1166
+ // Return value
1167
+ $returnValue = 0;
1168
+
1169
+ // Loop through arguments
1170
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1171
+ foreach ($aArgs as $k => $arg) {
1172
+ if ((is_bool($arg)) &&
1173
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
1174
+ $arg = (integer) $arg;
1175
+ }
1176
+ // Is it a numeric value?
1177
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1178
+ ++$returnValue;
1179
+ }
1180
+ }
1181
+
1182
+ // Return
1183
+ return $returnValue;
1184
+ } // function COUNT()
1185
+
1186
+
1187
+ /**
1188
+ * COUNTA
1189
+ *
1190
+ * Counts the number of cells that are not empty within the list of arguments
1191
+ *
1192
+ * Excel Function:
1193
+ * COUNTA(value1[,value2[, ...]])
1194
+ *
1195
+ * @access public
1196
+ * @category Statistical Functions
1197
+ * @param mixed $arg,... Data values
1198
+ * @return int
1199
+ */
1200
+ public static function COUNTA() {
1201
+ // Return value
1202
+ $returnValue = 0;
1203
+
1204
+ // Loop through arguments
1205
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1206
+ foreach ($aArgs as $arg) {
1207
+ // Is it a numeric, boolean or string value?
1208
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
1209
+ ++$returnValue;
1210
+ }
1211
+ }
1212
+
1213
+ // Return
1214
+ return $returnValue;
1215
+ } // function COUNTA()
1216
+
1217
+
1218
+ /**
1219
+ * COUNTBLANK
1220
+ *
1221
+ * Counts the number of empty cells within the list of arguments
1222
+ *
1223
+ * Excel Function:
1224
+ * COUNTBLANK(value1[,value2[, ...]])
1225
+ *
1226
+ * @access public
1227
+ * @category Statistical Functions
1228
+ * @param mixed $arg,... Data values
1229
+ * @return int
1230
+ */
1231
+ public static function COUNTBLANK() {
1232
+ // Return value
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 blank cell?
1239
+ if ((is_null($arg)) || ((is_string($arg)) && ($arg == ''))) {
1240
+ ++$returnValue;
1241
+ }
1242
+ }
1243
+
1244
+ // Return
1245
+ return $returnValue;
1246
+ } // function COUNTBLANK()
1247
+
1248
+
1249
+ /**
1250
+ * COUNTIF
1251
+ *
1252
+ * Counts the number of cells that contain numbers within the list of arguments
1253
+ *
1254
+ * Excel Function:
1255
+ * COUNTIF(value1[,value2[, ...]],condition)
1256
+ *
1257
+ * @access public
1258
+ * @category Statistical Functions
1259
+ * @param mixed $arg,... Data values
1260
+ * @param string $condition The criteria that defines which cells will be counted.
1261
+ * @return int
1262
+ */
1263
+ public static function COUNTIF($aArgs,$condition) {
1264
+ // Return value
1265
+ $returnValue = 0;
1266
+
1267
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
1268
+ $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
1269
+ // Loop through arguments
1270
+ foreach ($aArgs as $arg) {
1271
+ if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
1272
+ $testCondition = '='.$arg.$condition;
1273
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
1274
+ // Is it a value within our criteria
1275
+ ++$returnValue;
1276
+ }
1277
+ }
1278
+
1279
+ // Return
1280
+ return $returnValue;
1281
+ } // function COUNTIF()
1282
+
1283
+
1284
+ /**
1285
+ * COVAR
1286
+ *
1287
+ * Returns covariance, the average of the products of deviations for each data point pair.
1288
+ *
1289
+ * @param array of mixed Data Series Y
1290
+ * @param array of mixed Data Series X
1291
+ * @return float
1292
+ */
1293
+ public static function COVAR($yValues,$xValues) {
1294
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
1295
+ return PHPExcel_Calculation_Functions::VALUE();
1296
+ }
1297
+ $yValueCount = count($yValues);
1298
+ $xValueCount = count($xValues);
1299
+
1300
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1301
+ return PHPExcel_Calculation_Functions::NA();
1302
+ } elseif ($yValueCount == 1) {
1303
+ return PHPExcel_Calculation_Functions::DIV0();
1304
+ }
1305
+
1306
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
1307
+ return $bestFitLinear->getCovariance();
1308
+ } // function COVAR()
1309
+
1310
+
1311
+ /**
1312
+ * CRITBINOM
1313
+ *
1314
+ * Returns the smallest value for which the cumulative binomial distribution is greater
1315
+ * than or equal to a criterion value
1316
+ *
1317
+ * See http://support.microsoft.com/kb/828117/ for details of the algorithm used
1318
+ *
1319
+ * @param float $trials number of Bernoulli trials
1320
+ * @param float $probability probability of a success on each trial
1321
+ * @param float $alpha criterion value
1322
+ * @return int
1323
+ *
1324
+ * @todo Warning. This implementation differs from the algorithm detailed on the MS
1325
+ * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess
1326
+ * This eliminates a potential endless loop error, but may have an adverse affect on the
1327
+ * accuracy of the function (although all my tests have so far returned correct results).
1328
+ *
1329
+ */
1330
+ public static function CRITBINOM($trials, $probability, $alpha) {
1331
+ $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials));
1332
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1333
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1334
+
1335
+ if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) {
1336
+ if ($trials < 0) {
1337
+ return PHPExcel_Calculation_Functions::NaN();
1338
+ }
1339
+ if (($probability < 0) || ($probability > 1)) {
1340
+ return PHPExcel_Calculation_Functions::NaN();
1341
+ }
1342
+ if (($alpha < 0) || ($alpha > 1)) {
1343
+ return PHPExcel_Calculation_Functions::NaN();
1344
+ }
1345
+ if ($alpha <= 0.5) {
1346
+ $t = sqrt(log(1 / ($alpha * $alpha)));
1347
+ $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));
1348
+ } else {
1349
+ $t = sqrt(log(1 / pow(1 - $alpha,2)));
1350
+ $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t);
1351
+ }
1352
+ $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability)));
1353
+ if ($Guess < 0) {
1354
+ $Guess = 0;
1355
+ } elseif ($Guess > $trials) {
1356
+ $Guess = $trials;
1357
+ }
1358
+
1359
+ $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0;
1360
+ $EssentiallyZero = 10e-12;
1361
+
1362
+ $m = floor($trials * $probability);
1363
+ ++$TotalUnscaledProbability;
1364
+ if ($m == $Guess) { ++$UnscaledPGuess; }
1365
+ if ($m <= $Guess) { ++$UnscaledCumPGuess; }
1366
+
1367
+ $PreviousValue = 1;
1368
+ $Done = False;
1369
+ $k = $m + 1;
1370
+ while ((!$Done) && ($k <= $trials)) {
1371
+ $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability));
1372
+ $TotalUnscaledProbability += $CurrentValue;
1373
+ if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; }
1374
+ if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; }
1375
+ if ($CurrentValue <= $EssentiallyZero) { $Done = True; }
1376
+ $PreviousValue = $CurrentValue;
1377
+ ++$k;
1378
+ }
1379
+
1380
+ $PreviousValue = 1;
1381
+ $Done = False;
1382
+ $k = $m - 1;
1383
+ while ((!$Done) && ($k >= 0)) {
1384
+ $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability);
1385
+ $TotalUnscaledProbability += $CurrentValue;
1386
+ if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; }
1387
+ if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; }
1388
+ if ($CurrentValue <= $EssentiallyZero) { $Done = True; }
1389
+ $PreviousValue = $CurrentValue;
1390
+ --$k;
1391
+ }
1392
+
1393
+ $PGuess = $UnscaledPGuess / $TotalUnscaledProbability;
1394
+ $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability;
1395
+
1396
+ // $CumPGuessMinus1 = $CumPGuess - $PGuess;
1397
+ $CumPGuessMinus1 = $CumPGuess - 1;
1398
+
1399
+ while (True) {
1400
+ if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) {
1401
+ return $Guess;
1402
+ } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) {
1403
+ $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability);
1404
+ $CumPGuessMinus1 = $CumPGuess;
1405
+ $CumPGuess = $CumPGuess + $PGuessPlus1;
1406
+ $PGuess = $PGuessPlus1;
1407
+ ++$Guess;
1408
+ } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) {
1409
+ $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability;
1410
+ $CumPGuess = $CumPGuessMinus1;
1411
+ $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess;
1412
+ $PGuess = $PGuessMinus1;
1413
+ --$Guess;
1414
+ }
1415
+ }
1416
+ }
1417
+ return PHPExcel_Calculation_Functions::VALUE();
1418
+ } // function CRITBINOM()
1419
+
1420
+
1421
+ /**
1422
+ * DEVSQ
1423
+ *
1424
+ * Returns the sum of squares of deviations of data points from their sample mean.
1425
+ *
1426
+ * Excel Function:
1427
+ * DEVSQ(value1[,value2[, ...]])
1428
+ *
1429
+ * @access public
1430
+ * @category Statistical Functions
1431
+ * @param mixed $arg,... Data values
1432
+ * @return float
1433
+ */
1434
+ public static function DEVSQ() {
1435
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1436
+
1437
+ // Return value
1438
+ $returnValue = null;
1439
+
1440
+ $aMean = self::AVERAGE($aArgs);
1441
+ if ($aMean != PHPExcel_Calculation_Functions::DIV0()) {
1442
+ $aCount = -1;
1443
+ foreach ($aArgs as $k => $arg) {
1444
+ // Is it a numeric value?
1445
+ if ((is_bool($arg)) &&
1446
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
1447
+ $arg = (integer) $arg;
1448
+ }
1449
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1450
+ if (is_null($returnValue)) {
1451
+ $returnValue = pow(($arg - $aMean),2);
1452
+ } else {
1453
+ $returnValue += pow(($arg - $aMean),2);
1454
+ }
1455
+ ++$aCount;
1456
+ }
1457
+ }
1458
+
1459
+ // Return
1460
+ if (is_null($returnValue)) {
1461
+ return PHPExcel_Calculation_Functions::NaN();
1462
+ } else {
1463
+ return $returnValue;
1464
+ }
1465
+ }
1466
+ return self::NA();
1467
+ } // function DEVSQ()
1468
+
1469
+
1470
+ /**
1471
+ * EXPONDIST
1472
+ *
1473
+ * Returns the exponential distribution. Use EXPONDIST to model the time between events,
1474
+ * such as how long an automated bank teller takes to deliver cash. For example, you can
1475
+ * use EXPONDIST to determine the probability that the process takes at most 1 minute.
1476
+ *
1477
+ * @param float $value Value of the function
1478
+ * @param float $lambda The parameter value
1479
+ * @param boolean $cumulative
1480
+ * @return float
1481
+ */
1482
+ public static function EXPONDIST($value, $lambda, $cumulative) {
1483
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1484
+ $lambda = PHPExcel_Calculation_Functions::flattenSingleValue($lambda);
1485
+ $cumulative = PHPExcel_Calculation_Functions::flattenSingleValue($cumulative);
1486
+
1487
+ if ((is_numeric($value)) && (is_numeric($lambda))) {
1488
+ if (($value < 0) || ($lambda < 0)) {
1489
+ return PHPExcel_Calculation_Functions::NaN();
1490
+ }
1491
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
1492
+ if ($cumulative) {
1493
+ return 1 - exp(0-$value*$lambda);
1494
+ } else {
1495
+ return $lambda * exp(0-$value*$lambda);
1496
+ }
1497
+ }
1498
+ }
1499
+ return PHPExcel_Calculation_Functions::VALUE();
1500
+ } // function EXPONDIST()
1501
+
1502
+
1503
+ /**
1504
+ * FISHER
1505
+ *
1506
+ * Returns the Fisher transformation at x. This transformation produces a function that
1507
+ * is normally distributed rather than skewed. Use this function to perform hypothesis
1508
+ * testing on the correlation coefficient.
1509
+ *
1510
+ * @param float $value
1511
+ * @return float
1512
+ */
1513
+ public static function FISHER($value) {
1514
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1515
+
1516
+ if (is_numeric($value)) {
1517
+ if (($value <= -1) || ($value >= 1)) {
1518
+ return PHPExcel_Calculation_Functions::NaN();
1519
+ }
1520
+ return 0.5 * log((1+$value)/(1-$value));
1521
+ }
1522
+ return PHPExcel_Calculation_Functions::VALUE();
1523
+ } // function FISHER()
1524
+
1525
+
1526
+ /**
1527
+ * FISHERINV
1528
+ *
1529
+ * Returns the inverse of the Fisher transformation. Use this transformation when
1530
+ * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then
1531
+ * FISHERINV(y) = x.
1532
+ *
1533
+ * @param float $value
1534
+ * @return float
1535
+ */
1536
+ public static function FISHERINV($value) {
1537
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1538
+
1539
+ if (is_numeric($value)) {
1540
+ return (exp(2 * $value) - 1) / (exp(2 * $value) + 1);
1541
+ }
1542
+ return PHPExcel_Calculation_Functions::VALUE();
1543
+ } // function FISHERINV()
1544
+
1545
+
1546
+ /**
1547
+ * FORECAST
1548
+ *
1549
+ * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value.
1550
+ *
1551
+ * @param float Value of X for which we want to find Y
1552
+ * @param array of mixed Data Series Y
1553
+ * @param array of mixed Data Series X
1554
+ * @return float
1555
+ */
1556
+ public static function FORECAST($xValue,$yValues,$xValues) {
1557
+ $xValue = PHPExcel_Calculation_Functions::flattenSingleValue($xValue);
1558
+ if (!is_numeric($xValue)) {
1559
+ return PHPExcel_Calculation_Functions::VALUE();
1560
+ }
1561
+
1562
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
1563
+ return PHPExcel_Calculation_Functions::VALUE();
1564
+ }
1565
+ $yValueCount = count($yValues);
1566
+ $xValueCount = count($xValues);
1567
+
1568
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1569
+ return PHPExcel_Calculation_Functions::NA();
1570
+ } elseif ($yValueCount == 1) {
1571
+ return PHPExcel_Calculation_Functions::DIV0();
1572
+ }
1573
+
1574
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
1575
+ return $bestFitLinear->getValueOfYForX($xValue);
1576
+ } // function FORECAST()
1577
+
1578
+
1579
+ /**
1580
+ * GAMMADIST
1581
+ *
1582
+ * Returns the gamma distribution.
1583
+ *
1584
+ * @param float $value Value at which you want to evaluate the distribution
1585
+ * @param float $a Parameter to the distribution
1586
+ * @param float $b Parameter to the distribution
1587
+ * @param boolean $cumulative
1588
+ * @return float
1589
+ *
1590
+ */
1591
+ public static function GAMMADIST($value,$a,$b,$cumulative) {
1592
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1593
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
1594
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
1595
+
1596
+ if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) {
1597
+ if (($value < 0) || ($a <= 0) || ($b <= 0)) {
1598
+ return PHPExcel_Calculation_Functions::NaN();
1599
+ }
1600
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
1601
+ if ($cumulative) {
1602
+ return self::_incompleteGamma($a,$value / $b) / self::_gamma($a);
1603
+ } else {
1604
+ return (1 / (pow($b,$a) * self::_gamma($a))) * pow($value,$a-1) * exp(0-($value / $b));
1605
+ }
1606
+ }
1607
+ }
1608
+ return PHPExcel_Calculation_Functions::VALUE();
1609
+ } // function GAMMADIST()
1610
+
1611
+
1612
+ /**
1613
+ * GAMMAINV
1614
+ *
1615
+ * Returns the inverse of the beta distribution.
1616
+ *
1617
+ * @param float $probability Probability at which you want to evaluate the distribution
1618
+ * @param float $alpha Parameter to the distribution
1619
+ * @param float $beta Parameter to the distribution
1620
+ * @return float
1621
+ *
1622
+ */
1623
+ public static function GAMMAINV($probability,$alpha,$beta) {
1624
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1625
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1626
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
1627
+
1628
+ if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) {
1629
+ if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) {
1630
+ return PHPExcel_Calculation_Functions::NaN();
1631
+ }
1632
+
1633
+ $xLo = 0;
1634
+ $xHi = $alpha * $beta * 5;
1635
+
1636
+ $x = $xNew = 1;
1637
+ $error = $pdf = 0;
1638
+ $dx = 1024;
1639
+ $i = 0;
1640
+
1641
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
1642
+ // Apply Newton-Raphson step
1643
+ $error = self::GAMMADIST($x, $alpha, $beta, True) - $probability;
1644
+ if ($error < 0.0) {
1645
+ $xLo = $x;
1646
+ } else {
1647
+ $xHi = $x;
1648
+ }
1649
+ $pdf = self::GAMMADIST($x, $alpha, $beta, False);
1650
+ // Avoid division by zero
1651
+ if ($pdf != 0.0) {
1652
+ $dx = $error / $pdf;
1653
+ $xNew = $x - $dx;
1654
+ }
1655
+ // If the NR fails to converge (which for example may be the
1656
+ // case if the initial guess is too rough) we apply a bisection
1657
+ // step to determine a more narrow interval around the root.
1658
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) {
1659
+ $xNew = ($xLo + $xHi) / 2;
1660
+ $dx = $xNew - $x;
1661
+ }
1662
+ $x = $xNew;
1663
+ }
1664
+ if ($i == MAX_ITERATIONS) {
1665
+ return PHPExcel_Calculation_Functions::NA();
1666
+ }
1667
+ return $x;
1668
+ }
1669
+ return PHPExcel_Calculation_Functions::VALUE();
1670
+ } // function GAMMAINV()
1671
+
1672
+
1673
+ /**
1674
+ * GAMMALN
1675
+ *
1676
+ * Returns the natural logarithm of the gamma function.
1677
+ *
1678
+ * @param float $value
1679
+ * @return float
1680
+ */
1681
+ public static function GAMMALN($value) {
1682
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1683
+
1684
+ if (is_numeric($value)) {
1685
+ if ($value <= 0) {
1686
+ return PHPExcel_Calculation_Functions::NaN();
1687
+ }
1688
+ return log(self::_gamma($value));
1689
+ }
1690
+ return PHPExcel_Calculation_Functions::VALUE();
1691
+ } // function GAMMALN()
1692
+
1693
+
1694
+ /**
1695
+ * GEOMEAN
1696
+ *
1697
+ * Returns the geometric mean of an array or range of positive data. For example, you
1698
+ * can use GEOMEAN to calculate average growth rate given compound interest with
1699
+ * variable rates.
1700
+ *
1701
+ * Excel Function:
1702
+ * GEOMEAN(value1[,value2[, ...]])
1703
+ *
1704
+ * @access public
1705
+ * @category Statistical Functions
1706
+ * @param mixed $arg,... Data values
1707
+ * @return float
1708
+ */
1709
+ public static function GEOMEAN() {
1710
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1711
+
1712
+ $aMean = PHPExcel_Calculation_MathTrig::PRODUCT($aArgs);
1713
+ if (is_numeric($aMean) && ($aMean > 0)) {
1714
+ $aCount = self::COUNT($aArgs) ;
1715
+ if (self::MIN($aArgs) > 0) {
1716
+ return pow($aMean, (1 / $aCount));
1717
+ }
1718
+ }
1719
+ return PHPExcel_Calculation_Functions::NaN();
1720
+ } // GEOMEAN()
1721
+
1722
+
1723
+ /**
1724
+ * GROWTH
1725
+ *
1726
+ * Returns values along a predicted emponential trend
1727
+ *
1728
+ * @param array of mixed Data Series Y
1729
+ * @param array of mixed Data Series X
1730
+ * @param array of mixed Values of X for which we want to find Y
1731
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
1732
+ * @return array of float
1733
+ */
1734
+ public static function GROWTH($yValues,$xValues=array(),$newValues=array(),$const=True) {
1735
+ $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues);
1736
+ $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues);
1737
+ $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues);
1738
+ $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
1739
+
1740
+ $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const);
1741
+ if (empty($newValues)) {
1742
+ $newValues = $bestFitExponential->getXValues();
1743
+ }
1744
+
1745
+ $returnArray = array();
1746
+ foreach($newValues as $xValue) {
1747
+ $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue);
1748
+ }
1749
+
1750
+ return $returnArray;
1751
+ } // function GROWTH()
1752
+
1753
+
1754
+ /**
1755
+ * HARMEAN
1756
+ *
1757
+ * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the
1758
+ * arithmetic mean of reciprocals.
1759
+ *
1760
+ * Excel Function:
1761
+ * HARMEAN(value1[,value2[, ...]])
1762
+ *
1763
+ * @access public
1764
+ * @category Statistical Functions
1765
+ * @param mixed $arg,... Data values
1766
+ * @return float
1767
+ */
1768
+ public static function HARMEAN() {
1769
+ // Return value
1770
+ $returnValue = PHPExcel_Calculation_Functions::NA();
1771
+
1772
+ // Loop through arguments
1773
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1774
+ if (self::MIN($aArgs) < 0) {
1775
+ return PHPExcel_Calculation_Functions::NaN();
1776
+ }
1777
+ $aCount = 0;
1778
+ foreach ($aArgs as $arg) {
1779
+ // Is it a numeric value?
1780
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1781
+ if ($arg <= 0) {
1782
+ return PHPExcel_Calculation_Functions::NaN();
1783
+ }
1784
+ if (is_null($returnValue)) {
1785
+ $returnValue = (1 / $arg);
1786
+ } else {
1787
+ $returnValue += (1 / $arg);
1788
+ }
1789
+ ++$aCount;
1790
+ }
1791
+ }
1792
+
1793
+ // Return
1794
+ if ($aCount > 0) {
1795
+ return 1 / ($returnValue / $aCount);
1796
+ } else {
1797
+ return $returnValue;
1798
+ }
1799
+ } // function HARMEAN()
1800
+
1801
+
1802
+ /**
1803
+ * HYPGEOMDIST
1804
+ *
1805
+ * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of
1806
+ * sample successes, given the sample size, population successes, and population size.
1807
+ *
1808
+ * @param float $sampleSuccesses Number of successes in the sample
1809
+ * @param float $sampleNumber Size of the sample
1810
+ * @param float $populationSuccesses Number of successes in the population
1811
+ * @param float $populationNumber Population size
1812
+ * @return float
1813
+ *
1814
+ */
1815
+ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) {
1816
+ $sampleSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleSuccesses));
1817
+ $sampleNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleNumber));
1818
+ $populationSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationSuccesses));
1819
+ $populationNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationNumber));
1820
+
1821
+ if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) {
1822
+ if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
1823
+ return PHPExcel_Calculation_Functions::NaN();
1824
+ }
1825
+ if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
1826
+ return PHPExcel_Calculation_Functions::NaN();
1827
+ }
1828
+ if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
1829
+ return PHPExcel_Calculation_Functions::NaN();
1830
+ }
1831
+ return PHPExcel_Calculation_MathTrig::COMBIN($populationSuccesses,$sampleSuccesses) *
1832
+ PHPExcel_Calculation_MathTrig::COMBIN($populationNumber - $populationSuccesses,$sampleNumber - $sampleSuccesses) /
1833
+ PHPExcel_Calculation_MathTrig::COMBIN($populationNumber,$sampleNumber);
1834
+ }
1835
+ return PHPExcel_Calculation_Functions::VALUE();
1836
+ } // function HYPGEOMDIST()
1837
+
1838
+
1839
+ /**
1840
+ * INTERCEPT
1841
+ *
1842
+ * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values.
1843
+ *
1844
+ * @param array of mixed Data Series Y
1845
+ * @param array of mixed Data Series X
1846
+ * @return float
1847
+ */
1848
+ public static function INTERCEPT($yValues,$xValues) {
1849
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
1850
+ return PHPExcel_Calculation_Functions::VALUE();
1851
+ }
1852
+ $yValueCount = count($yValues);
1853
+ $xValueCount = count($xValues);
1854
+
1855
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1856
+ return PHPExcel_Calculation_Functions::NA();
1857
+ } elseif ($yValueCount == 1) {
1858
+ return PHPExcel_Calculation_Functions::DIV0();
1859
+ }
1860
+
1861
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
1862
+ return $bestFitLinear->getIntersect();
1863
+ } // function INTERCEPT()
1864
+
1865
+
1866
+ /**
1867
+ * KURT
1868
+ *
1869
+ * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness
1870
+ * or flatness of a distribution compared with the normal distribution. Positive
1871
+ * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a
1872
+ * relatively flat distribution.
1873
+ *
1874
+ * @param array Data Series
1875
+ * @return float
1876
+ */
1877
+ public static function KURT() {
1878
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1879
+ $mean = self::AVERAGE($aArgs);
1880
+ $stdDev = self::STDEV($aArgs);
1881
+
1882
+ if ($stdDev > 0) {
1883
+ $count = $summer = 0;
1884
+ // Loop through arguments
1885
+ foreach ($aArgs as $k => $arg) {
1886
+ if ((is_bool($arg)) &&
1887
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
1888
+ } else {
1889
+ // Is it a numeric value?
1890
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1891
+ $summer += pow((($arg - $mean) / $stdDev),4) ;
1892
+ ++$count;
1893
+ }
1894
+ }
1895
+ }
1896
+
1897
+ // Return
1898
+ if ($count > 3) {
1899
+ return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1,2) / (($count-2) * ($count-3)));
1900
+ }
1901
+ }
1902
+ return PHPExcel_Calculation_Functions::DIV0();
1903
+ } // function KURT()
1904
+
1905
+
1906
+ /**
1907
+ * LARGE
1908
+ *
1909
+ * Returns the nth largest value in a data set. You can use this function to
1910
+ * select a value based on its relative standing.
1911
+ *
1912
+ * Excel Function:
1913
+ * LARGE(value1[,value2[, ...]],entry)
1914
+ *
1915
+ * @access public
1916
+ * @category Statistical Functions
1917
+ * @param mixed $arg,... Data values
1918
+ * @param int $entry Position (ordered from the largest) in the array or range of data to return
1919
+ * @return float
1920
+ *
1921
+ */
1922
+ public static function LARGE() {
1923
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1924
+
1925
+ // Calculate
1926
+ $entry = floor(array_pop($aArgs));
1927
+
1928
+ if ((is_numeric($entry)) && (!is_string($entry))) {
1929
+ $mArgs = array();
1930
+ foreach ($aArgs as $arg) {
1931
+ // Is it a numeric value?
1932
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1933
+ $mArgs[] = $arg;
1934
+ }
1935
+ }
1936
+ $count = self::COUNT($mArgs);
1937
+ $entry = floor(--$entry);
1938
+ if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
1939
+ return PHPExcel_Calculation_Functions::NaN();
1940
+ }
1941
+ rsort($mArgs);
1942
+ return $mArgs[$entry];
1943
+ }
1944
+ return PHPExcel_Calculation_Functions::VALUE();
1945
+ } // function LARGE()
1946
+
1947
+
1948
+ /**
1949
+ * LINEST
1950
+ *
1951
+ * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data,
1952
+ * and then returns an array that describes the line.
1953
+ *
1954
+ * @param array of mixed Data Series Y
1955
+ * @param array of mixed Data Series X
1956
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
1957
+ * @param boolean A logical value specifying whether to return additional regression statistics.
1958
+ * @return array
1959
+ */
1960
+ public static function LINEST($yValues, $xValues = NULL, $const = TRUE, $stats = FALSE) {
1961
+ $const = (is_null($const)) ? TRUE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
1962
+ $stats = (is_null($stats)) ? FALSE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats);
1963
+ if (is_null($xValues)) $xValues = range(1,count(PHPExcel_Calculation_Functions::flattenArray($yValues)));
1964
+
1965
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
1966
+ return PHPExcel_Calculation_Functions::VALUE();
1967
+ }
1968
+ $yValueCount = count($yValues);
1969
+ $xValueCount = count($xValues);
1970
+
1971
+
1972
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1973
+ return PHPExcel_Calculation_Functions::NA();
1974
+ } elseif ($yValueCount == 1) {
1975
+ return 0;
1976
+ }
1977
+
1978
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const);
1979
+ if ($stats) {
1980
+ return array( array( $bestFitLinear->getSlope(),
1981
+ $bestFitLinear->getSlopeSE(),
1982
+ $bestFitLinear->getGoodnessOfFit(),
1983
+ $bestFitLinear->getF(),
1984
+ $bestFitLinear->getSSRegression(),
1985
+ ),
1986
+ array( $bestFitLinear->getIntersect(),
1987
+ $bestFitLinear->getIntersectSE(),
1988
+ $bestFitLinear->getStdevOfResiduals(),
1989
+ $bestFitLinear->getDFResiduals(),
1990
+ $bestFitLinear->getSSResiduals()
1991
+ )
1992
+ );
1993
+ } else {
1994
+ return array( $bestFitLinear->getSlope(),
1995
+ $bestFitLinear->getIntersect()
1996
+ );
1997
+ }
1998
+ } // function LINEST()
1999
+
2000
+
2001
+ /**
2002
+ * LOGEST
2003
+ *
2004
+ * Calculates an exponential curve that best fits the X and Y data series,
2005
+ * and then returns an array that describes the line.
2006
+ *
2007
+ * @param array of mixed Data Series Y
2008
+ * @param array of mixed Data Series X
2009
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
2010
+ * @param boolean A logical value specifying whether to return additional regression statistics.
2011
+ * @return array
2012
+ */
2013
+ public static function LOGEST($yValues,$xValues=null,$const=True,$stats=False) {
2014
+ $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
2015
+ $stats = (is_null($stats)) ? False : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats);
2016
+ if (is_null($xValues)) $xValues = range(1,count(PHPExcel_Calculation_Functions::flattenArray($yValues)));
2017
+
2018
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
2019
+ return PHPExcel_Calculation_Functions::VALUE();
2020
+ }
2021
+ $yValueCount = count($yValues);
2022
+ $xValueCount = count($xValues);
2023
+
2024
+ foreach($yValues as $value) {
2025
+ if ($value <= 0.0) {
2026
+ return PHPExcel_Calculation_Functions::NaN();
2027
+ }
2028
+ }
2029
+
2030
+
2031
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2032
+ return PHPExcel_Calculation_Functions::NA();
2033
+ } elseif ($yValueCount == 1) {
2034
+ return 1;
2035
+ }
2036
+
2037
+ $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const);
2038
+ if ($stats) {
2039
+ return array( array( $bestFitExponential->getSlope(),
2040
+ $bestFitExponential->getSlopeSE(),
2041
+ $bestFitExponential->getGoodnessOfFit(),
2042
+ $bestFitExponential->getF(),
2043
+ $bestFitExponential->getSSRegression(),
2044
+ ),
2045
+ array( $bestFitExponential->getIntersect(),
2046
+ $bestFitExponential->getIntersectSE(),
2047
+ $bestFitExponential->getStdevOfResiduals(),
2048
+ $bestFitExponential->getDFResiduals(),
2049
+ $bestFitExponential->getSSResiduals()
2050
+ )
2051
+ );
2052
+ } else {
2053
+ return array( $bestFitExponential->getSlope(),
2054
+ $bestFitExponential->getIntersect()
2055
+ );
2056
+ }
2057
+ } // function LOGEST()
2058
+
2059
+
2060
+ /**
2061
+ * LOGINV
2062
+ *
2063
+ * Returns the inverse of the normal cumulative distribution
2064
+ *
2065
+ * @param float $probability
2066
+ * @param float $mean
2067
+ * @param float $stdDev
2068
+ * @return float
2069
+ *
2070
+ * @todo Try implementing P J Acklam's refinement algorithm for greater
2071
+ * accuracy if I can get my head round the mathematics
2072
+ * (as described at) http://home.online.no/~pjacklam/notes/invnorm/
2073
+ */
2074
+ public static function LOGINV($probability, $mean, $stdDev) {
2075
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2076
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2077
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2078
+
2079
+ if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2080
+ if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) {
2081
+ return PHPExcel_Calculation_Functions::NaN();
2082
+ }
2083
+ return exp($mean + $stdDev * self::NORMSINV($probability));
2084
+ }
2085
+ return PHPExcel_Calculation_Functions::VALUE();
2086
+ } // function LOGINV()
2087
+
2088
+
2089
+ /**
2090
+ * LOGNORMDIST
2091
+ *
2092
+ * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed
2093
+ * with parameters mean and standard_dev.
2094
+ *
2095
+ * @param float $value
2096
+ * @param float $mean
2097
+ * @param float $stdDev
2098
+ * @return float
2099
+ */
2100
+ public static function LOGNORMDIST($value, $mean, $stdDev) {
2101
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2102
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2103
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2104
+
2105
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2106
+ if (($value <= 0) || ($stdDev <= 0)) {
2107
+ return PHPExcel_Calculation_Functions::NaN();
2108
+ }
2109
+ return self::NORMSDIST((log($value) - $mean) / $stdDev);
2110
+ }
2111
+ return PHPExcel_Calculation_Functions::VALUE();
2112
+ } // function LOGNORMDIST()
2113
+
2114
+
2115
+ /**
2116
+ * MAX
2117
+ *
2118
+ * MAX returns the value of the element of the values passed that has the highest value,
2119
+ * with negative numbers considered smaller than positive numbers.
2120
+ *
2121
+ * Excel Function:
2122
+ * MAX(value1[,value2[, ...]])
2123
+ *
2124
+ * @access public
2125
+ * @category Statistical Functions
2126
+ * @param mixed $arg,... Data values
2127
+ * @return float
2128
+ */
2129
+ public static function MAX() {
2130
+ // Return value
2131
+ $returnValue = null;
2132
+
2133
+ // Loop through arguments
2134
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2135
+ foreach ($aArgs as $arg) {
2136
+ // Is it a numeric value?
2137
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2138
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2139
+ $returnValue = $arg;
2140
+ }
2141
+ }
2142
+ }
2143
+
2144
+ // Return
2145
+ if(is_null($returnValue)) {
2146
+ return 0;
2147
+ }
2148
+ return $returnValue;
2149
+ } // function MAX()
2150
+
2151
+
2152
+ /**
2153
+ * MAXA
2154
+ *
2155
+ * Returns the greatest value in a list of arguments, including numbers, text, and logical values
2156
+ *
2157
+ * Excel Function:
2158
+ * MAXA(value1[,value2[, ...]])
2159
+ *
2160
+ * @access public
2161
+ * @category Statistical Functions
2162
+ * @param mixed $arg,... Data values
2163
+ * @return float
2164
+ */
2165
+ public static function MAXA() {
2166
+ // Return value
2167
+ $returnValue = null;
2168
+
2169
+ // Loop through arguments
2170
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2171
+ foreach ($aArgs as $arg) {
2172
+ // Is it a numeric value?
2173
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
2174
+ if (is_bool($arg)) {
2175
+ $arg = (integer) $arg;
2176
+ } elseif (is_string($arg)) {
2177
+ $arg = 0;
2178
+ }
2179
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2180
+ $returnValue = $arg;
2181
+ }
2182
+ }
2183
+ }
2184
+
2185
+ // Return
2186
+ if(is_null($returnValue)) {
2187
+ return 0;
2188
+ }
2189
+ return $returnValue;
2190
+ } // function MAXA()
2191
+
2192
+
2193
+ /**
2194
+ * MAXIF
2195
+ *
2196
+ * Counts the maximum value within a range of cells that contain numbers within the list of arguments
2197
+ *
2198
+ * Excel Function:
2199
+ * MAXIF(value1[,value2[, ...]],condition)
2200
+ *
2201
+ * @access public
2202
+ * @category Mathematical and Trigonometric Functions
2203
+ * @param mixed $arg,... Data values
2204
+ * @param string $condition The criteria that defines which cells will be checked.
2205
+ * @return float
2206
+ */
2207
+ public static function MAXIF($aArgs,$condition,$sumArgs = array()) {
2208
+ // Return value
2209
+ $returnValue = null;
2210
+
2211
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
2212
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
2213
+ if (empty($sumArgs)) {
2214
+ $sumArgs = $aArgs;
2215
+ }
2216
+ $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
2217
+ // Loop through arguments
2218
+ foreach ($aArgs as $key => $arg) {
2219
+ if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
2220
+ $testCondition = '='.$arg.$condition;
2221
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
2222
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2223
+ $returnValue = $arg;
2224
+ }
2225
+ }
2226
+ }
2227
+
2228
+ // Return
2229
+ return $returnValue;
2230
+ } // function MAXIF()
2231
+
2232
+
2233
+ /**
2234
+ * MEDIAN
2235
+ *
2236
+ * Returns the median of the given numbers. The median is the number in the middle of a set of numbers.
2237
+ *
2238
+ * Excel Function:
2239
+ * MEDIAN(value1[,value2[, ...]])
2240
+ *
2241
+ * @access public
2242
+ * @category Statistical Functions
2243
+ * @param mixed $arg,... Data values
2244
+ * @return float
2245
+ */
2246
+ public static function MEDIAN() {
2247
+ // Return value
2248
+ $returnValue = PHPExcel_Calculation_Functions::NaN();
2249
+
2250
+ $mArgs = array();
2251
+ // Loop through arguments
2252
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2253
+ foreach ($aArgs as $arg) {
2254
+ // Is it a numeric value?
2255
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2256
+ $mArgs[] = $arg;
2257
+ }
2258
+ }
2259
+
2260
+ $mValueCount = count($mArgs);
2261
+ if ($mValueCount > 0) {
2262
+ sort($mArgs,SORT_NUMERIC);
2263
+ $mValueCount = $mValueCount / 2;
2264
+ if ($mValueCount == floor($mValueCount)) {
2265
+ $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2;
2266
+ } else {
2267
+ $mValueCount == floor($mValueCount);
2268
+ $returnValue = $mArgs[$mValueCount];
2269
+ }
2270
+ }
2271
+
2272
+ // Return
2273
+ return $returnValue;
2274
+ } // function MEDIAN()
2275
+
2276
+
2277
+ /**
2278
+ * MIN
2279
+ *
2280
+ * MIN returns the value of the element of the values passed that has the smallest value,
2281
+ * with negative numbers considered smaller than positive numbers.
2282
+ *
2283
+ * Excel Function:
2284
+ * MIN(value1[,value2[, ...]])
2285
+ *
2286
+ * @access public
2287
+ * @category Statistical Functions
2288
+ * @param mixed $arg,... Data values
2289
+ * @return float
2290
+ */
2291
+ public static function MIN() {
2292
+ // Return value
2293
+ $returnValue = null;
2294
+
2295
+ // Loop through arguments
2296
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2297
+ foreach ($aArgs as $arg) {
2298
+ // Is it a numeric value?
2299
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2300
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2301
+ $returnValue = $arg;
2302
+ }
2303
+ }
2304
+ }
2305
+
2306
+ // Return
2307
+ if(is_null($returnValue)) {
2308
+ return 0;
2309
+ }
2310
+ return $returnValue;
2311
+ } // function MIN()
2312
+
2313
+
2314
+ /**
2315
+ * MINA
2316
+ *
2317
+ * Returns the smallest value in a list of arguments, including numbers, text, and logical values
2318
+ *
2319
+ * Excel Function:
2320
+ * MINA(value1[,value2[, ...]])
2321
+ *
2322
+ * @access public
2323
+ * @category Statistical Functions
2324
+ * @param mixed $arg,... Data values
2325
+ * @return float
2326
+ */
2327
+ public static function MINA() {
2328
+ // Return value
2329
+ $returnValue = null;
2330
+
2331
+ // Loop through arguments
2332
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2333
+ foreach ($aArgs as $arg) {
2334
+ // Is it a numeric value?
2335
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
2336
+ if (is_bool($arg)) {
2337
+ $arg = (integer) $arg;
2338
+ } elseif (is_string($arg)) {
2339
+ $arg = 0;
2340
+ }
2341
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2342
+ $returnValue = $arg;
2343
+ }
2344
+ }
2345
+ }
2346
+
2347
+ // Return
2348
+ if(is_null($returnValue)) {
2349
+ return 0;
2350
+ }
2351
+ return $returnValue;
2352
+ } // function MINA()
2353
+
2354
+
2355
+ /**
2356
+ * MINIF
2357
+ *
2358
+ * Returns the minimum value within a range of cells that contain numbers within the list of arguments
2359
+ *
2360
+ * Excel Function:
2361
+ * MINIF(value1[,value2[, ...]],condition)
2362
+ *
2363
+ * @access public
2364
+ * @category Mathematical and Trigonometric Functions
2365
+ * @param mixed $arg,... Data values
2366
+ * @param string $condition The criteria that defines which cells will be checked.
2367
+ * @return float
2368
+ */
2369
+ public static function MINIF($aArgs,$condition,$sumArgs = array()) {
2370
+ // Return value
2371
+ $returnValue = null;
2372
+
2373
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
2374
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
2375
+ if (empty($sumArgs)) {
2376
+ $sumArgs = $aArgs;
2377
+ }
2378
+ $condition = PHPExcel_Calculation_Functions::_ifCondition($condition);
2379
+ // Loop through arguments
2380
+ foreach ($aArgs as $key => $arg) {
2381
+ if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
2382
+ $testCondition = '='.$arg.$condition;
2383
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
2384
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2385
+ $returnValue = $arg;
2386
+ }
2387
+ }
2388
+ }
2389
+
2390
+ // Return
2391
+ return $returnValue;
2392
+ } // function MINIF()
2393
+
2394
+
2395
+ //
2396
+ // Special variant of array_count_values that isn't limited to strings and integers,
2397
+ // but can work with floating point numbers as values
2398
+ //
2399
+ private static function _modeCalc($data) {
2400
+ $frequencyArray = array();
2401
+ foreach($data as $datum) {
2402
+ $found = False;
2403
+ foreach($frequencyArray as $key => $value) {
2404
+ if ((string) $value['value'] == (string) $datum) {
2405
+ ++$frequencyArray[$key]['frequency'];
2406
+ $found = True;
2407
+ break;
2408
+ }
2409
+ }
2410
+ if (!$found) {
2411
+ $frequencyArray[] = array('value' => $datum,
2412
+ 'frequency' => 1 );
2413
+ }
2414
+ }
2415
+
2416
+ foreach($frequencyArray as $key => $value) {
2417
+ $frequencyList[$key] = $value['frequency'];
2418
+ $valueList[$key] = $value['value'];
2419
+ }
2420
+ array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray);
2421
+
2422
+ if ($frequencyArray[0]['frequency'] == 1) {
2423
+ return PHPExcel_Calculation_Functions::NA();
2424
+ }
2425
+ return $frequencyArray[0]['value'];
2426
+ } // function _modeCalc()
2427
+
2428
+
2429
+ /**
2430
+ * MODE
2431
+ *
2432
+ * Returns the most frequently occurring, or repetitive, value in an array or range of data
2433
+ *
2434
+ * Excel Function:
2435
+ * MODE(value1[,value2[, ...]])
2436
+ *
2437
+ * @access public
2438
+ * @category Statistical Functions
2439
+ * @param mixed $arg,... Data values
2440
+ * @return float
2441
+ */
2442
+ public static function MODE() {
2443
+ // Return value
2444
+ $returnValue = PHPExcel_Calculation_Functions::NA();
2445
+
2446
+ // Loop through arguments
2447
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2448
+
2449
+ $mArgs = array();
2450
+ foreach ($aArgs as $arg) {
2451
+ // Is it a numeric value?
2452
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2453
+ $mArgs[] = $arg;
2454
+ }
2455
+ }
2456
+
2457
+ if (!empty($mArgs)) {
2458
+ return self::_modeCalc($mArgs);
2459
+ }
2460
+
2461
+ // Return
2462
+ return $returnValue;
2463
+ } // function MODE()
2464
+
2465
+
2466
+ /**
2467
+ * NEGBINOMDIST
2468
+ *
2469
+ * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that
2470
+ * there will be number_f failures before the number_s-th success, when the constant
2471
+ * probability of a success is probability_s. This function is similar to the binomial
2472
+ * distribution, except that the number of successes is fixed, and the number of trials is
2473
+ * variable. Like the binomial, trials are assumed to be independent.
2474
+ *
2475
+ * @param float $failures Number of Failures
2476
+ * @param float $successes Threshold number of Successes
2477
+ * @param float $probability Probability of success on each trial
2478
+ * @return float
2479
+ *
2480
+ */
2481
+ public static function NEGBINOMDIST($failures, $successes, $probability) {
2482
+ $failures = floor(PHPExcel_Calculation_Functions::flattenSingleValue($failures));
2483
+ $successes = floor(PHPExcel_Calculation_Functions::flattenSingleValue($successes));
2484
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2485
+
2486
+ if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) {
2487
+ if (($failures < 0) || ($successes < 1)) {
2488
+ return PHPExcel_Calculation_Functions::NaN();
2489
+ }
2490
+ if (($probability < 0) || ($probability > 1)) {
2491
+ return PHPExcel_Calculation_Functions::NaN();
2492
+ }
2493
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
2494
+ if (($failures + $successes - 1) <= 0) {
2495
+ return PHPExcel_Calculation_Functions::NaN();
2496
+ }
2497
+ }
2498
+ return (PHPExcel_Calculation_MathTrig::COMBIN($failures + $successes - 1,$successes - 1)) * (pow($probability,$successes)) * (pow(1 - $probability,$failures)) ;
2499
+ }
2500
+ return PHPExcel_Calculation_Functions::VALUE();
2501
+ } // function NEGBINOMDIST()
2502
+
2503
+
2504
+ /**
2505
+ * NORMDIST
2506
+ *
2507
+ * Returns the normal distribution for the specified mean and standard deviation. This
2508
+ * function has a very wide range of applications in statistics, including hypothesis
2509
+ * testing.
2510
+ *
2511
+ * @param float $value
2512
+ * @param float $mean Mean Value
2513
+ * @param float $stdDev Standard Deviation
2514
+ * @param boolean $cumulative
2515
+ * @return float
2516
+ *
2517
+ */
2518
+ public static function NORMDIST($value, $mean, $stdDev, $cumulative) {
2519
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2520
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2521
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2522
+
2523
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2524
+ if ($stdDev < 0) {
2525
+ return PHPExcel_Calculation_Functions::NaN();
2526
+ }
2527
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
2528
+ if ($cumulative) {
2529
+ return 0.5 * (1 + PHPExcel_Calculation_Engineering::_erfVal(($value - $mean) / ($stdDev * sqrt(2))));
2530
+ } else {
2531
+ return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean,2) / (2 * ($stdDev * $stdDev))));
2532
+ }
2533
+ }
2534
+ }
2535
+ return PHPExcel_Calculation_Functions::VALUE();
2536
+ } // function NORMDIST()
2537
+
2538
+
2539
+ /**
2540
+ * NORMINV
2541
+ *
2542
+ * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
2543
+ *
2544
+ * @param float $value
2545
+ * @param float $mean Mean Value
2546
+ * @param float $stdDev Standard Deviation
2547
+ * @return float
2548
+ *
2549
+ */
2550
+ public static function NORMINV($probability,$mean,$stdDev) {
2551
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2552
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2553
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2554
+
2555
+ if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2556
+ if (($probability < 0) || ($probability > 1)) {
2557
+ return PHPExcel_Calculation_Functions::NaN();
2558
+ }
2559
+ if ($stdDev < 0) {
2560
+ return PHPExcel_Calculation_Functions::NaN();
2561
+ }
2562
+ return (self::_inverse_ncdf($probability) * $stdDev) + $mean;
2563
+ }
2564
+ return PHPExcel_Calculation_Functions::VALUE();
2565
+ } // function NORMINV()
2566
+
2567
+
2568
+ /**
2569
+ * NORMSDIST
2570
+ *
2571
+ * Returns the standard normal cumulative distribution function. The distribution has
2572
+ * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
2573
+ * table of standard normal curve areas.
2574
+ *
2575
+ * @param float $value
2576
+ * @return float
2577
+ */
2578
+ public static function NORMSDIST($value) {
2579
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2580
+
2581
+ return self::NORMDIST($value, 0, 1, True);
2582
+ } // function NORMSDIST()
2583
+
2584
+
2585
+ /**
2586
+ * NORMSINV
2587
+ *
2588
+ * Returns the inverse of the standard normal cumulative distribution
2589
+ *
2590
+ * @param float $value
2591
+ * @return float
2592
+ */
2593
+ public static function NORMSINV($value) {
2594
+ return self::NORMINV($value, 0, 1);
2595
+ } // function NORMSINV()
2596
+
2597
+
2598
+ /**
2599
+ * PERCENTILE
2600
+ *
2601
+ * Returns the nth percentile of values in a range..
2602
+ *
2603
+ * Excel Function:
2604
+ * PERCENTILE(value1[,value2[, ...]],entry)
2605
+ *
2606
+ * @access public
2607
+ * @category Statistical Functions
2608
+ * @param mixed $arg,... Data values
2609
+ * @param float $entry Percentile value in the range 0..1, inclusive.
2610
+ * @return float
2611
+ */
2612
+ public static function PERCENTILE() {
2613
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2614
+
2615
+ // Calculate
2616
+ $entry = array_pop($aArgs);
2617
+
2618
+ if ((is_numeric($entry)) && (!is_string($entry))) {
2619
+ if (($entry < 0) || ($entry > 1)) {
2620
+ return PHPExcel_Calculation_Functions::NaN();
2621
+ }
2622
+ $mArgs = array();
2623
+ foreach ($aArgs as $arg) {
2624
+ // Is it a numeric value?
2625
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2626
+ $mArgs[] = $arg;
2627
+ }
2628
+ }
2629
+ $mValueCount = count($mArgs);
2630
+ if ($mValueCount > 0) {
2631
+ sort($mArgs);
2632
+ $count = self::COUNT($mArgs);
2633
+ $index = $entry * ($count-1);
2634
+ $iBase = floor($index);
2635
+ if ($index == $iBase) {
2636
+ return $mArgs[$index];
2637
+ } else {
2638
+ $iNext = $iBase + 1;
2639
+ $iProportion = $index - $iBase;
2640
+ return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ;
2641
+ }
2642
+ }
2643
+ }
2644
+ return PHPExcel_Calculation_Functions::VALUE();
2645
+ } // function PERCENTILE()
2646
+
2647
+
2648
+ /**
2649
+ * PERCENTRANK
2650
+ *
2651
+ * Returns the rank of a value in a data set as a percentage of the data set.
2652
+ *
2653
+ * @param array of number An array of, or a reference to, a list of numbers.
2654
+ * @param number The number whose rank you want to find.
2655
+ * @param number The number of significant digits for the returned percentage value.
2656
+ * @return float
2657
+ */
2658
+ public static function PERCENTRANK($valueSet,$value,$significance=3) {
2659
+ $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet);
2660
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2661
+ $significance = (is_null($significance)) ? 3 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($significance);
2662
+
2663
+ foreach($valueSet as $key => $valueEntry) {
2664
+ if (!is_numeric($valueEntry)) {
2665
+ unset($valueSet[$key]);
2666
+ }
2667
+ }
2668
+ sort($valueSet,SORT_NUMERIC);
2669
+ $valueCount = count($valueSet);
2670
+ if ($valueCount == 0) {
2671
+ return PHPExcel_Calculation_Functions::NaN();
2672
+ }
2673
+
2674
+ $valueAdjustor = $valueCount - 1;
2675
+ if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
2676
+ return PHPExcel_Calculation_Functions::NA();
2677
+ }
2678
+
2679
+ $pos = array_search($value,$valueSet);
2680
+ if ($pos === False) {
2681
+ $pos = 0;
2682
+ $testValue = $valueSet[0];
2683
+ while ($testValue < $value) {
2684
+ $testValue = $valueSet[++$pos];
2685
+ }
2686
+ --$pos;
2687
+ $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos]));
2688
+ }
2689
+
2690
+ return round($pos / $valueAdjustor,$significance);
2691
+ } // function PERCENTRANK()
2692
+
2693
+
2694
+ /**
2695
+ * PERMUT
2696
+ *
2697
+ * Returns the number of permutations for a given number of objects that can be
2698
+ * selected from number objects. A permutation is any set or subset of objects or
2699
+ * events where internal order is significant. Permutations are different from
2700
+ * combinations, for which the internal order is not significant. Use this function
2701
+ * for lottery-style probability calculations.
2702
+ *
2703
+ * @param int $numObjs Number of different objects
2704
+ * @param int $numInSet Number of objects in each permutation
2705
+ * @return int Number of permutations
2706
+ */
2707
+ public static function PERMUT($numObjs,$numInSet) {
2708
+ $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
2709
+ $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
2710
+
2711
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
2712
+ $numInSet = floor($numInSet);
2713
+ if ($numObjs < $numInSet) {
2714
+ return PHPExcel_Calculation_Functions::NaN();
2715
+ }
2716
+ return round(PHPExcel_Calculation_MathTrig::FACT($numObjs) / PHPExcel_Calculation_MathTrig::FACT($numObjs - $numInSet));
2717
+ }
2718
+ return PHPExcel_Calculation_Functions::VALUE();
2719
+ } // function PERMUT()
2720
+
2721
+
2722
+ /**
2723
+ * POISSON
2724
+ *
2725
+ * Returns the Poisson distribution. A common application of the Poisson distribution
2726
+ * is predicting the number of events over a specific time, such as the number of
2727
+ * cars arriving at a toll plaza in 1 minute.
2728
+ *
2729
+ * @param float $value
2730
+ * @param float $mean Mean Value
2731
+ * @param boolean $cumulative
2732
+ * @return float
2733
+ *
2734
+ */
2735
+ public static function POISSON($value, $mean, $cumulative) {
2736
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2737
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2738
+
2739
+ if ((is_numeric($value)) && (is_numeric($mean))) {
2740
+ if (($value < 0) || ($mean <= 0)) {
2741
+ return PHPExcel_Calculation_Functions::NaN();
2742
+ }
2743
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
2744
+ if ($cumulative) {
2745
+ $summer = 0;
2746
+ for ($i = 0; $i <= floor($value); ++$i) {
2747
+ $summer += pow($mean,$i) / PHPExcel_Calculation_MathTrig::FACT($i);
2748
+ }
2749
+ return exp(0-$mean) * $summer;
2750
+ } else {
2751
+ return (exp(0-$mean) * pow($mean,$value)) / PHPExcel_Calculation_MathTrig::FACT($value);
2752
+ }
2753
+ }
2754
+ }
2755
+ return PHPExcel_Calculation_Functions::VALUE();
2756
+ } // function POISSON()
2757
+
2758
+
2759
+ /**
2760
+ * QUARTILE
2761
+ *
2762
+ * Returns the quartile of a data set.
2763
+ *
2764
+ * Excel Function:
2765
+ * QUARTILE(value1[,value2[, ...]],entry)
2766
+ *
2767
+ * @access public
2768
+ * @category Statistical Functions
2769
+ * @param mixed $arg,... Data values
2770
+ * @param int $entry Quartile value in the range 1..3, inclusive.
2771
+ * @return float
2772
+ */
2773
+ public static function QUARTILE() {
2774
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2775
+
2776
+ // Calculate
2777
+ $entry = floor(array_pop($aArgs));
2778
+
2779
+ if ((is_numeric($entry)) && (!is_string($entry))) {
2780
+ $entry /= 4;
2781
+ if (($entry < 0) || ($entry > 1)) {
2782
+ return PHPExcel_Calculation_Functions::NaN();
2783
+ }
2784
+ return self::PERCENTILE($aArgs,$entry);
2785
+ }
2786
+ return PHPExcel_Calculation_Functions::VALUE();
2787
+ } // function QUARTILE()
2788
+
2789
+
2790
+ /**
2791
+ * RANK
2792
+ *
2793
+ * Returns the rank of a number in a list of numbers.
2794
+ *
2795
+ * @param number The number whose rank you want to find.
2796
+ * @param array of number An array of, or a reference to, a list of numbers.
2797
+ * @param mixed Order to sort the values in the value set
2798
+ * @return float
2799
+ */
2800
+ public static function RANK($value,$valueSet,$order=0) {
2801
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2802
+ $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet);
2803
+ $order = (is_null($order)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($order);
2804
+
2805
+ foreach($valueSet as $key => $valueEntry) {
2806
+ if (!is_numeric($valueEntry)) {
2807
+ unset($valueSet[$key]);
2808
+ }
2809
+ }
2810
+
2811
+ if ($order == 0) {
2812
+ rsort($valueSet,SORT_NUMERIC);
2813
+ } else {
2814
+ sort($valueSet,SORT_NUMERIC);
2815
+ }
2816
+ $pos = array_search($value,$valueSet);
2817
+ if ($pos === False) {
2818
+ return PHPExcel_Calculation_Functions::NA();
2819
+ }
2820
+
2821
+ return ++$pos;
2822
+ } // function RANK()
2823
+
2824
+
2825
+ /**
2826
+ * RSQ
2827
+ *
2828
+ * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's.
2829
+ *
2830
+ * @param array of mixed Data Series Y
2831
+ * @param array of mixed Data Series X
2832
+ * @return float
2833
+ */
2834
+ public static function RSQ($yValues,$xValues) {
2835
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
2836
+ return PHPExcel_Calculation_Functions::VALUE();
2837
+ }
2838
+ $yValueCount = count($yValues);
2839
+ $xValueCount = count($xValues);
2840
+
2841
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2842
+ return PHPExcel_Calculation_Functions::NA();
2843
+ } elseif ($yValueCount == 1) {
2844
+ return PHPExcel_Calculation_Functions::DIV0();
2845
+ }
2846
+
2847
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
2848
+ return $bestFitLinear->getGoodnessOfFit();
2849
+ } // function RSQ()
2850
+
2851
+
2852
+ /**
2853
+ * SKEW
2854
+ *
2855
+ * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry
2856
+ * of a distribution around its mean. Positive skewness indicates a distribution with an
2857
+ * asymmetric tail extending toward more positive values. Negative skewness indicates a
2858
+ * distribution with an asymmetric tail extending toward more negative values.
2859
+ *
2860
+ * @param array Data Series
2861
+ * @return float
2862
+ */
2863
+ public static function SKEW() {
2864
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
2865
+ $mean = self::AVERAGE($aArgs);
2866
+ $stdDev = self::STDEV($aArgs);
2867
+
2868
+ $count = $summer = 0;
2869
+ // Loop through arguments
2870
+ foreach ($aArgs as $k => $arg) {
2871
+ if ((is_bool($arg)) &&
2872
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
2873
+ } else {
2874
+ // Is it a numeric value?
2875
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2876
+ $summer += pow((($arg - $mean) / $stdDev),3) ;
2877
+ ++$count;
2878
+ }
2879
+ }
2880
+ }
2881
+
2882
+ // Return
2883
+ if ($count > 2) {
2884
+ return $summer * ($count / (($count-1) * ($count-2)));
2885
+ }
2886
+ return PHPExcel_Calculation_Functions::DIV0();
2887
+ } // function SKEW()
2888
+
2889
+
2890
+ /**
2891
+ * SLOPE
2892
+ *
2893
+ * Returns the slope of the linear regression line through data points in known_y's and known_x's.
2894
+ *
2895
+ * @param array of mixed Data Series Y
2896
+ * @param array of mixed Data Series X
2897
+ * @return float
2898
+ */
2899
+ public static function SLOPE($yValues,$xValues) {
2900
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
2901
+ return PHPExcel_Calculation_Functions::VALUE();
2902
+ }
2903
+ $yValueCount = count($yValues);
2904
+ $xValueCount = count($xValues);
2905
+
2906
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2907
+ return PHPExcel_Calculation_Functions::NA();
2908
+ } elseif ($yValueCount == 1) {
2909
+ return PHPExcel_Calculation_Functions::DIV0();
2910
+ }
2911
+
2912
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
2913
+ return $bestFitLinear->getSlope();
2914
+ } // function SLOPE()
2915
+
2916
+
2917
+ /**
2918
+ * SMALL
2919
+ *
2920
+ * Returns the nth smallest value in a data set. You can use this function to
2921
+ * select a value based on its relative standing.
2922
+ *
2923
+ * Excel Function:
2924
+ * SMALL(value1[,value2[, ...]],entry)
2925
+ *
2926
+ * @access public
2927
+ * @category Statistical Functions
2928
+ * @param mixed $arg,... Data values
2929
+ * @param int $entry Position (ordered from the smallest) in the array or range of data to return
2930
+ * @return float
2931
+ */
2932
+ public static function SMALL() {
2933
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2934
+
2935
+ // Calculate
2936
+ $entry = array_pop($aArgs);
2937
+
2938
+ if ((is_numeric($entry)) && (!is_string($entry))) {
2939
+ $mArgs = array();
2940
+ foreach ($aArgs as $arg) {
2941
+ // Is it a numeric value?
2942
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2943
+ $mArgs[] = $arg;
2944
+ }
2945
+ }
2946
+ $count = self::COUNT($mArgs);
2947
+ $entry = floor(--$entry);
2948
+ if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
2949
+ return PHPExcel_Calculation_Functions::NaN();
2950
+ }
2951
+ sort($mArgs);
2952
+ return $mArgs[$entry];
2953
+ }
2954
+ return PHPExcel_Calculation_Functions::VALUE();
2955
+ } // function SMALL()
2956
+
2957
+
2958
+ /**
2959
+ * STANDARDIZE
2960
+ *
2961
+ * Returns a normalized value from a distribution characterized by mean and standard_dev.
2962
+ *
2963
+ * @param float $value Value to normalize
2964
+ * @param float $mean Mean Value
2965
+ * @param float $stdDev Standard Deviation
2966
+ * @return float Standardized value
2967
+ */
2968
+ public static function STANDARDIZE($value,$mean,$stdDev) {
2969
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2970
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2971
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2972
+
2973
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2974
+ if ($stdDev <= 0) {
2975
+ return PHPExcel_Calculation_Functions::NaN();
2976
+ }
2977
+ return ($value - $mean) / $stdDev ;
2978
+ }
2979
+ return PHPExcel_Calculation_Functions::VALUE();
2980
+ } // function STANDARDIZE()
2981
+
2982
+
2983
+ /**
2984
+ * STDEV
2985
+ *
2986
+ * Estimates standard deviation based on a sample. The standard deviation is a measure of how
2987
+ * widely values are dispersed from the average value (the mean).
2988
+ *
2989
+ * Excel Function:
2990
+ * STDEV(value1[,value2[, ...]])
2991
+ *
2992
+ * @access public
2993
+ * @category Statistical Functions
2994
+ * @param mixed $arg,... Data values
2995
+ * @return float
2996
+ */
2997
+ public static function STDEV() {
2998
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
2999
+
3000
+ // Return value
3001
+ $returnValue = null;
3002
+
3003
+ $aMean = self::AVERAGE($aArgs);
3004
+ if (!is_null($aMean)) {
3005
+ $aCount = -1;
3006
+ foreach ($aArgs as $k => $arg) {
3007
+ if ((is_bool($arg)) &&
3008
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
3009
+ $arg = (integer) $arg;
3010
+ }
3011
+ // Is it a numeric value?
3012
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3013
+ if (is_null($returnValue)) {
3014
+ $returnValue = pow(($arg - $aMean),2);
3015
+ } else {
3016
+ $returnValue += pow(($arg - $aMean),2);
3017
+ }
3018
+ ++$aCount;
3019
+ }
3020
+ }
3021
+
3022
+ // Return
3023
+ if (($aCount > 0) && ($returnValue >= 0)) {
3024
+ return sqrt($returnValue / $aCount);
3025
+ }
3026
+ }
3027
+ return PHPExcel_Calculation_Functions::DIV0();
3028
+ } // function STDEV()
3029
+
3030
+
3031
+ /**
3032
+ * STDEVA
3033
+ *
3034
+ * Estimates standard deviation based on a sample, including numbers, text, and logical values
3035
+ *
3036
+ * Excel Function:
3037
+ * STDEVA(value1[,value2[, ...]])
3038
+ *
3039
+ * @access public
3040
+ * @category Statistical Functions
3041
+ * @param mixed $arg,... Data values
3042
+ * @return float
3043
+ */
3044
+ public static function STDEVA() {
3045
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3046
+
3047
+ // Return value
3048
+ $returnValue = null;
3049
+
3050
+ $aMean = self::AVERAGEA($aArgs);
3051
+ if (!is_null($aMean)) {
3052
+ $aCount = -1;
3053
+ foreach ($aArgs as $k => $arg) {
3054
+ if ((is_bool($arg)) &&
3055
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3056
+ } else {
3057
+ // Is it a numeric value?
3058
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3059
+ if (is_bool($arg)) {
3060
+ $arg = (integer) $arg;
3061
+ } elseif (is_string($arg)) {
3062
+ $arg = 0;
3063
+ }
3064
+ if (is_null($returnValue)) {
3065
+ $returnValue = pow(($arg - $aMean),2);
3066
+ } else {
3067
+ $returnValue += pow(($arg - $aMean),2);
3068
+ }
3069
+ ++$aCount;
3070
+ }
3071
+ }
3072
+ }
3073
+
3074
+ // Return
3075
+ if (($aCount > 0) && ($returnValue >= 0)) {
3076
+ return sqrt($returnValue / $aCount);
3077
+ }
3078
+ }
3079
+ return PHPExcel_Calculation_Functions::DIV0();
3080
+ } // function STDEVA()
3081
+
3082
+
3083
+ /**
3084
+ * STDEVP
3085
+ *
3086
+ * Calculates standard deviation based on the entire population
3087
+ *
3088
+ * Excel Function:
3089
+ * STDEVP(value1[,value2[, ...]])
3090
+ *
3091
+ * @access public
3092
+ * @category Statistical Functions
3093
+ * @param mixed $arg,... Data values
3094
+ * @return float
3095
+ */
3096
+ public static function STDEVP() {
3097
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3098
+
3099
+ // Return value
3100
+ $returnValue = null;
3101
+
3102
+ $aMean = self::AVERAGE($aArgs);
3103
+ if (!is_null($aMean)) {
3104
+ $aCount = 0;
3105
+ foreach ($aArgs as $k => $arg) {
3106
+ if ((is_bool($arg)) &&
3107
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
3108
+ $arg = (integer) $arg;
3109
+ }
3110
+ // Is it a numeric value?
3111
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3112
+ if (is_null($returnValue)) {
3113
+ $returnValue = pow(($arg - $aMean),2);
3114
+ } else {
3115
+ $returnValue += pow(($arg - $aMean),2);
3116
+ }
3117
+ ++$aCount;
3118
+ }
3119
+ }
3120
+
3121
+ // Return
3122
+ if (($aCount > 0) && ($returnValue >= 0)) {
3123
+ return sqrt($returnValue / $aCount);
3124
+ }
3125
+ }
3126
+ return PHPExcel_Calculation_Functions::DIV0();
3127
+ } // function STDEVP()
3128
+
3129
+
3130
+ /**
3131
+ * STDEVPA
3132
+ *
3133
+ * Calculates standard deviation based on the entire population, including numbers, text, and logical values
3134
+ *
3135
+ * Excel Function:
3136
+ * STDEVPA(value1[,value2[, ...]])
3137
+ *
3138
+ * @access public
3139
+ * @category Statistical Functions
3140
+ * @param mixed $arg,... Data values
3141
+ * @return float
3142
+ */
3143
+ public static function STDEVPA() {
3144
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3145
+
3146
+ // Return value
3147
+ $returnValue = null;
3148
+
3149
+ $aMean = self::AVERAGEA($aArgs);
3150
+ if (!is_null($aMean)) {
3151
+ $aCount = 0;
3152
+ foreach ($aArgs as $k => $arg) {
3153
+ if ((is_bool($arg)) &&
3154
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3155
+ } else {
3156
+ // Is it a numeric value?
3157
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3158
+ if (is_bool($arg)) {
3159
+ $arg = (integer) $arg;
3160
+ } elseif (is_string($arg)) {
3161
+ $arg = 0;
3162
+ }
3163
+ if (is_null($returnValue)) {
3164
+ $returnValue = pow(($arg - $aMean),2);
3165
+ } else {
3166
+ $returnValue += pow(($arg - $aMean),2);
3167
+ }
3168
+ ++$aCount;
3169
+ }
3170
+ }
3171
+ }
3172
+
3173
+ // Return
3174
+ if (($aCount > 0) && ($returnValue >= 0)) {
3175
+ return sqrt($returnValue / $aCount);
3176
+ }
3177
+ }
3178
+ return PHPExcel_Calculation_Functions::DIV0();
3179
+ } // function STDEVPA()
3180
+
3181
+
3182
+ /**
3183
+ * STEYX
3184
+ *
3185
+ * Returns the standard error of the predicted y-value for each x in the regression.
3186
+ *
3187
+ * @param array of mixed Data Series Y
3188
+ * @param array of mixed Data Series X
3189
+ * @return float
3190
+ */
3191
+ public static function STEYX($yValues,$xValues) {
3192
+ if (!self::_checkTrendArrays($yValues,$xValues)) {
3193
+ return PHPExcel_Calculation_Functions::VALUE();
3194
+ }
3195
+ $yValueCount = count($yValues);
3196
+ $xValueCount = count($xValues);
3197
+
3198
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
3199
+ return PHPExcel_Calculation_Functions::NA();
3200
+ } elseif ($yValueCount == 1) {
3201
+ return PHPExcel_Calculation_Functions::DIV0();
3202
+ }
3203
+
3204
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
3205
+ return $bestFitLinear->getStdevOfResiduals();
3206
+ } // function STEYX()
3207
+
3208
+
3209
+ /**
3210
+ * TDIST
3211
+ *
3212
+ * Returns the probability of Student's T distribution.
3213
+ *
3214
+ * @param float $value Value for the function
3215
+ * @param float $degrees degrees of freedom
3216
+ * @param float $tails number of tails (1 or 2)
3217
+ * @return float
3218
+ */
3219
+ public static function TDIST($value, $degrees, $tails) {
3220
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
3221
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
3222
+ $tails = floor(PHPExcel_Calculation_Functions::flattenSingleValue($tails));
3223
+
3224
+ if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) {
3225
+ if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
3226
+ return PHPExcel_Calculation_Functions::NaN();
3227
+ }
3228
+ // tdist, which finds the probability that corresponds to a given value
3229
+ // of t with k degrees of freedom. This algorithm is translated from a
3230
+ // pascal function on p81 of "Statistical Computing in Pascal" by D
3231
+ // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd:
3232
+ // London). The above Pascal algorithm is itself a translation of the
3233
+ // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer
3234
+ // Laboratory as reported in (among other places) "Applied Statistics
3235
+ // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis
3236
+ // Horwood Ltd.; W. Sussex, England).
3237
+ $tterm = $degrees;
3238
+ $ttheta = atan2($value,sqrt($tterm));
3239
+ $tc = cos($ttheta);
3240
+ $ts = sin($ttheta);
3241
+ $tsum = 0;
3242
+
3243
+ if (($degrees % 2) == 1) {
3244
+ $ti = 3;
3245
+ $tterm = $tc;
3246
+ } else {
3247
+ $ti = 2;
3248
+ $tterm = 1;
3249
+ }
3250
+
3251
+ $tsum = $tterm;
3252
+ while ($ti < $degrees) {
3253
+ $tterm *= $tc * $tc * ($ti - 1) / $ti;
3254
+ $tsum += $tterm;
3255
+ $ti += 2;
3256
+ }
3257
+ $tsum *= $ts;
3258
+ if (($degrees % 2) == 1) { $tsum = M_2DIVPI * ($tsum + $ttheta); }
3259
+ $tValue = 0.5 * (1 + $tsum);
3260
+ if ($tails == 1) {
3261
+ return 1 - abs($tValue);
3262
+ } else {
3263
+ return 1 - abs((1 - $tValue) - $tValue);
3264
+ }
3265
+ }
3266
+ return PHPExcel_Calculation_Functions::VALUE();
3267
+ } // function TDIST()
3268
+
3269
+
3270
+ /**
3271
+ * TINV
3272
+ *
3273
+ * Returns the one-tailed probability of the chi-squared distribution.
3274
+ *
3275
+ * @param float $probability Probability for the function
3276
+ * @param float $degrees degrees of freedom
3277
+ * @return float
3278
+ */
3279
+ public static function TINV($probability, $degrees) {
3280
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
3281
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
3282
+
3283
+ if ((is_numeric($probability)) && (is_numeric($degrees))) {
3284
+ $xLo = 100;
3285
+ $xHi = 0;
3286
+
3287
+ $x = $xNew = 1;
3288
+ $dx = 1;
3289
+ $i = 0;
3290
+
3291
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
3292
+ // Apply Newton-Raphson step
3293
+ $result = self::TDIST($x, $degrees, 2);
3294
+ $error = $result - $probability;
3295
+ if ($error == 0.0) {
3296
+ $dx = 0;
3297
+ } elseif ($error < 0.0) {
3298
+ $xLo = $x;
3299
+ } else {
3300
+ $xHi = $x;
3301
+ }
3302
+ // Avoid division by zero
3303
+ if ($result != 0.0) {
3304
+ $dx = $error / $result;
3305
+ $xNew = $x - $dx;
3306
+ }
3307
+ // If the NR fails to converge (which for example may be the
3308
+ // case if the initial guess is too rough) we apply a bisection
3309
+ // step to determine a more narrow interval around the root.
3310
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
3311
+ $xNew = ($xLo + $xHi) / 2;
3312
+ $dx = $xNew - $x;
3313
+ }
3314
+ $x = $xNew;
3315
+ }
3316
+ if ($i == MAX_ITERATIONS) {
3317
+ return PHPExcel_Calculation_Functions::NA();
3318
+ }
3319
+ return round($x,12);
3320
+ }
3321
+ return PHPExcel_Calculation_Functions::VALUE();
3322
+ } // function TINV()
3323
+
3324
+
3325
+ /**
3326
+ * TREND
3327
+ *
3328
+ * Returns values along a linear trend
3329
+ *
3330
+ * @param array of mixed Data Series Y
3331
+ * @param array of mixed Data Series X
3332
+ * @param array of mixed Values of X for which we want to find Y
3333
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
3334
+ * @return array of float
3335
+ */
3336
+ public static function TREND($yValues,$xValues=array(),$newValues=array(),$const=True) {
3337
+ $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues);
3338
+ $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues);
3339
+ $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues);
3340
+ $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
3341
+
3342
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const);
3343
+ if (empty($newValues)) {
3344
+ $newValues = $bestFitLinear->getXValues();
3345
+ }
3346
+
3347
+ $returnArray = array();
3348
+ foreach($newValues as $xValue) {
3349
+ $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue);
3350
+ }
3351
+
3352
+ return $returnArray;
3353
+ } // function TREND()
3354
+
3355
+
3356
+ /**
3357
+ * TRIMMEAN
3358
+ *
3359
+ * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean
3360
+ * taken by excluding a percentage of data points from the top and bottom tails
3361
+ * of a data set.
3362
+ *
3363
+ * Excel Function:
3364
+ * TRIMEAN(value1[,value2[, ...]],$discard)
3365
+ *
3366
+ * @access public
3367
+ * @category Statistical Functions
3368
+ * @param mixed $arg,... Data values
3369
+ * @param float $discard Percentage to discard
3370
+ * @return float
3371
+ */
3372
+ public static function TRIMMEAN() {
3373
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3374
+
3375
+ // Calculate
3376
+ $percent = array_pop($aArgs);
3377
+
3378
+ if ((is_numeric($percent)) && (!is_string($percent))) {
3379
+ if (($percent < 0) || ($percent > 1)) {
3380
+ return PHPExcel_Calculation_Functions::NaN();
3381
+ }
3382
+ $mArgs = array();
3383
+ foreach ($aArgs as $arg) {
3384
+ // Is it a numeric value?
3385
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3386
+ $mArgs[] = $arg;
3387
+ }
3388
+ }
3389
+ $discard = floor(self::COUNT($mArgs) * $percent / 2);
3390
+ sort($mArgs);
3391
+ for ($i=0; $i < $discard; ++$i) {
3392
+ array_pop($mArgs);
3393
+ array_shift($mArgs);
3394
+ }
3395
+ return self::AVERAGE($mArgs);
3396
+ }
3397
+ return PHPExcel_Calculation_Functions::VALUE();
3398
+ } // function TRIMMEAN()
3399
+
3400
+
3401
+ /**
3402
+ * VARFunc
3403
+ *
3404
+ * Estimates variance based on a sample.
3405
+ *
3406
+ * Excel Function:
3407
+ * VAR(value1[,value2[, ...]])
3408
+ *
3409
+ * @access public
3410
+ * @category Statistical Functions
3411
+ * @param mixed $arg,... Data values
3412
+ * @return float
3413
+ */
3414
+ public static function VARFunc() {
3415
+ // Return value
3416
+ $returnValue = PHPExcel_Calculation_Functions::DIV0();
3417
+
3418
+ $summerA = $summerB = 0;
3419
+
3420
+ // Loop through arguments
3421
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3422
+ $aCount = 0;
3423
+ foreach ($aArgs as $arg) {
3424
+ if (is_bool($arg)) { $arg = (integer) $arg; }
3425
+ // Is it a numeric value?
3426
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3427
+ $summerA += ($arg * $arg);
3428
+ $summerB += $arg;
3429
+ ++$aCount;
3430
+ }
3431
+ }
3432
+
3433
+ // Return
3434
+ if ($aCount > 1) {
3435
+ $summerA *= $aCount;
3436
+ $summerB *= $summerB;
3437
+ $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
3438
+ }
3439
+ return $returnValue;
3440
+ } // function VARFunc()
3441
+
3442
+
3443
+ /**
3444
+ * VARA
3445
+ *
3446
+ * Estimates variance based on a sample, including numbers, text, and logical values
3447
+ *
3448
+ * Excel Function:
3449
+ * VARA(value1[,value2[, ...]])
3450
+ *
3451
+ * @access public
3452
+ * @category Statistical Functions
3453
+ * @param mixed $arg,... Data values
3454
+ * @return float
3455
+ */
3456
+ public static function VARA() {
3457
+ // Return value
3458
+ $returnValue = PHPExcel_Calculation_Functions::DIV0();
3459
+
3460
+ $summerA = $summerB = 0;
3461
+
3462
+ // Loop through arguments
3463
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3464
+ $aCount = 0;
3465
+ foreach ($aArgs as $k => $arg) {
3466
+ if ((is_string($arg)) &&
3467
+ (PHPExcel_Calculation_Functions::isValue($k))) {
3468
+ return PHPExcel_Calculation_Functions::VALUE();
3469
+ } elseif ((is_string($arg)) &&
3470
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3471
+ } else {
3472
+ // Is it a numeric value?
3473
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3474
+ if (is_bool($arg)) {
3475
+ $arg = (integer) $arg;
3476
+ } elseif (is_string($arg)) {
3477
+ $arg = 0;
3478
+ }
3479
+ $summerA += ($arg * $arg);
3480
+ $summerB += $arg;
3481
+ ++$aCount;
3482
+ }
3483
+ }
3484
+ }
3485
+
3486
+ // Return
3487
+ if ($aCount > 1) {
3488
+ $summerA *= $aCount;
3489
+ $summerB *= $summerB;
3490
+ $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
3491
+ }
3492
+ return $returnValue;
3493
+ } // function VARA()
3494
+
3495
+
3496
+ /**
3497
+ * VARP
3498
+ *
3499
+ * Calculates variance based on the entire population
3500
+ *
3501
+ * Excel Function:
3502
+ * VARP(value1[,value2[, ...]])
3503
+ *
3504
+ * @access public
3505
+ * @category Statistical Functions
3506
+ * @param mixed $arg,... Data values
3507
+ * @return float
3508
+ */
3509
+ public static function VARP() {
3510
+ // Return value
3511
+ $returnValue = PHPExcel_Calculation_Functions::DIV0();
3512
+
3513
+ $summerA = $summerB = 0;
3514
+
3515
+ // Loop through arguments
3516
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3517
+ $aCount = 0;
3518
+ foreach ($aArgs as $arg) {
3519
+ if (is_bool($arg)) { $arg = (integer) $arg; }
3520
+ // Is it a numeric value?
3521
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3522
+ $summerA += ($arg * $arg);
3523
+ $summerB += $arg;
3524
+ ++$aCount;
3525
+ }
3526
+ }
3527
+
3528
+ // Return
3529
+ if ($aCount > 0) {
3530
+ $summerA *= $aCount;
3531
+ $summerB *= $summerB;
3532
+ $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
3533
+ }
3534
+ return $returnValue;
3535
+ } // function VARP()
3536
+
3537
+
3538
+ /**
3539
+ * VARPA
3540
+ *
3541
+ * Calculates variance based on the entire population, including numbers, text, and logical values
3542
+ *
3543
+ * Excel Function:
3544
+ * VARPA(value1[,value2[, ...]])
3545
+ *
3546
+ * @access public
3547
+ * @category Statistical Functions
3548
+ * @param mixed $arg,... Data values
3549
+ * @return float
3550
+ */
3551
+ public static function VARPA() {
3552
+ // Return value
3553
+ $returnValue = PHPExcel_Calculation_Functions::DIV0();
3554
+
3555
+ $summerA = $summerB = 0;
3556
+
3557
+ // Loop through arguments
3558
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3559
+ $aCount = 0;
3560
+ foreach ($aArgs as $k => $arg) {
3561
+ if ((is_string($arg)) &&
3562
+ (PHPExcel_Calculation_Functions::isValue($k))) {
3563
+ return PHPExcel_Calculation_Functions::VALUE();
3564
+ } elseif ((is_string($arg)) &&
3565
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3566
+ } else {
3567
+ // Is it a numeric value?
3568
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3569
+ if (is_bool($arg)) {
3570
+ $arg = (integer) $arg;
3571
+ } elseif (is_string($arg)) {
3572
+ $arg = 0;
3573
+ }
3574
+ $summerA += ($arg * $arg);
3575
+ $summerB += $arg;
3576
+ ++$aCount;
3577
+ }
3578
+ }
3579
+ }
3580
+
3581
+ // Return
3582
+ if ($aCount > 0) {
3583
+ $summerA *= $aCount;
3584
+ $summerB *= $summerB;
3585
+ $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
3586
+ }
3587
+ return $returnValue;
3588
+ } // function VARPA()
3589
+
3590
+
3591
+ /**
3592
+ * WEIBULL
3593
+ *
3594
+ * Returns the Weibull distribution. Use this distribution in reliability
3595
+ * analysis, such as calculating a device's mean time to failure.
3596
+ *
3597
+ * @param float $value
3598
+ * @param float $alpha Alpha Parameter
3599
+ * @param float $beta Beta Parameter
3600
+ * @param boolean $cumulative
3601
+ * @return float
3602
+ *
3603
+ */
3604
+ public static function WEIBULL($value, $alpha, $beta, $cumulative) {
3605
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
3606
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
3607
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
3608
+
3609
+ if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) {
3610
+ if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) {
3611
+ return PHPExcel_Calculation_Functions::NaN();
3612
+ }
3613
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
3614
+ if ($cumulative) {
3615
+ return 1 - exp(0 - pow($value / $beta,$alpha));
3616
+ } else {
3617
+ return ($alpha / pow($beta,$alpha)) * pow($value,$alpha - 1) * exp(0 - pow($value / $beta,$alpha));
3618
+ }
3619
+ }
3620
+ }
3621
+ return PHPExcel_Calculation_Functions::VALUE();
3622
+ } // function WEIBULL()
3623
+
3624
+
3625
+ /**
3626
+ * ZTEST
3627
+ *
3628
+ * Returns the Weibull distribution. Use this distribution in reliability
3629
+ * analysis, such as calculating a device's mean time to failure.
3630
+ *
3631
+ * @param float $dataSet
3632
+ * @param float $m0 Alpha Parameter
3633
+ * @param float $sigma Beta Parameter
3634
+ * @param boolean $cumulative
3635
+ * @return float
3636
+ *
3637
+ */
3638
+ public static function ZTEST($dataSet, $m0, $sigma = NULL) {
3639
+ $dataSet = PHPExcel_Calculation_Functions::flattenArrayIndexed($dataSet);
3640
+ $m0 = PHPExcel_Calculation_Functions::flattenSingleValue($m0);
3641
+ $sigma = PHPExcel_Calculation_Functions::flattenSingleValue($sigma);
3642
+
3643
+ if (is_null($sigma)) {
3644
+ $sigma = self::STDEV($dataSet);
3645
+ }
3646
+ $n = count($dataSet);
3647
+
3648
+ return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0)/($sigma/SQRT($n)));
3649
+ } // function ZTEST()
3650
+
3651
+ } // class PHPExcel_Calculation_Statistical
libraries/PHPExcel/Calculation/TextData.php ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Calculation_TextData
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Calculation
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Calculation_TextData {
47
+
48
+ private static $_invalidChars = Null;
49
+
50
+ private static function _uniord($c) {
51
+ if (ord($c{0}) >=0 && ord($c{0}) <= 127)
52
+ return ord($c{0});
53
+ if (ord($c{0}) >= 192 && ord($c{0}) <= 223)
54
+ return (ord($c{0})-192)*64 + (ord($c{1})-128);
55
+ if (ord($c{0}) >= 224 && ord($c{0}) <= 239)
56
+ return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
57
+ if (ord($c{0}) >= 240 && ord($c{0}) <= 247)
58
+ return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
59
+ if (ord($c{0}) >= 248 && ord($c{0}) <= 251)
60
+ return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
61
+ if (ord($c{0}) >= 252 && ord($c{0}) <= 253)
62
+ return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
63
+ if (ord($c{0}) >= 254 && ord($c{0}) <= 255) //error
64
+ return PHPExcel_Calculation_Functions::VALUE();
65
+ return 0;
66
+ } // function _uniord()
67
+
68
+ /**
69
+ * CHARACTER
70
+ *
71
+ * @param string $character Value
72
+ * @return int
73
+ */
74
+ public static function CHARACTER($character) {
75
+ $character = PHPExcel_Calculation_Functions::flattenSingleValue($character);
76
+
77
+ if ((!is_numeric($character)) || ($character < 0)) {
78
+ return PHPExcel_Calculation_Functions::VALUE();
79
+ }
80
+
81
+ if (function_exists('mb_convert_encoding')) {
82
+ return mb_convert_encoding('&#'.intval($character).';', 'UTF-8', 'HTML-ENTITIES');
83
+ } else {
84
+ return chr(intval($character));
85
+ }
86
+ }
87
+
88
+
89
+ /**
90
+ * TRIMNONPRINTABLE
91
+ *
92
+ * @param mixed $stringValue Value to check
93
+ * @return string
94
+ */
95
+ public static function TRIMNONPRINTABLE($stringValue = '') {
96
+ $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue);
97
+
98
+ if (is_bool($stringValue)) {
99
+ return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
100
+ }
101
+
102
+ if (self::$_invalidChars == Null) {
103
+ self::$_invalidChars = range(chr(0),chr(31));
104
+ }
105
+
106
+ if (is_string($stringValue) || is_numeric($stringValue)) {
107
+ return str_replace(self::$_invalidChars, '', trim($stringValue, "\x00..\x1F"));
108
+ }
109
+ return NULL;
110
+ } // function TRIMNONPRINTABLE()
111
+
112
+
113
+ /**
114
+ * TRIMSPACES
115
+ *
116
+ * @param mixed $stringValue Value to check
117
+ * @return string
118
+ */
119
+ public static function TRIMSPACES($stringValue = '') {
120
+ $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue);
121
+ if (is_bool($stringValue)) {
122
+ return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
123
+ }
124
+
125
+ if (is_string($stringValue) || is_numeric($stringValue)) {
126
+ return trim(preg_replace('/ +/',' ',trim($stringValue, ' ')), ' ');
127
+ }
128
+ return NULL;
129
+ } // function TRIMSPACES()
130
+
131
+
132
+ /**
133
+ * ASCIICODE
134
+ *
135
+ * @param string $characters Value
136
+ * @return int
137
+ */
138
+ public static function ASCIICODE($characters) {
139
+ if (($characters === NULL) || ($characters === ''))
140
+ return PHPExcel_Calculation_Functions::VALUE();
141
+ $characters = PHPExcel_Calculation_Functions::flattenSingleValue($characters);
142
+ if (is_bool($characters)) {
143
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
144
+ $characters = (int) $characters;
145
+ } else {
146
+ $characters = ($characters) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
147
+ }
148
+ }
149
+
150
+ $character = $characters;
151
+ if ((function_exists('mb_strlen')) && (function_exists('mb_substr'))) {
152
+ if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); }
153
+ return self::_uniord($character);
154
+ } else {
155
+ if (strlen($characters) > 0) { $character = substr($characters, 0, 1); }
156
+ return ord($character);
157
+ }
158
+ } // function ASCIICODE()
159
+
160
+
161
+ /**
162
+ * CONCATENATE
163
+ *
164
+ * @return string
165
+ */
166
+ public static function CONCATENATE() {
167
+ // Return value
168
+ $returnValue = '';
169
+
170
+ // Loop through arguments
171
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
172
+ foreach ($aArgs as $arg) {
173
+ if (is_bool($arg)) {
174
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
175
+ $arg = (int) $arg;
176
+ } else {
177
+ $arg = ($arg) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
178
+ }
179
+ }
180
+ $returnValue .= $arg;
181
+ }
182
+
183
+ // Return
184
+ return $returnValue;
185
+ } // function CONCATENATE()
186
+
187
+
188
+ /**
189
+ * DOLLAR
190
+ *
191
+ * This function converts a number to text using currency format, with the decimals rounded to the specified place.
192
+ * The format used is $#,##0.00_);($#,##0.00)..
193
+ *
194
+ * @param float $value The value to format
195
+ * @param int $decimals The number of digits to display to the right of the decimal point.
196
+ * If decimals is negative, number is rounded to the left of the decimal point.
197
+ * If you omit decimals, it is assumed to be 2
198
+ * @return string
199
+ */
200
+ public static function DOLLAR($value = 0, $decimals = 2) {
201
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
202
+ $decimals = is_null($decimals) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($decimals);
203
+
204
+ // Validate parameters
205
+ if (!is_numeric($value) || !is_numeric($decimals)) {
206
+ return PHPExcel_Calculation_Functions::NaN();
207
+ }
208
+ $decimals = floor($decimals);
209
+
210
+ $mask = '$#,##0';
211
+ if ($decimals > 0) {
212
+ $mask .= '.' . str_repeat('0',$decimals);
213
+ } else {
214
+ $round = pow(10,abs($decimals));
215
+ if ($value < 0) { $round = 0-$round; }
216
+ $value = PHPExcel_Calculation_MathTrig::MROUND($value, $round);
217
+ }
218
+
219
+ return PHPExcel_Style_NumberFormat::toFormattedString($value, $mask);
220
+
221
+ } // function DOLLAR()
222
+
223
+
224
+ /**
225
+ * SEARCHSENSITIVE
226
+ *
227
+ * @param string $needle The string to look for
228
+ * @param string $haystack The string in which to look
229
+ * @param int $offset Offset within $haystack
230
+ * @return string
231
+ */
232
+ public static function SEARCHSENSITIVE($needle,$haystack,$offset=1) {
233
+ $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle);
234
+ $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack);
235
+ $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset);
236
+
237
+ if (!is_bool($needle)) {
238
+ if (is_bool($haystack)) {
239
+ $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
240
+ }
241
+
242
+ if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) {
243
+ if (PHPExcel_Shared_String::CountCharacters($needle) == 0) {
244
+ return $offset;
245
+ }
246
+ if (function_exists('mb_strpos')) {
247
+ $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8');
248
+ } else {
249
+ $pos = strpos($haystack, $needle, --$offset);
250
+ }
251
+ if ($pos !== false) {
252
+ return ++$pos;
253
+ }
254
+ }
255
+ }
256
+ return PHPExcel_Calculation_Functions::VALUE();
257
+ } // function SEARCHSENSITIVE()
258
+
259
+
260
+ /**
261
+ * SEARCHINSENSITIVE
262
+ *
263
+ * @param string $needle The string to look for
264
+ * @param string $haystack The string in which to look
265
+ * @param int $offset Offset within $haystack
266
+ * @return string
267
+ */
268
+ public static function SEARCHINSENSITIVE($needle,$haystack,$offset=1) {
269
+ $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle);
270
+ $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack);
271
+ $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset);
272
+
273
+ if (!is_bool($needle)) {
274
+ if (is_bool($haystack)) {
275
+ $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
276
+ }
277
+
278
+ if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) {
279
+ if (PHPExcel_Shared_String::CountCharacters($needle) == 0) {
280
+ return $offset;
281
+ }
282
+ if (function_exists('mb_stripos')) {
283
+ $pos = mb_stripos($haystack, $needle, --$offset,'UTF-8');
284
+ } else {
285
+ $pos = stripos($haystack, $needle, --$offset);
286
+ }
287
+ if ($pos !== false) {
288
+ return ++$pos;
289
+ }
290
+ }
291
+ }
292
+ return PHPExcel_Calculation_Functions::VALUE();
293
+ } // function SEARCHINSENSITIVE()
294
+
295
+
296
+ /**
297
+ * FIXEDFORMAT
298
+ *
299
+ * @param mixed $value Value to check
300
+ * @param integer $decimals
301
+ * @param boolean $no_commas
302
+ * @return boolean
303
+ */
304
+ public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = FALSE) {
305
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
306
+ $decimals = PHPExcel_Calculation_Functions::flattenSingleValue($decimals);
307
+ $no_commas = PHPExcel_Calculation_Functions::flattenSingleValue($no_commas);
308
+
309
+ // Validate parameters
310
+ if (!is_numeric($value) || !is_numeric($decimals)) {
311
+ return PHPExcel_Calculation_Functions::NaN();
312
+ }
313
+ $decimals = floor($decimals);
314
+
315
+ $valueResult = round($value,$decimals);
316
+ if ($decimals < 0) { $decimals = 0; }
317
+ if (!$no_commas) {
318
+ $valueResult = number_format($valueResult,$decimals);
319
+ }
320
+
321
+ return (string) $valueResult;
322
+ } // function FIXEDFORMAT()
323
+
324
+
325
+ /**
326
+ * LEFT
327
+ *
328
+ * @param string $value Value
329
+ * @param int $chars Number of characters
330
+ * @return string
331
+ */
332
+ public static function LEFT($value = '', $chars = 1) {
333
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
334
+ $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars);
335
+
336
+ if ($chars < 0) {
337
+ return PHPExcel_Calculation_Functions::VALUE();
338
+ }
339
+
340
+ if (is_bool($value)) {
341
+ $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
342
+ }
343
+
344
+ if (function_exists('mb_substr')) {
345
+ return mb_substr($value, 0, $chars, 'UTF-8');
346
+ } else {
347
+ return substr($value, 0, $chars);
348
+ }
349
+ } // function LEFT()
350
+
351
+
352
+ /**
353
+ * MID
354
+ *
355
+ * @param string $value Value
356
+ * @param int $start Start character
357
+ * @param int $chars Number of characters
358
+ * @return string
359
+ */
360
+ public static function MID($value = '', $start = 1, $chars = null) {
361
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
362
+ $start = PHPExcel_Calculation_Functions::flattenSingleValue($start);
363
+ $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars);
364
+
365
+ if (($start < 1) || ($chars < 0)) {
366
+ return PHPExcel_Calculation_Functions::VALUE();
367
+ }
368
+
369
+ if (is_bool($value)) {
370
+ $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
371
+ }
372
+
373
+ if (function_exists('mb_substr')) {
374
+ return mb_substr($value, --$start, $chars, 'UTF-8');
375
+ } else {
376
+ return substr($value, --$start, $chars);
377
+ }
378
+ } // function MID()
379
+
380
+
381
+ /**
382
+ * RIGHT
383
+ *
384
+ * @param string $value Value
385
+ * @param int $chars Number of characters
386
+ * @return string
387
+ */
388
+ public static function RIGHT($value = '', $chars = 1) {
389
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
390
+ $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars);
391
+
392
+ if ($chars < 0) {
393
+ return PHPExcel_Calculation_Functions::VALUE();
394
+ }
395
+
396
+ if (is_bool($value)) {
397
+ $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
398
+ }
399
+
400
+ if ((function_exists('mb_substr')) && (function_exists('mb_strlen'))) {
401
+ return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8');
402
+ } else {
403
+ return substr($value, strlen($value) - $chars);
404
+ }
405
+ } // function RIGHT()
406
+
407
+
408
+ /**
409
+ * STRINGLENGTH
410
+ *
411
+ * @param string $value Value
412
+ * @return string
413
+ */
414
+ public static function STRINGLENGTH($value = '') {
415
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
416
+
417
+ if (is_bool($value)) {
418
+ $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
419
+ }
420
+
421
+ if (function_exists('mb_strlen')) {
422
+ return mb_strlen($value, 'UTF-8');
423
+ } else {
424
+ return strlen($value);
425
+ }
426
+ } // function STRINGLENGTH()
427
+
428
+
429
+ /**
430
+ * LOWERCASE
431
+ *
432
+ * Converts a string value to upper case.
433
+ *
434
+ * @param string $mixedCaseString
435
+ * @return string
436
+ */
437
+ public static function LOWERCASE($mixedCaseString) {
438
+ $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString);
439
+
440
+ if (is_bool($mixedCaseString)) {
441
+ $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
442
+ }
443
+
444
+ return PHPExcel_Shared_String::StrToLower($mixedCaseString);
445
+ } // function LOWERCASE()
446
+
447
+
448
+ /**
449
+ * UPPERCASE
450
+ *
451
+ * Converts a string value to upper case.
452
+ *
453
+ * @param string $mixedCaseString
454
+ * @return string
455
+ */
456
+ public static function UPPERCASE($mixedCaseString) {
457
+ $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString);
458
+
459
+ if (is_bool($mixedCaseString)) {
460
+ $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
461
+ }
462
+
463
+ return PHPExcel_Shared_String::StrToUpper($mixedCaseString);
464
+ } // function UPPERCASE()
465
+
466
+
467
+ /**
468
+ * PROPERCASE
469
+ *
470
+ * Converts a string value to upper case.
471
+ *
472
+ * @param string $mixedCaseString
473
+ * @return string
474
+ */
475
+ public static function PROPERCASE($mixedCaseString) {
476
+ $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString);
477
+
478
+ if (is_bool($mixedCaseString)) {
479
+ $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE();
480
+ }
481
+
482
+ return PHPExcel_Shared_String::StrToTitle($mixedCaseString);
483
+ } // function PROPERCASE()
484
+
485
+
486
+ /**
487
+ * REPLACE
488
+ *
489
+ * @param string $oldText String to modify
490
+ * @param int $start Start character
491
+ * @param int $chars Number of characters
492
+ * @param string $newText String to replace in defined position
493
+ * @return string
494
+ */
495
+ public static function REPLACE($oldText = '', $start = 1, $chars = null, $newText) {
496
+ $oldText = PHPExcel_Calculation_Functions::flattenSingleValue($oldText);
497
+ $start = PHPExcel_Calculation_Functions::flattenSingleValue($start);
498
+ $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars);
499
+ $newText = PHPExcel_Calculation_Functions::flattenSingleValue($newText);
500
+
501
+ $left = self::LEFT($oldText,$start-1);
502
+ $right = self::RIGHT($oldText,self::STRINGLENGTH($oldText)-($start+$chars)+1);
503
+
504
+ return $left.$newText.$right;
505
+ } // function REPLACE()
506
+
507
+
508
+ /**
509
+ * SUBSTITUTE
510
+ *
511
+ * @param string $text Value
512
+ * @param string $fromText From Value
513
+ * @param string $toText To Value
514
+ * @param integer $instance Instance Number
515
+ * @return string
516
+ */
517
+ public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) {
518
+ $text = PHPExcel_Calculation_Functions::flattenSingleValue($text);
519
+ $fromText = PHPExcel_Calculation_Functions::flattenSingleValue($fromText);
520
+ $toText = PHPExcel_Calculation_Functions::flattenSingleValue($toText);
521
+ $instance = floor(PHPExcel_Calculation_Functions::flattenSingleValue($instance));
522
+
523
+ if ($instance == 0) {
524
+ if(function_exists('mb_str_replace')) {
525
+ return mb_str_replace($fromText,$toText,$text);
526
+ } else {
527
+ return str_replace($fromText,$toText,$text);
528
+ }
529
+ } else {
530
+ $pos = -1;
531
+ while($instance > 0) {
532
+ if (function_exists('mb_strpos')) {
533
+ $pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8');
534
+ } else {
535
+ $pos = strpos($text, $fromText, $pos+1);
536
+ }
537
+ if ($pos === false) {
538
+ break;
539
+ }
540
+ --$instance;
541
+ }
542
+ if ($pos !== false) {
543
+ if (function_exists('mb_strlen')) {
544
+ return self::REPLACE($text,++$pos,mb_strlen($fromText, 'UTF-8'),$toText);
545
+ } else {
546
+ return self::REPLACE($text,++$pos,strlen($fromText),$toText);
547
+ }
548
+ }
549
+ }
550
+
551
+ return $text;
552
+ } // function SUBSTITUTE()
553
+
554
+
555
+ /**
556
+ * RETURNSTRING
557
+ *
558
+ * @param mixed $testValue Value to check
559
+ * @return boolean
560
+ */
561
+ public static function RETURNSTRING($testValue = '') {
562
+ $testValue = PHPExcel_Calculation_Functions::flattenSingleValue($testValue);
563
+
564
+ if (is_string($testValue)) {
565
+ return $testValue;
566
+ }
567
+ return Null;
568
+ } // function RETURNSTRING()
569
+
570
+
571
+ /**
572
+ * TEXTFORMAT
573
+ *
574
+ * @param mixed $value Value to check
575
+ * @param string $format Format mask to use
576
+ * @return boolean
577
+ */
578
+ public static function TEXTFORMAT($value,$format) {
579
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
580
+ $format = PHPExcel_Calculation_Functions::flattenSingleValue($format);
581
+
582
+ if ((is_string($value)) && (!is_numeric($value)) && PHPExcel_Shared_Date::isDateTimeFormatCode($format)) {
583
+ $value = PHPExcel_Calculation_DateTime::DATEVALUE($value);
584
+ }
585
+
586
+ return (string) PHPExcel_Style_NumberFormat::toFormattedString($value,$format);
587
+ } // function TEXTFORMAT()
588
+
589
+ /**
590
+ * VALUE
591
+ *
592
+ * @param mixed $value Value to check
593
+ * @return boolean
594
+ */
595
+ public static function VALUE($value = '') {
596
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
597
+
598
+ if (!is_numeric($value)) {
599
+ $numberValue = str_replace(
600
+ PHPExcel_Shared_String::getThousandsSeparator(),
601
+ '',
602
+ trim($value, " \t\n\r\0\x0B" . PHPExcel_Shared_String::getCurrencyCode())
603
+ );
604
+ if (is_numeric($numberValue)) {
605
+ return (float) $numberValue;
606
+ }
607
+
608
+ $dateSetting = PHPExcel_Calculation_Functions::getReturnDateType();
609
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
610
+
611
+ if (strpos($value, ':') !== false) {
612
+ $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($value);
613
+ if ($timeValue !== PHPExcel_Calculation_Functions::VALUE()) {
614
+ PHPExcel_Calculation_Functions::setReturnDateType($dateSetting);
615
+ return $timeValue;
616
+ }
617
+ }
618
+ $dateValue = PHPExcel_Calculation_DateTime::DATEVALUE($value);
619
+ if ($dateValue !== PHPExcel_Calculation_Functions::VALUE()) {
620
+ PHPExcel_Calculation_Functions::setReturnDateType($dateSetting);
621
+ return $dateValue;
622
+ }
623
+ PHPExcel_Calculation_Functions::setReturnDateType($dateSetting);
624
+
625
+ return PHPExcel_Calculation_Functions::VALUE();
626
+ }
627
+ return (float) $value;
628
+ }
629
+
630
+ }
libraries/PHPExcel/Calculation/Token/Stack.php ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Calculation
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Calculation_Token_Stack
31
+ *
32
+ * @category PHPExcel_Calculation_Token_Stack
33
+ * @package PHPExcel_Calculation
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Calculation_Token_Stack {
37
+
38
+ /**
39
+ * The parser stack for formulae
40
+ *
41
+ * @var mixed[]
42
+ */
43
+ private $_stack = array();
44
+
45
+ /**
46
+ * Count of entries in the parser stack
47
+ *
48
+ * @var integer
49
+ */
50
+ private $_count = 0;
51
+
52
+
53
+ /**
54
+ * Return the number of entries on the stack
55
+ *
56
+ * @return integer
57
+ */
58
+ public function count() {
59
+ return $this->_count;
60
+ } // function count()
61
+
62
+ /**
63
+ * Push a new entry onto the stack
64
+ *
65
+ * @param mixed $type
66
+ * @param mixed $value
67
+ * @param mixed $reference
68
+ */
69
+ public function push($type, $value, $reference = NULL) {
70
+ $this->_stack[$this->_count++] = array('type' => $type,
71
+ 'value' => $value,
72
+ 'reference' => $reference
73
+ );
74
+ if ($type == 'Function') {
75
+ $localeFunction = PHPExcel_Calculation::_localeFunc($value);
76
+ if ($localeFunction != $value) {
77
+ $this->_stack[($this->_count - 1)]['localeValue'] = $localeFunction;
78
+ }
79
+ }
80
+ } // function push()
81
+
82
+ /**
83
+ * Pop the last entry from the stack
84
+ *
85
+ * @return mixed
86
+ */
87
+ public function pop() {
88
+ if ($this->_count > 0) {
89
+ return $this->_stack[--$this->_count];
90
+ }
91
+ return NULL;
92
+ } // function pop()
93
+
94
+ /**
95
+ * Return an entry from the stack without removing it
96
+ *
97
+ * @param integer $n number indicating how far back in the stack we want to look
98
+ * @return mixed
99
+ */
100
+ public function last($n = 1) {
101
+ if ($this->_count - $n < 0) {
102
+ return NULL;
103
+ }
104
+ return $this->_stack[$this->_count - $n];
105
+ } // function last()
106
+
107
+ /**
108
+ * Clear the stack
109
+ */
110
+ function clear() {
111
+ $this->_stack = array();
112
+ $this->_count = 0;
113
+ }
114
+
115
+ } // class PHPExcel_Calculation_Token_Stack
libraries/PHPExcel/Calculation/functionlist.txt ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ABS
2
+ ACCRINT
3
+ ACCRINTM
4
+ ACOS
5
+ ACOSH
6
+ ADDRESS
7
+ AMORDEGRC
8
+ AMORLINC
9
+ AND
10
+ AREAS
11
+ ASC
12
+ ASIN
13
+ ASINH
14
+ ATAN
15
+ ATAN2
16
+ ATANH
17
+ AVEDEV
18
+ AVERAGE
19
+ AVERAGEA
20
+ AVERAGEIF
21
+ AVERAGEIFS
22
+ BAHTTEXT
23
+ BESSELI
24
+ BESSELJ
25
+ BESSELK
26
+ BESSELY
27
+ BETADIST
28
+ BETAINV
29
+ BIN2DEC
30
+ BIN2HEX
31
+ BIN2OCT
32
+ BINOMDIST
33
+ CEILING
34
+ CELL
35
+ CHAR
36
+ CHIDIST
37
+ CHIINV
38
+ CHITEST
39
+ CHOOSE
40
+ CLEAN
41
+ CODE
42
+ COLUMN
43
+ COLUMNS
44
+ COMBIN
45
+ COMPLEX
46
+ CONCATENATE
47
+ CONFIDENCE
48
+ CONVERT
49
+ CORREL
50
+ COS
51
+ COSH
52
+ COUNT
53
+ COUNTA
54
+ COUNTBLANK
55
+ COUNTIF
56
+ COUNTIFS
57
+ COUPDAYBS
58
+ COUPDAYBS
59
+ COUPDAYSNC
60
+ COUPNCD
61
+ COUPNUM
62
+ COUPPCD
63
+ COVAR
64
+ CRITBINOM
65
+ CUBEKPIMEMBER
66
+ CUBEMEMBER
67
+ CUBEMEMBERPROPERTY
68
+ CUBERANKEDMEMBER
69
+ CUBESET
70
+ CUBESETCOUNT
71
+ CUBEVALUE
72
+ CUMIPMT
73
+ CUMPRINC
74
+ DATE
75
+ DATEDIF
76
+ DATEVALUE
77
+ DAVERAGE
78
+ DAY
79
+ DAYS360
80
+ DB
81
+ DCOUNT
82
+ DCOUNTA
83
+ DDB
84
+ DEC2BIN
85
+ DEC2HEX
86
+ DEC2OCT
87
+ DEGREES
88
+ DELTA
89
+ DEVSQ
90
+ DGET
91
+ DISC
92
+ DMAX
93
+ DMIN
94
+ DOLLAR
95
+ DOLLARDE
96
+ DOLLARFR
97
+ DPRODUCT
98
+ DSTDEV
99
+ DSTDEVP
100
+ DSUM
101
+ DURATION
102
+ DVAR
103
+ DVARP
104
+ EDATE
105
+ EFFECT
106
+ EOMONTH
107
+ ERF
108
+ ERFC
109
+ ERROR.TYPE
110
+ EVEN
111
+ EXACT
112
+ EXP
113
+ EXPONDIST
114
+ FACT
115
+ FACTDOUBLE
116
+ FALSE
117
+ FDIST
118
+ FIND
119
+ FINDB
120
+ FINV
121
+ FISHER
122
+ FISHERINV
123
+ FIXED
124
+ FLOOR
125
+ FORECAST
126
+ FREQUENCY
127
+ FTEST
128
+ FV
129
+ FVSCHEDULE
130
+ GAMAMDIST
131
+ GAMMAINV
132
+ GAMMALN
133
+ GCD
134
+ GEOMEAN
135
+ GESTEP
136
+ GETPIVOTDATA
137
+ GROWTH
138
+ HARMEAN
139
+ HEX2BIN
140
+ HEX2OCT
141
+ HLOOKUP
142
+ HOUR
143
+ HYPERLINK
144
+ HYPGEOMDIST
145
+ IF
146
+ IFERROR
147
+ IMABS
148
+ IMAGINARY
149
+ IMARGUMENT
150
+ IMCONJUGATE
151
+ IMCOS
152
+ IMEXP
153
+ IMLN
154
+ IMLOG10
155
+ IMLOG2
156
+ IMPOWER
157
+ IMPRODUCT
158
+ IMREAL
159
+ IMSIN
160
+ IMSQRT
161
+ IMSUB
162
+ IMSUM
163
+ INDEX
164
+ INDIRECT
165
+ INFO
166
+ INT
167
+ INTERCEPT
168
+ INTRATE
169
+ IPMT
170
+ IRR
171
+ ISBLANK
172
+ ISERR
173
+ ISERROR
174
+ ISEVEN
175
+ ISLOGICAL
176
+ ISNA
177
+ ISNONTEXT
178
+ ISNUMBER
179
+ ISODD
180
+ ISPMT
181
+ ISREF
182
+ ISTEXT
183
+ JIS
184
+ KURT
185
+ LARGE
186
+ LCM
187
+ LEFT
188
+ LEFTB
189
+ LEN
190
+ LENB
191
+ LINEST
192
+ LN
193
+ LOG
194
+ LOG10
195
+ LOGEST
196
+ LOGINV
197
+ LOGNORMDIST
198
+ LOOKUP
199
+ LOWER
200
+ MATCH
201
+ MAX
202
+ MAXA
203
+ MDETERM
204
+ MDURATION
205
+ MEDIAN
206
+ MID
207
+ MIDB
208
+ MIN
209
+ MINA
210
+ MINUTE
211
+ MINVERSE
212
+ MIRR
213
+ MMULT
214
+ MOD
215
+ MODE
216
+ MONTH
217
+ MROUND
218
+ MULTINOMIAL
219
+ N
220
+ NA
221
+ NEGBINOMDIST
222
+ NETWORKDAYS
223
+ NOMINAL
224
+ NORMDIST
225
+ NORMINV
226
+ NORMSDIST
227
+ NORMSINV
228
+ NOT
229
+ NOW
230
+ NPER
231
+ NPV
232
+ OCT2BIN
233
+ OCT2DEC
234
+ OCT2HEX
235
+ ODD
236
+ ODDFPRICE
237
+ ODDFYIELD
238
+ ODDLPRICE
239
+ ODDLYIELD
240
+ OFFSET
241
+ OR
242
+ PEARSON
243
+ PERCENTILE
244
+ PERCENTRANK
245
+ PERMUT
246
+ PHONETIC
247
+ PI
248
+ PMT
249
+ POISSON
250
+ POWER
251
+ PPMT
252
+ PRICE
253
+ PRICEDISC
254
+ PRICEMAT
255
+ PROB
256
+ PRODUCT
257
+ PROPER
258
+ PV
259
+ QUARTILE
260
+ QUOTIENT
261
+ RADIANS
262
+ RAND
263
+ RANDBETWEEN
264
+ RANK
265
+ RATE
266
+ RECEIVED
267
+ REPLACE
268
+ REPLACEB
269
+ REPT
270
+ RIGHT
271
+ RIGHTB
272
+ ROMAN
273
+ ROUND
274
+ ROUNDDOWN
275
+ ROUNDUP
276
+ ROW
277
+ ROWS
278
+ RSQ
279
+ RTD
280
+ SEARCH
281
+ SEARCHB
282
+ SECOND
283
+ SERIESSUM
284
+ SIGN
285
+ SIN
286
+ SINH
287
+ SKEW
288
+ SLN
289
+ SLOPE
290
+ SMALL
291
+ SQRT
292
+ SQRTPI
293
+ STANDARDIZE
294
+ STDEV
295
+ STDEVA
296
+ STDEVP
297
+ STDEVPA
298
+ STEYX
299
+ SUBSTITUTE
300
+ SUBTOTAL
301
+ SUM
302
+ SUMIF
303
+ SUMIFS
304
+ SUMPRODUCT
305
+ SUMSQ
306
+ SUMX2MY2
307
+ SUMX2PY2
308
+ SUMXMY2
309
+ SYD
310
+ T
311
+ TAN
312
+ TANH
313
+ TBILLEQ
314
+ TBILLPRICE
315
+ TBILLYIELD
316
+ TDIST
317
+ TEXT
318
+ TIME
319
+ TIMEVALUE
320
+ TINV
321
+ TODAY
322
+ TRANSPOSE
323
+ TREND
324
+ TRIM
325
+ TRIMMEAN
326
+ TRUE
327
+ TRUNC
328
+ TTEST
329
+ TYPE
330
+ UPPER
331
+ USDOLLAR
332
+ VALUE
333
+ VAR
334
+ VARA
335
+ VARP
336
+ VARPA
337
+ VDB
338
+ VERSION
339
+ VLOOKUP
340
+ WEEKDAY
341
+ WEEKNUM
342
+ WEIBULL
343
+ WORKDAY
344
+ XIRR
345
+ XNPV
346
+ YEAR
347
+ YEARFRAC
348
+ YIELD
349
+ YIELDDISC
350
+ YIELDMAT
351
+ ZTEST
libraries/PHPExcel/Cell.php ADDED
@@ -0,0 +1,1022 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Cell
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Cell
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Cell
37
+ {
38
+
39
+ /**
40
+ * Default range variable constant
41
+ *
42
+ * @var string
43
+ */
44
+ const DEFAULT_RANGE = 'A1:A1';
45
+
46
+ /**
47
+ * Value binder to use
48
+ *
49
+ * @var PHPExcel_Cell_IValueBinder
50
+ */
51
+ private static $_valueBinder = NULL;
52
+
53
+ /**
54
+ * Value of the cell
55
+ *
56
+ * @var mixed
57
+ */
58
+ private $_value;
59
+
60
+ /**
61
+ * Calculated value of the cell (used for caching)
62
+ * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
63
+ * create the original spreadsheet file.
64
+ * Note that this value is not guaranteed to reflect the actual calculated value because it is
65
+ * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
66
+ * values used by the formula have changed since it was last calculated.
67
+ *
68
+ * @var mixed
69
+ */
70
+ private $_calculatedValue = NULL;
71
+
72
+ /**
73
+ * Type of the cell data
74
+ *
75
+ * @var string
76
+ */
77
+ private $_dataType;
78
+
79
+ /**
80
+ * Parent worksheet
81
+ *
82
+ * @var PHPExcel_CachedObjectStorage_CacheBase
83
+ */
84
+ private $_parent;
85
+
86
+ /**
87
+ * Index to cellXf
88
+ *
89
+ * @var int
90
+ */
91
+ private $_xfIndex = 0;
92
+
93
+ /**
94
+ * Attributes of the formula
95
+ *
96
+ */
97
+ private $_formulaAttributes;
98
+
99
+
100
+ /**
101
+ * Send notification to the cache controller
102
+ *
103
+ * @return void
104
+ **/
105
+ public function notifyCacheController() {
106
+ $this->_parent->updateCacheData($this);
107
+
108
+ return $this;
109
+ }
110
+
111
+ public function detach() {
112
+ $this->_parent = NULL;
113
+ }
114
+
115
+ public function attach(PHPExcel_CachedObjectStorage_CacheBase $parent) {
116
+ $this->_parent = $parent;
117
+ }
118
+
119
+
120
+ /**
121
+ * Create a new Cell
122
+ *
123
+ * @param mixed $pValue
124
+ * @param string $pDataType
125
+ * @param PHPExcel_Worksheet $pSheet
126
+ * @throws PHPExcel_Exception
127
+ */
128
+ public function __construct($pValue = NULL, $pDataType = NULL, PHPExcel_Worksheet $pSheet = NULL)
129
+ {
130
+ // Initialise cell value
131
+ $this->_value = $pValue;
132
+
133
+ // Set worksheet cache
134
+ $this->_parent = $pSheet->getCellCacheController();
135
+
136
+ // Set datatype?
137
+ if ($pDataType !== NULL) {
138
+ if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2)
139
+ $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
140
+ $this->_dataType = $pDataType;
141
+ } elseif (!self::getValueBinder()->bindValue($this, $pValue)) {
142
+ throw new PHPExcel_Exception("Value could not be bound to cell.");
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Get cell coordinate column
148
+ *
149
+ * @return string
150
+ */
151
+ public function getColumn()
152
+ {
153
+ return $this->_parent->getCurrentColumn();
154
+ }
155
+
156
+ /**
157
+ * Get cell coordinate row
158
+ *
159
+ * @return int
160
+ */
161
+ public function getRow()
162
+ {
163
+ return $this->_parent->getCurrentRow();
164
+ }
165
+
166
+ /**
167
+ * Get cell coordinate
168
+ *
169
+ * @return string
170
+ */
171
+ public function getCoordinate()
172
+ {
173
+ return $this->_parent->getCurrentAddress();
174
+ }
175
+
176
+ /**
177
+ * Get cell value
178
+ *
179
+ * @return mixed
180
+ */
181
+ public function getValue()
182
+ {
183
+ return $this->_value;
184
+ }
185
+
186
+ /**
187
+ * Get cell value with formatting
188
+ *
189
+ * @return string
190
+ */
191
+ public function getFormattedValue()
192
+ {
193
+ return (string) PHPExcel_Style_NumberFormat::toFormattedString(
194
+ $this->getCalculatedValue(),
195
+ $this->getStyle()
196
+ ->getNumberFormat()->getFormatCode()
197
+ );
198
+ }
199
+
200
+ /**
201
+ * Set cell value
202
+ *
203
+ * Sets the value for a cell, automatically determining the datatype using the value binder
204
+ *
205
+ * @param mixed $pValue Value
206
+ * @return PHPExcel_Cell
207
+ * @throws PHPExcel_Exception
208
+ */
209
+ public function setValue($pValue = NULL)
210
+ {
211
+ if (!self::getValueBinder()->bindValue($this, $pValue)) {
212
+ throw new PHPExcel_Exception("Value could not be bound to cell.");
213
+ }
214
+ return $this;
215
+ }
216
+
217
+ /**
218
+ * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder)
219
+ *
220
+ * @param mixed $pValue Value
221
+ * @param string $pDataType Explicit data type
222
+ * @return PHPExcel_Cell
223
+ * @throws PHPExcel_Exception
224
+ */
225
+ public function setValueExplicit($pValue = NULL, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
226
+ {
227
+ // set the value according to data type
228
+ switch ($pDataType) {
229
+ case PHPExcel_Cell_DataType::TYPE_NULL:
230
+ $this->_value = $pValue;
231
+ break;
232
+ case PHPExcel_Cell_DataType::TYPE_STRING2:
233
+ $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
234
+ case PHPExcel_Cell_DataType::TYPE_STRING:
235
+ case PHPExcel_Cell_DataType::TYPE_INLINE:
236
+ $this->_value = PHPExcel_Cell_DataType::checkString($pValue);
237
+ break;
238
+ case PHPExcel_Cell_DataType::TYPE_NUMERIC:
239
+ $this->_value = (float)$pValue;
240
+ break;
241
+ case PHPExcel_Cell_DataType::TYPE_FORMULA:
242
+ $this->_value = (string)$pValue;
243
+ break;
244
+ case PHPExcel_Cell_DataType::TYPE_BOOL:
245
+ $this->_value = (bool)$pValue;
246
+ break;
247
+ case PHPExcel_Cell_DataType::TYPE_ERROR:
248
+ $this->_value = PHPExcel_Cell_DataType::checkErrorCode($pValue);
249
+ break;
250
+ default:
251
+ throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType);
252
+ break;
253
+ }
254
+
255
+ // set the datatype
256
+ $this->_dataType = $pDataType;
257
+
258
+ return $this->notifyCacheController();
259
+ }
260
+
261
+ /**
262
+ * Get calculated cell value
263
+ *
264
+ * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
265
+ *
266
+ * @param boolean $resetLog Whether the calculation engine logger should be reset or not
267
+ * @return mixed
268
+ * @throws PHPExcel_Exception
269
+ */
270
+ public function getCalculatedValue($resetLog = TRUE)
271
+ {
272
+ //echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().PHP_EOL;
273
+ if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) {
274
+ try {
275
+ //echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL;
276
+ $result = PHPExcel_Calculation::getInstance(
277
+ $this->getWorksheet()->getParent()
278
+ )->calculateCellValue($this,$resetLog);
279
+ //echo $this->getCoordinate().' calculation result is '.$result.PHP_EOL;
280
+ // We don't yet handle array returns
281
+ if (is_array($result)) {
282
+ while (is_array($result)) {
283
+ $result = array_pop($result);
284
+ }
285
+ }
286
+ } catch ( PHPExcel_Exception $ex ) {
287
+ if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->_calculatedValue !== NULL)) {
288
+ //echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
289
+ return $this->_calculatedValue; // Fallback for calculations referencing external files.
290
+ }
291
+ //echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL;
292
+ $result = '#N/A';
293
+ throw new PHPExcel_Calculation_Exception(
294
+ $this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage()
295
+ );
296
+ }
297
+
298
+ if ($result === '#Not Yet Implemented') {
299
+ //echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL;
300
+ return $this->_calculatedValue; // Fallback if calculation engine does not support the formula.
301
+ }
302
+ //echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL;
303
+ return $result;
304
+ } elseif($this->_value instanceof PHPExcel_RichText) {
305
+ // echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->_value.'<br />';
306
+ return $this->_value->getPlainText();
307
+ }
308
+ // echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'<br />';
309
+ return $this->_value;
310
+ }
311
+
312
+ /**
313
+ * Set old calculated value (cached)
314
+ *
315
+ * @param mixed $pValue Value
316
+ * @return PHPExcel_Cell
317
+ */
318
+ public function setCalculatedValue($pValue = NULL)
319
+ {
320
+ if ($pValue !== NULL) {
321
+ $this->_calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue;
322
+ }
323
+
324
+ return $this->notifyCacheController();
325
+ }
326
+
327
+ /**
328
+ * Get old calculated value (cached)
329
+ * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
330
+ * create the original spreadsheet file.
331
+ * Note that this value is not guaranteed to refelect the actual calculated value because it is
332
+ * possible that auto-calculation was disabled in the original spreadsheet, and underlying data
333
+ * values used by the formula have changed since it was last calculated.
334
+ *
335
+ * @return mixed
336
+ */
337
+ public function getOldCalculatedValue()
338
+ {
339
+ return $this->_calculatedValue;
340
+ }
341
+
342
+ /**
343
+ * Get cell data type
344
+ *
345
+ * @return string
346
+ */
347
+ public function getDataType()
348
+ {
349
+ return $this->_dataType;
350
+ }
351
+
352
+ /**
353
+ * Set cell data type
354
+ *
355
+ * @param string $pDataType
356
+ * @return PHPExcel_Cell
357
+ */
358
+ public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING)
359
+ {
360
+ if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2)
361
+ $pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
362
+
363
+ $this->_dataType = $pDataType;
364
+
365
+ return $this->notifyCacheController();
366
+ }
367
+
368
+ /**
369
+ * Identify if the cell contains a formula
370
+ *
371
+ * @return boolean
372
+ */
373
+ public function isFormula()
374
+ {
375
+ return $this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA;
376
+ }
377
+
378
+ /**
379
+ * Does this cell contain Data validation rules?
380
+ *
381
+ * @return boolean
382
+ * @throws PHPExcel_Exception
383
+ */
384
+ public function hasDataValidation()
385
+ {
386
+ if (!isset($this->_parent)) {
387
+ throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet');
388
+ }
389
+
390
+ return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
391
+ }
392
+
393
+ /**
394
+ * Get Data validation rules
395
+ *
396
+ * @return PHPExcel_Cell_DataValidation
397
+ * @throws PHPExcel_Exception
398
+ */
399
+ public function getDataValidation()
400
+ {
401
+ if (!isset($this->_parent)) {
402
+ throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet');
403
+ }
404
+
405
+ return $this->getWorksheet()->getDataValidation($this->getCoordinate());
406
+ }
407
+
408
+ /**
409
+ * Set Data validation rules
410
+ *
411
+ * @param PHPExcel_Cell_DataValidation $pDataValidation
412
+ * @return PHPExcel_Cell
413
+ * @throws PHPExcel_Exception
414
+ */
415
+ public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = NULL)
416
+ {
417
+ if (!isset($this->_parent)) {
418
+ throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet');
419
+ }
420
+
421
+ $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation);
422
+
423
+ return $this->notifyCacheController();
424
+ }
425
+
426
+ /**
427
+ * Does this cell contain a Hyperlink?
428
+ *
429
+ * @return boolean
430
+ * @throws PHPExcel_Exception
431
+ */
432
+ public function hasHyperlink()
433
+ {
434
+ if (!isset($this->_parent)) {
435
+ throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet');
436
+ }
437
+
438
+ return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
439
+ }
440
+
441
+ /**
442
+ * Get Hyperlink
443
+ *
444
+ * @return PHPExcel_Cell_Hyperlink
445
+ * @throws PHPExcel_Exception
446
+ */
447
+ public function getHyperlink()
448
+ {
449
+ if (!isset($this->_parent)) {
450
+ throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet');
451
+ }
452
+
453
+ return $this->getWorksheet()->getHyperlink($this->getCoordinate());
454
+ }
455
+
456
+ /**
457
+ * Set Hyperlink
458
+ *
459
+ * @param PHPExcel_Cell_Hyperlink $pHyperlink
460
+ * @return PHPExcel_Cell
461
+ * @throws PHPExcel_Exception
462
+ */
463
+ public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = NULL)
464
+ {
465
+ if (!isset($this->_parent)) {
466
+ throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet');
467
+ }
468
+
469
+ $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink);
470
+
471
+ return $this->notifyCacheController();
472
+ }
473
+
474
+ /**
475
+ * Get parent worksheet
476
+ *
477
+ * @return PHPExcel_CachedObjectStorage_CacheBase
478
+ */
479
+ public function getParent() {
480
+ return $this->_parent;
481
+ }
482
+
483
+ /**
484
+ * Get parent worksheet
485
+ *
486
+ * @return PHPExcel_Worksheet
487
+ */
488
+ public function getWorksheet() {
489
+ return $this->_parent->getParent();
490
+ }
491
+
492
+ /**
493
+ * Is this cell in a merge range
494
+ *
495
+ * @return boolean
496
+ */
497
+ public function isInMergeRange() {
498
+ return (boolean) $this->getMergeRange();
499
+ }
500
+
501
+ /**
502
+ * Is this cell the master (top left cell) in a merge range (that holds the actual data value)
503
+ *
504
+ * @return boolean
505
+ */
506
+ public function isMergeRangeValueCell() {
507
+ if ($mergeRange = $this->getMergeRange()) {
508
+ $mergeRange = PHPExcel_Cell::splitRange($mergeRange);
509
+ list($startCell) = $mergeRange[0];
510
+ if ($this->getCoordinate() === $startCell) {
511
+ return true;
512
+ }
513
+ }
514
+ return false;
515
+ }
516
+
517
+ /**
518
+ * If this cell is in a merge range, then return the range
519
+ *
520
+ * @return string
521
+ */
522
+ public function getMergeRange() {
523
+ foreach($this->getWorksheet()->getMergeCells() as $mergeRange) {
524
+ if ($this->isInRange($mergeRange)) {
525
+ return $mergeRange;
526
+ }
527
+ }
528
+ return false;
529
+ }
530
+
531
+ /**
532
+ * Get cell style
533
+ *
534
+ * @return PHPExcel_Style
535
+ */
536
+ public function getStyle()
537
+ {
538
+ return $this->getWorksheet()->getStyle($this->getCoordinate());
539
+ }
540
+
541
+ /**
542
+ * Re-bind parent
543
+ *
544
+ * @param PHPExcel_Worksheet $parent
545
+ * @return PHPExcel_Cell
546
+ */
547
+ public function rebindParent(PHPExcel_Worksheet $parent) {
548
+ $this->_parent = $parent->getCellCacheController();
549
+
550
+ return $this->notifyCacheController();
551
+ }
552
+
553
+ /**
554
+ * Is cell in a specific range?
555
+ *
556
+ * @param string $pRange Cell range (e.g. A1:A1)
557
+ * @return boolean
558
+ */
559
+ public function isInRange($pRange = 'A1:A1')
560
+ {
561
+ list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange);
562
+
563
+ // Translate properties
564
+ $myColumn = self::columnIndexFromString($this->getColumn());
565
+ $myRow = $this->getRow();
566
+
567
+ // Verify if cell is in range
568
+ return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) &&
569
+ ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow)
570
+ );
571
+ }
572
+
573
+ /**
574
+ * Coordinate from string
575
+ *
576
+ * @param string $pCoordinateString
577
+ * @return array Array containing column and row (indexes 0 and 1)
578
+ * @throws PHPExcel_Exception
579
+ */
580
+ public static function coordinateFromString($pCoordinateString = 'A1')
581
+ {
582
+ if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) {
583
+ return array($matches[1],$matches[2]);
584
+ } elseif ((strpos($pCoordinateString,':') !== FALSE) || (strpos($pCoordinateString,',') !== FALSE)) {
585
+ throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
586
+ } elseif ($pCoordinateString == '') {
587
+ throw new PHPExcel_Exception('Cell coordinate can not be zero-length string');
588
+ }
589
+
590
+ throw new PHPExcel_Exception('Invalid cell coordinate '.$pCoordinateString);
591
+ }
592
+
593
+ /**
594
+ * Make string row, column or cell coordinate absolute
595
+ *
596
+ * @param string $pCoordinateString e.g. 'A' or '1' or 'A1'
597
+ * Note that this value can be a row or column reference as well as a cell reference
598
+ * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1'
599
+ * @throws PHPExcel_Exception
600
+ */
601
+ public static function absoluteReference($pCoordinateString = 'A1')
602
+ {
603
+ if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) {
604
+ // Split out any worksheet name from the reference
605
+ $worksheet = '';
606
+ $cellAddress = explode('!',$pCoordinateString);
607
+ if (count($cellAddress) > 1) {
608
+ list($worksheet,$pCoordinateString) = $cellAddress;
609
+ }
610
+ if ($worksheet > '') $worksheet .= '!';
611
+
612
+ // Create absolute coordinate
613
+ if (ctype_digit($pCoordinateString)) {
614
+ return $worksheet . '$' . $pCoordinateString;
615
+ } elseif (ctype_alpha($pCoordinateString)) {
616
+ return $worksheet . '$' . strtoupper($pCoordinateString);
617
+ }
618
+ return $worksheet . self::absoluteCoordinate($pCoordinateString);
619
+ }
620
+
621
+ throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
622
+ }
623
+
624
+ /**
625
+ * Make string coordinate absolute
626
+ *
627
+ * @param string $pCoordinateString e.g. 'A1'
628
+ * @return string Absolute coordinate e.g. '$A$1'
629
+ * @throws PHPExcel_Exception
630
+ */
631
+ public static function absoluteCoordinate($pCoordinateString = 'A1')
632
+ {
633
+ if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) {
634
+ // Split out any worksheet name from the coordinate
635
+ $worksheet = '';
636
+ $cellAddress = explode('!',$pCoordinateString);
637
+ if (count($cellAddress) > 1) {
638
+ list($worksheet,$pCoordinateString) = $cellAddress;
639
+ }
640
+ if ($worksheet > '') $worksheet .= '!';
641
+
642
+ // Create absolute coordinate
643
+ list($column, $row) = self::coordinateFromString($pCoordinateString);
644
+ $column = ltrim($column,'$');
645
+ $row = ltrim($row,'$');
646
+ return $worksheet . '$' . $column . '$' . $row;
647
+ }
648
+
649
+ throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells');
650
+ }
651
+
652
+ /**
653
+ * Split range into coordinate strings
654
+ *
655
+ * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
656
+ * @return array Array containg one or more arrays containing one or two coordinate strings
657
+ * e.g. array('B4','D9') or array(array('B4','D9'),array('H2','O11'))
658
+ * or array('B4')
659
+ */
660
+ public static function splitRange($pRange = 'A1:A1')
661
+ {
662
+ // Ensure $pRange is a valid range
663
+ if(empty($pRange)) {
664
+ $pRange = self::DEFAULT_RANGE;
665
+ }
666
+
667
+ $exploded = explode(',', $pRange);
668
+ $counter = count($exploded);
669
+ for ($i = 0; $i < $counter; ++$i) {
670
+ $exploded[$i] = explode(':', $exploded[$i]);
671
+ }
672
+ return $exploded;
673
+ }
674
+
675
+ /**
676
+ * Build range from coordinate strings
677
+ *
678
+ * @param array $pRange Array containg one or more arrays containing one or two coordinate strings
679
+ * @return string String representation of $pRange
680
+ * @throws PHPExcel_Exception
681
+ */
682
+ public static function buildRange($pRange)
683
+ {
684
+ // Verify range
685
+ if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) {
686
+ throw new PHPExcel_Exception('Range does not contain any information');
687
+ }
688
+
689
+ // Build range
690
+ $imploded = array();
691
+ $counter = count($pRange);
692
+ for ($i = 0; $i < $counter; ++$i) {
693
+ $pRange[$i] = implode(':', $pRange[$i]);
694
+ }
695
+ $imploded = implode(',', $pRange);
696
+
697
+ return $imploded;
698
+ }
699
+
700
+ /**
701
+ * Calculate range boundaries
702
+ *
703
+ * @param string $pRange Cell range (e.g. A1:A1)
704
+ * @return array Range coordinates array(Start Cell, End Cell)
705
+ * where Start Cell and End Cell are arrays (Column Number, Row Number)
706
+ */
707
+ public static function rangeBoundaries($pRange = 'A1:A1')
708
+ {
709
+ // Ensure $pRange is a valid range
710
+ if(empty($pRange)) {
711
+ $pRange = self::DEFAULT_RANGE;
712
+ }
713
+
714
+ // Uppercase coordinate
715
+ $pRange = strtoupper($pRange);
716
+
717
+ // Extract range
718
+ if (strpos($pRange, ':') === FALSE) {
719
+ $rangeA = $rangeB = $pRange;
720
+ } else {
721
+ list($rangeA, $rangeB) = explode(':', $pRange);
722
+ }
723
+
724
+ // Calculate range outer borders
725
+ $rangeStart = self::coordinateFromString($rangeA);
726
+ $rangeEnd = self::coordinateFromString($rangeB);
727
+
728
+ // Translate column into index
729
+ $rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
730
+ $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
731
+
732
+ return array($rangeStart, $rangeEnd);
733
+ }
734
+
735
+ /**
736
+ * Calculate range dimension
737
+ *
738
+ * @param string $pRange Cell range (e.g. A1:A1)
739
+ * @return array Range dimension (width, height)
740
+ */
741
+ public static function rangeDimension($pRange = 'A1:A1')
742
+ {
743
+ // Calculate range outer borders
744
+ list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange);
745
+
746
+ return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) );
747
+ }
748
+
749
+ /**
750
+ * Calculate range boundaries
751
+ *
752
+ * @param string $pRange Cell range (e.g. A1:A1)
753
+ * @return array Range coordinates array(Start Cell, End Cell)
754
+ * where Start Cell and End Cell are arrays (Column ID, Row Number)
755
+ */
756
+ public static function getRangeBoundaries($pRange = 'A1:A1')
757
+ {
758
+ // Ensure $pRange is a valid range
759
+ if(empty($pRange)) {
760
+ $pRange = self::DEFAULT_RANGE;
761
+ }
762
+
763
+ // Uppercase coordinate
764
+ $pRange = strtoupper($pRange);
765
+
766
+ // Extract range
767
+ if (strpos($pRange, ':') === FALSE) {
768
+ $rangeA = $rangeB = $pRange;
769
+ } else {
770
+ list($rangeA, $rangeB) = explode(':', $pRange);
771
+ }
772
+
773
+ return array( self::coordinateFromString($rangeA), self::coordinateFromString($rangeB));
774
+ }
775
+
776
+ /**
777
+ * Column index from string
778
+ *
779
+ * @param string $pString
780
+ * @return int Column index (base 1 !!!)
781
+ */
782
+ public static function columnIndexFromString($pString = 'A')
783
+ {
784
+ // Using a lookup cache adds a slight memory overhead, but boosts speed
785
+ // caching using a static within the method is faster than a class static,
786
+ // though it's additional memory overhead
787
+ static $_indexCache = array();
788
+
789
+ if (isset($_indexCache[$pString]))
790
+ return $_indexCache[$pString];
791
+
792
+ // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord()
793
+ // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant
794
+ // memory overhead either
795
+ static $_columnLookup = array(
796
+ 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13,
797
+ 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
798
+ 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13,
799
+ 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26
800
+ );
801
+
802
+ // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString
803
+ // for improved performance
804
+ if (isset($pString{0})) {
805
+ if (!isset($pString{1})) {
806
+ $_indexCache[$pString] = $_columnLookup[$pString];
807
+ return $_indexCache[$pString];
808
+ } elseif(!isset($pString{2})) {
809
+ $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}];
810
+ return $_indexCache[$pString];
811
+ } elseif(!isset($pString{3})) {
812
+ $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}];
813
+ return $_indexCache[$pString];
814
+ }
815
+ }
816
+ throw new PHPExcel_Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty"));
817
+ }
818
+
819
+ /**
820
+ * String from columnindex
821
+ *
822
+ * @param int $pColumnIndex Column index (base 0 !!!)
823
+ * @return string
824
+ */
825
+ public static function stringFromColumnIndex($pColumnIndex = 0)
826
+ {
827
+ // Using a lookup cache adds a slight memory overhead, but boosts speed
828
+ // caching using a static within the method is faster than a class static,
829
+ // though it's additional memory overhead
830
+ static $_indexCache = array();
831
+
832
+ if (!isset($_indexCache[$pColumnIndex])) {
833
+ // Determine column string
834
+ if ($pColumnIndex < 26) {
835
+ $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
836
+ } elseif ($pColumnIndex < 702) {
837
+ $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) .
838
+ chr(65 + $pColumnIndex % 26);
839
+ } else {
840
+ $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) .
841
+ chr(65 + ((($pColumnIndex - 26) % 676) / 26)) .
842
+ chr(65 + $pColumnIndex % 26);
843
+ }
844
+ }
845
+ return $_indexCache[$pColumnIndex];
846
+ }
847
+
848
+ /**
849
+ * Extract all cell references in range
850
+ *
851
+ * @param string $pRange Range (e.g. A1 or A1:C10 or A1:E10 A20:E25)
852
+ * @return array Array containing single cell references
853
+ */
854
+ public static function extractAllCellReferencesInRange($pRange = 'A1') {
855
+ // Returnvalue
856
+ $returnValue = array();
857
+
858
+ // Explode spaces
859
+ $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange)));
860
+ foreach ($cellBlocks as $cellBlock) {
861
+ // Single cell?
862
+ if (strpos($cellBlock,':') === FALSE && strpos($cellBlock,',') === FALSE) {
863
+ $returnValue[] = $cellBlock;
864
+ continue;
865
+ }
866
+
867
+ // Range...
868
+ $ranges = self::splitRange($cellBlock);
869
+ foreach($ranges as $range) {
870
+ // Single cell?
871
+ if (!isset($range[1])) {
872
+ $returnValue[] = $range[0];
873
+ continue;
874
+ }
875
+
876
+ // Range...
877
+ list($rangeStart, $rangeEnd) = $range;
878
+ sscanf($rangeStart,'%[A-Z]%d', $startCol, $startRow);
879
+ sscanf($rangeEnd,'%[A-Z]%d', $endCol, $endRow);
880
+ $endCol++;
881
+
882
+ // Current data
883
+ $currentCol = $startCol;
884
+ $currentRow = $startRow;
885
+
886
+ // Loop cells
887
+ while ($currentCol != $endCol) {
888
+ while ($currentRow <= $endRow) {
889
+ $returnValue[] = $currentCol.$currentRow;
890
+ ++$currentRow;
891
+ }
892
+ ++$currentCol;
893
+ $currentRow = $startRow;
894
+ }
895
+ }
896
+ }
897
+
898
+ // Sort the result by column and row
899
+ $sortKeys = array();
900
+ foreach (array_unique($returnValue) as $coord) {
901
+ sscanf($coord,'%[A-Z]%d', $column, $row);
902
+ $sortKeys[sprintf('%3s%09d',$column,$row)] = $coord;
903
+ }
904
+ ksort($sortKeys);
905
+
906
+ // Return value
907
+ return array_values($sortKeys);
908
+ }
909
+
910
+ /**
911
+ * Compare 2 cells
912
+ *
913
+ * @param PHPExcel_Cell $a Cell a
914
+ * @param PHPExcel_Cell $b Cell b
915
+ * @return int Result of comparison (always -1 or 1, never zero!)
916
+ */
917
+ public static function compareCells(PHPExcel_Cell $a, PHPExcel_Cell $b)
918
+ {
919
+ if ($a->getRow() < $b->getRow()) {
920
+ return -1;
921
+ } elseif ($a->getRow() > $b->getRow()) {
922
+ return 1;
923
+ } elseif (self::columnIndexFromString($a->getColumn()) < self::columnIndexFromString($b->getColumn())) {
924
+ return -1;
925
+ } else {
926
+ return 1;
927
+ }
928
+ }
929
+
930
+ /**
931
+ * Get value binder to use
932
+ *
933
+ * @return PHPExcel_Cell_IValueBinder
934
+ */
935
+ public static function getValueBinder() {
936
+ if (self::$_valueBinder === NULL) {
937
+ self::$_valueBinder = new PHPExcel_Cell_DefaultValueBinder();
938
+ }
939
+
940
+ return self::$_valueBinder;
941
+ }
942
+
943
+ /**
944
+ * Set value binder to use
945
+ *
946
+ * @param PHPExcel_Cell_IValueBinder $binder
947
+ * @throws PHPExcel_Exception
948
+ */
949
+ public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = NULL) {
950
+ if ($binder === NULL) {
951
+ throw new PHPExcel_Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly.");
952
+ }
953
+
954
+ self::$_valueBinder = $binder;
955
+ }
956
+
957
+ /**
958
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
959
+ */
960
+ public function __clone() {
961
+ $vars = get_object_vars($this);
962
+ foreach ($vars as $key => $value) {
963
+ if ((is_object($value)) && ($key != '_parent')) {
964
+ $this->$key = clone $value;
965
+ } else {
966
+ $this->$key = $value;
967
+ }
968
+ }
969
+ }
970
+
971
+ /**
972
+ * Get index to cellXf
973
+ *
974
+ * @return int
975
+ */
976
+ public function getXfIndex()
977
+ {
978
+ return $this->_xfIndex;
979
+ }
980
+
981
+ /**
982
+ * Set index to cellXf
983
+ *
984
+ * @param int $pValue
985
+ * @return PHPExcel_Cell
986
+ */
987
+ public function setXfIndex($pValue = 0)
988
+ {
989
+ $this->_xfIndex = $pValue;
990
+
991
+ return $this->notifyCacheController();
992
+ }
993
+
994
+ /**
995
+ * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
996
+ */
997
+ public function setFormulaAttributes($pAttributes)
998
+ {
999
+ $this->_formulaAttributes = $pAttributes;
1000
+ return $this;
1001
+ }
1002
+
1003
+ /**
1004
+ * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling
1005
+ */
1006
+ public function getFormulaAttributes()
1007
+ {
1008
+ return $this->_formulaAttributes;
1009
+ }
1010
+
1011
+ /**
1012
+ * Convert to string
1013
+ *
1014
+ * @return string
1015
+ */
1016
+ public function __toString()
1017
+ {
1018
+ return (string) $this->getValue();
1019
+ }
1020
+
1021
+ }
1022
+
libraries/PHPExcel/Cell/AdvancedValueBinder.php ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Cell_AdvancedValueBinder
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Cell
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Cell_AdvancedValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
47
+ {
48
+ /**
49
+ * Bind value to a cell
50
+ *
51
+ * @param PHPExcel_Cell $cell Cell to bind value to
52
+ * @param mixed $value Value to bind in cell
53
+ * @return boolean
54
+ */
55
+ public function bindValue(PHPExcel_Cell $cell, $value = null)
56
+ {
57
+ // sanitize UTF-8 strings
58
+ if (is_string($value)) {
59
+ $value = PHPExcel_Shared_String::SanitizeUTF8($value);
60
+ }
61
+
62
+ // Find out data type
63
+ $dataType = parent::dataTypeForValue($value);
64
+
65
+ // Style logic - strings
66
+ if ($dataType === PHPExcel_Cell_DataType::TYPE_STRING && !$value instanceof PHPExcel_RichText) {
67
+ // Test for booleans using locale-setting
68
+ if ($value == PHPExcel_Calculation::getTRUE()) {
69
+ $cell->setValueExplicit( TRUE, PHPExcel_Cell_DataType::TYPE_BOOL);
70
+ return true;
71
+ } elseif($value == PHPExcel_Calculation::getFALSE()) {
72
+ $cell->setValueExplicit( FALSE, PHPExcel_Cell_DataType::TYPE_BOOL);
73
+ return true;
74
+ }
75
+
76
+ // Check for number in scientific format
77
+ if (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NUMBER.'$/', $value)) {
78
+ $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
79
+ return true;
80
+ }
81
+
82
+ // Check for fraction
83
+ if (preg_match('/^([+-]?)\s*([0-9]+)\s?\/\s*([0-9]+)$/', $value, $matches)) {
84
+ // Convert value to number
85
+ $value = $matches[2] / $matches[3];
86
+ if ($matches[1] == '-') $value = 0 - $value;
87
+ $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
88
+ // Set style
89
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
90
+ ->getNumberFormat()->setFormatCode( '??/??' );
91
+ return true;
92
+ } elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) {
93
+ // Convert value to number
94
+ $value = $matches[2] + ($matches[3] / $matches[4]);
95
+ if ($matches[1] == '-') $value = 0 - $value;
96
+ $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
97
+ // Set style
98
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
99
+ ->getNumberFormat()->setFormatCode( '# ??/??' );
100
+ return true;
101
+ }
102
+
103
+ // Check for percentage
104
+ if (preg_match('/^\-?[0-9]*\.?[0-9]*\s?\%$/', $value)) {
105
+ // Convert value to number
106
+ $value = (float) str_replace('%', '', $value) / 100;
107
+ $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
108
+ // Set style
109
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
110
+ ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 );
111
+ return true;
112
+ }
113
+
114
+ // Check for currency
115
+ $currencyCode = PHPExcel_Shared_String::getCurrencyCode();
116
+ $decimalSeparator = PHPExcel_Shared_String::getDecimalSeparator();
117
+ $thousandsSeparator = PHPExcel_Shared_String::getThousandsSeparator();
118
+ if (preg_match('/^'.preg_quote($currencyCode).' *(\d{1,3}('.preg_quote($thousandsSeparator).'\d{3})*|(\d+))('.preg_quote($decimalSeparator).'\d{2})?$/', $value)) {
119
+ // Convert value to number
120
+ $value = (float) trim(str_replace(array($currencyCode, $thousandsSeparator, $decimalSeparator), array('', '', '.'), $value));
121
+ $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
122
+ // Set style
123
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
124
+ ->getNumberFormat()->setFormatCode(
125
+ str_replace('$', $currencyCode, PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE )
126
+ );
127
+ return true;
128
+ } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) {
129
+ // Convert value to number
130
+ $value = (float) trim(str_replace(array('$',','), '', $value));
131
+ $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
132
+ // Set style
133
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
134
+ ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE );
135
+ return true;
136
+ }
137
+
138
+ // Check for time without seconds e.g. '9:45', '09:45'
139
+ if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) {
140
+ // Convert value to number
141
+ list($h, $m) = explode(':', $value);
142
+ $days = $h / 24 + $m / 1440;
143
+ $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC);
144
+ // Set style
145
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
146
+ ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 );
147
+ return true;
148
+ }
149
+
150
+ // Check for time with seconds '9:45:59', '09:45:59'
151
+ if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) {
152
+ // Convert value to number
153
+ list($h, $m, $s) = explode(':', $value);
154
+ $days = $h / 24 + $m / 1440 + $s / 86400;
155
+ // Convert value to number
156
+ $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC);
157
+ // Set style
158
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
159
+ ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 );
160
+ return true;
161
+ }
162
+
163
+ // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10'
164
+ if (($d = PHPExcel_Shared_Date::stringToExcel($value)) !== false) {
165
+ // Convert value to number
166
+ $cell->setValueExplicit($d, PHPExcel_Cell_DataType::TYPE_NUMERIC);
167
+ // Determine style. Either there is a time part or not. Look for ':'
168
+ if (strpos($value, ':') !== false) {
169
+ $formatCode = 'yyyy-mm-dd h:mm';
170
+ } else {
171
+ $formatCode = 'yyyy-mm-dd';
172
+ }
173
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
174
+ ->getNumberFormat()->setFormatCode($formatCode);
175
+ return true;
176
+ }
177
+
178
+ // Check for newline character "\n"
179
+ if (strpos($value, "\n") !== FALSE) {
180
+ $value = PHPExcel_Shared_String::SanitizeUTF8($value);
181
+ $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
182
+ // Set style
183
+ $cell->getWorksheet()->getStyle( $cell->getCoordinate() )
184
+ ->getAlignment()->setWrapText(TRUE);
185
+ return true;
186
+ }
187
+ }
188
+
189
+ // Not bound yet? Use parent...
190
+ return parent::bindValue($cell, $value);
191
+ }
192
+ }
libraries/PHPExcel/Cell/DataType.php ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Cell_DataType
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Cell
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Cell_DataType
37
+ {
38
+ /* Data types */
39
+ const TYPE_STRING2 = 'str';
40
+ const TYPE_STRING = 's';
41
+ const TYPE_FORMULA = 'f';
42
+ const TYPE_NUMERIC = 'n';
43
+ const TYPE_BOOL = 'b';
44
+ const TYPE_NULL = 'null';
45
+ const TYPE_INLINE = 'inlineStr';
46
+ const TYPE_ERROR = 'e';
47
+
48
+ /**
49
+ * List of error codes
50
+ *
51
+ * @var array
52
+ */
53
+ private static $_errorCodes = array(
54
+ '#NULL!' => 0,
55
+ '#DIV/0!' => 1,
56
+ '#VALUE!' => 2,
57
+ '#REF!' => 3,
58
+ '#NAME?' => 4,
59
+ '#NUM!' => 5,
60
+ '#N/A' => 6
61
+ );
62
+
63
+ /**
64
+ * Get list of error codes
65
+ *
66
+ * @return array
67
+ */
68
+ public static function getErrorCodes() {
69
+ return self::$_errorCodes;
70
+ }
71
+
72
+ /**
73
+ * DataType for value
74
+ *
75
+ * @deprecated Replaced by PHPExcel_Cell_IValueBinder infrastructure, will be removed in version 1.8.0
76
+ * @param mixed $pValue
77
+ * @return string
78
+ */
79
+ public static function dataTypeForValue($pValue = null) {
80
+ return PHPExcel_Cell_DefaultValueBinder::dataTypeForValue($pValue);
81
+ }
82
+
83
+ /**
84
+ * Check a string that it satisfies Excel requirements
85
+ *
86
+ * @param mixed Value to sanitize to an Excel string
87
+ * @return mixed Sanitized value
88
+ */
89
+ public static function checkString($pValue = null)
90
+ {
91
+ if ($pValue instanceof PHPExcel_RichText) {
92
+ // TODO: Sanitize Rich-Text string (max. character count is 32,767)
93
+ return $pValue;
94
+ }
95
+
96
+ // string must never be longer than 32,767 characters, truncate if necessary
97
+ $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 32767);
98
+
99
+ // we require that newline is represented as "\n" in core, not as "\r\n" or "\r"
100
+ $pValue = str_replace(array("\r\n", "\r"), "\n", $pValue);
101
+
102
+ return $pValue;
103
+ }
104
+
105
+ /**
106
+ * Check a value that it is a valid error code
107
+ *
108
+ * @param mixed Value to sanitize to an Excel error code
109
+ * @return string Sanitized value
110
+ */
111
+ public static function checkErrorCode($pValue = null)
112
+ {
113
+ $pValue = (string) $pValue;
114
+
115
+ if ( !array_key_exists($pValue, self::$_errorCodes) ) {
116
+ $pValue = '#NULL!';
117
+ }
118
+
119
+ return $pValue;
120
+ }
121
+
122
+ }
libraries/PHPExcel/Cell/DataValidation.php ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Cell_DataValidation
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Cell
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Cell_DataValidation
37
+ {
38
+ /* Data validation types */
39
+ const TYPE_NONE = 'none';
40
+ const TYPE_CUSTOM = 'custom';
41
+ const TYPE_DATE = 'date';
42
+ const TYPE_DECIMAL = 'decimal';
43
+ const TYPE_LIST = 'list';
44
+ const TYPE_TEXTLENGTH = 'textLength';
45
+ const TYPE_TIME = 'time';
46
+ const TYPE_WHOLE = 'whole';
47
+
48
+ /* Data validation error styles */
49
+ const STYLE_STOP = 'stop';
50
+ const STYLE_WARNING = 'warning';
51
+ const STYLE_INFORMATION = 'information';
52
+
53
+ /* Data validation operators */
54
+ const OPERATOR_BETWEEN = 'between';
55
+ const OPERATOR_EQUAL = 'equal';
56
+ const OPERATOR_GREATERTHAN = 'greaterThan';
57
+ const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
58
+ const OPERATOR_LESSTHAN = 'lessThan';
59
+ const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
60
+ const OPERATOR_NOTBETWEEN = 'notBetween';
61
+ const OPERATOR_NOTEQUAL = 'notEqual';
62
+
63
+ /**
64
+ * Formula 1
65
+ *
66
+ * @var string
67
+ */
68
+ private $_formula1;
69
+
70
+ /**
71
+ * Formula 2
72
+ *
73
+ * @var string
74
+ */
75
+ private $_formula2;
76
+
77
+ /**
78
+ * Type
79
+ *
80
+ * @var string
81
+ */
82
+ private $_type = PHPExcel_Cell_DataValidation::TYPE_NONE;
83
+
84
+ /**
85
+ * Error style
86
+ *
87
+ * @var string
88
+ */
89
+ private $_errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP;
90
+
91
+ /**
92
+ * Operator
93
+ *
94
+ * @var string
95
+ */
96
+ private $_operator;
97
+
98
+ /**
99
+ * Allow Blank
100
+ *
101
+ * @var boolean
102
+ */
103
+ private $_allowBlank;
104
+
105
+ /**
106
+ * Show DropDown
107
+ *
108
+ * @var boolean
109
+ */
110
+ private $_showDropDown;
111
+
112
+ /**
113
+ * Show InputMessage
114
+ *
115
+ * @var boolean
116
+ */
117
+ private $_showInputMessage;
118
+
119
+ /**
120
+ * Show ErrorMessage
121
+ *
122
+ * @var boolean
123
+ */
124
+ private $_showErrorMessage;
125
+
126
+ /**
127
+ * Error title
128
+ *
129
+ * @var string
130
+ */
131
+ private $_errorTitle;
132
+
133
+ /**
134
+ * Error
135
+ *
136
+ * @var string
137
+ */
138
+ private $_error;
139
+
140
+ /**
141
+ * Prompt title
142
+ *
143
+ * @var string
144
+ */
145
+ private $_promptTitle;
146
+
147
+ /**
148
+ * Prompt
149
+ *
150
+ * @var string
151
+ */
152
+ private $_prompt;
153
+
154
+ /**
155
+ * Create a new PHPExcel_Cell_DataValidation
156
+ */
157
+ public function __construct()
158
+ {
159
+ // Initialise member variables
160
+ $this->_formula1 = '';
161
+ $this->_formula2 = '';
162
+ $this->_type = PHPExcel_Cell_DataValidation::TYPE_NONE;
163
+ $this->_errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP;
164
+ $this->_operator = '';
165
+ $this->_allowBlank = FALSE;
166
+ $this->_showDropDown = FALSE;
167
+ $this->_showInputMessage = FALSE;
168
+ $this->_showErrorMessage = FALSE;
169
+ $this->_errorTitle = '';
170
+ $this->_error = '';
171
+ $this->_promptTitle = '';
172
+ $this->_prompt = '';
173
+ }
174
+
175
+ /**
176
+ * Get Formula 1
177
+ *
178
+ * @return string
179
+ */
180
+ public function getFormula1() {
181
+ return $this->_formula1;
182
+ }
183
+
184
+ /**
185
+ * Set Formula 1
186
+ *
187
+ * @param string $value
188
+ * @return PHPExcel_Cell_DataValidation
189
+ */
190
+ public function setFormula1($value = '') {
191
+ $this->_formula1 = $value;
192
+ return $this;
193
+ }
194
+
195
+ /**
196
+ * Get Formula 2
197
+ *
198
+ * @return string
199
+ */
200
+ public function getFormula2() {
201
+ return $this->_formula2;
202
+ }
203
+
204
+ /**
205
+ * Set Formula 2
206
+ *
207
+ * @param string $value
208
+ * @return PHPExcel_Cell_DataValidation
209
+ */
210
+ public function setFormula2($value = '') {
211
+ $this->_formula2 = $value;
212
+ return $this;
213
+ }
214
+
215
+ /**
216
+ * Get Type
217
+ *
218
+ * @return string
219
+ */
220
+ public function getType() {
221
+ return $this->_type;
222
+ }
223
+
224
+ /**
225
+ * Set Type
226
+ *
227
+ * @param string $value
228
+ * @return PHPExcel_Cell_DataValidation
229
+ */
230
+ public function setType($value = PHPExcel_Cell_DataValidation::TYPE_NONE) {
231
+ $this->_type = $value;
232
+ return $this;
233
+ }
234
+
235
+ /**
236
+ * Get Error style
237
+ *
238
+ * @return string
239
+ */
240
+ public function getErrorStyle() {
241
+ return $this->_errorStyle;
242
+ }
243
+
244
+ /**
245
+ * Set Error style
246
+ *
247
+ * @param string $value
248
+ * @return PHPExcel_Cell_DataValidation
249
+ */
250
+ public function setErrorStyle($value = PHPExcel_Cell_DataValidation::STYLE_STOP) {
251
+ $this->_errorStyle = $value;
252
+ return $this;
253
+ }
254
+
255
+ /**
256
+ * Get Operator
257
+ *
258
+ * @return string
259
+ */
260
+ public function getOperator() {
261
+ return $this->_operator;
262
+ }
263
+
264
+ /**
265
+ * Set Operator
266
+ *
267
+ * @param string $value
268
+ * @return PHPExcel_Cell_DataValidation
269
+ */
270
+ public function setOperator($value = '') {
271
+ $this->_operator = $value;
272
+ return $this;
273
+ }
274
+
275
+ /**
276
+ * Get Allow Blank
277
+ *
278
+ * @return boolean
279
+ */
280
+ public function getAllowBlank() {
281
+ return $this->_allowBlank;
282
+ }
283
+
284
+ /**
285
+ * Set Allow Blank
286
+ *
287
+ * @param boolean $value
288
+ * @return PHPExcel_Cell_DataValidation
289
+ */
290
+ public function setAllowBlank($value = false) {
291
+ $this->_allowBlank = $value;
292
+ return $this;
293
+ }
294
+
295
+ /**
296
+ * Get Show DropDown
297
+ *
298
+ * @return boolean
299
+ */
300
+ public function getShowDropDown() {
301
+ return $this->_showDropDown;
302
+ }
303
+
304
+ /**
305
+ * Set Show DropDown
306
+ *
307
+ * @param boolean $value
308
+ * @return PHPExcel_Cell_DataValidation
309
+ */
310
+ public function setShowDropDown($value = false) {
311
+ $this->_showDropDown = $value;
312
+ return $this;
313
+ }
314
+
315
+ /**
316
+ * Get Show InputMessage
317
+ *
318
+ * @return boolean
319
+ */
320
+ public function getShowInputMessage() {
321
+ return $this->_showInputMessage;
322
+ }
323
+
324
+ /**
325
+ * Set Show InputMessage
326
+ *
327
+ * @param boolean $value
328
+ * @return PHPExcel_Cell_DataValidation
329
+ */
330
+ public function setShowInputMessage($value = false) {
331
+ $this->_showInputMessage = $value;
332
+ return $this;
333
+ }
334
+
335
+ /**
336
+ * Get Show ErrorMessage
337
+ *
338
+ * @return boolean
339
+ */
340
+ public function getShowErrorMessage() {
341
+ return $this->_showErrorMessage;
342
+ }
343
+
344
+ /**
345
+ * Set Show ErrorMessage
346
+ *
347
+ * @param boolean $value
348
+ * @return PHPExcel_Cell_DataValidation
349
+ */
350
+ public function setShowErrorMessage($value = false) {
351
+ $this->_showErrorMessage = $value;
352
+ return $this;
353
+ }
354
+
355
+ /**
356
+ * Get Error title
357
+ *
358
+ * @return string
359
+ */
360
+ public function getErrorTitle() {
361
+ return $this->_errorTitle;
362
+ }
363
+
364
+ /**
365
+ * Set Error title
366
+ *
367
+ * @param string $value
368
+ * @return PHPExcel_Cell_DataValidation
369
+ */
370
+ public function setErrorTitle($value = '') {
371
+ $this->_errorTitle = $value;
372
+ return $this;
373
+ }
374
+
375
+ /**
376
+ * Get Error
377
+ *
378
+ * @return string
379
+ */
380
+ public function getError() {
381
+ return $this->_error;
382
+ }
383
+
384
+ /**
385
+ * Set Error
386
+ *
387
+ * @param string $value
388
+ * @return PHPExcel_Cell_DataValidation
389
+ */
390
+ public function setError($value = '') {
391
+ $this->_error = $value;
392
+ return $this;
393
+ }
394
+
395
+ /**
396
+ * Get Prompt title
397
+ *
398
+ * @return string
399
+ */
400
+ public function getPromptTitle() {
401
+ return $this->_promptTitle;
402
+ }
403
+
404
+ /**
405
+ * Set Prompt title
406
+ *
407
+ * @param string $value
408
+ * @return PHPExcel_Cell_DataValidation
409
+ */
410
+ public function setPromptTitle($value = '') {
411
+ $this->_promptTitle = $value;
412
+ return $this;
413
+ }
414
+
415
+ /**
416
+ * Get Prompt
417
+ *
418
+ * @return string
419
+ */
420
+ public function getPrompt() {
421
+ return $this->_prompt;
422
+ }
423
+
424
+ /**
425
+ * Set Prompt
426
+ *
427
+ * @param string $value
428
+ * @return PHPExcel_Cell_DataValidation
429
+ */
430
+ public function setPrompt($value = '') {
431
+ $this->_prompt = $value;
432
+ return $this;
433
+ }
434
+
435
+ /**
436
+ * Get hash code
437
+ *
438
+ * @return string Hash code
439
+ */
440
+ public function getHashCode() {
441
+ return md5(
442
+ $this->_formula1
443
+ . $this->_formula2
444
+ . $this->_type = PHPExcel_Cell_DataValidation::TYPE_NONE
445
+ . $this->_errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP
446
+ . $this->_operator
447
+ . ($this->_allowBlank ? 't' : 'f')
448
+ . ($this->_showDropDown ? 't' : 'f')
449
+ . ($this->_showInputMessage ? 't' : 'f')
450
+ . ($this->_showErrorMessage ? 't' : 'f')
451
+ . $this->_errorTitle
452
+ . $this->_error
453
+ . $this->_promptTitle
454
+ . $this->_prompt
455
+ . __CLASS__
456
+ );
457
+ }
458
+
459
+ /**
460
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
461
+ */
462
+ public function __clone() {
463
+ $vars = get_object_vars($this);
464
+ foreach ($vars as $key => $value) {
465
+ if (is_object($value)) {
466
+ $this->$key = clone $value;
467
+ } else {
468
+ $this->$key = $value;
469
+ }
470
+ }
471
+ }
472
+ }
libraries/PHPExcel/Cell/DefaultValueBinder.php ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+
39
+ /**
40
+ * PHPExcel_Cell_DefaultValueBinder
41
+ *
42
+ * @category PHPExcel
43
+ * @package PHPExcel_Cell
44
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
45
+ */
46
+ class PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
47
+ {
48
+ /**
49
+ * Bind value to a cell
50
+ *
51
+ * @param PHPExcel_Cell $cell Cell to bind value to
52
+ * @param mixed $value Value to bind in cell
53
+ * @return boolean
54
+ */
55
+ public function bindValue(PHPExcel_Cell $cell, $value = null)
56
+ {
57
+ // sanitize UTF-8 strings
58
+ if (is_string($value)) {
59
+ $value = PHPExcel_Shared_String::SanitizeUTF8($value);
60
+ } elseif (is_object($value)) {
61
+ // Handle any objects that might be injected
62
+ if ($value instanceof DateTime) {
63
+ $value = $value->format('Y-m-d H:i:s');
64
+ } elseif (!($value instanceof PHPExcel_RichText)) {
65
+ $value = (string) $value;
66
+ }
67
+ }
68
+
69
+ // Set value explicit
70
+ $cell->setValueExplicit( $value, self::dataTypeForValue($value) );
71
+
72
+ // Done!
73
+ return true;
74
+ }
75
+
76
+ /**
77
+ * DataType for value
78
+ *
79
+ * @param mixed $pValue
80
+ * @return string
81
+ */
82
+ public static function dataTypeForValue($pValue = null) {
83
+ // Match the value against a few data types
84
+ if ($pValue === null) {
85
+ return PHPExcel_Cell_DataType::TYPE_NULL;
86
+ } elseif ($pValue === '') {
87
+ return PHPExcel_Cell_DataType::TYPE_STRING;
88
+ } elseif ($pValue instanceof PHPExcel_RichText) {
89
+ return PHPExcel_Cell_DataType::TYPE_INLINE;
90
+ } elseif ($pValue{0} === '=' && strlen($pValue) > 1) {
91
+ return PHPExcel_Cell_DataType::TYPE_FORMULA;
92
+ } elseif (is_bool($pValue)) {
93
+ return PHPExcel_Cell_DataType::TYPE_BOOL;
94
+ } elseif (is_float($pValue) || is_int($pValue)) {
95
+ return PHPExcel_Cell_DataType::TYPE_NUMERIC;
96
+ } elseif (preg_match('/^[\+\-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
97
+ $tValue = ltrim($pValue, '+-');
98
+ if (is_string($pValue) && $tValue{0} === '0' && strlen($tValue) > 1 && $tValue{1} !== '.' ) {
99
+ return PHPExcel_Cell_DataType::TYPE_STRING;
100
+ } elseif((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) {
101
+ return PHPExcel_Cell_DataType::TYPE_STRING;
102
+ }
103
+ return PHPExcel_Cell_DataType::TYPE_NUMERIC;
104
+ } elseif (is_string($pValue) && array_key_exists($pValue, PHPExcel_Cell_DataType::getErrorCodes())) {
105
+ return PHPExcel_Cell_DataType::TYPE_ERROR;
106
+ }
107
+
108
+ return PHPExcel_Cell_DataType::TYPE_STRING;
109
+ }
110
+ }
libraries/PHPExcel/Cell/Hyperlink.php ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Cell_Hyperlink
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Cell
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Cell_Hyperlink
37
+ {
38
+ /**
39
+ * URL to link the cell to
40
+ *
41
+ * @var string
42
+ */
43
+ private $_url;
44
+
45
+ /**
46
+ * Tooltip to display on the hyperlink
47
+ *
48
+ * @var string
49
+ */
50
+ private $_tooltip;
51
+
52
+ /**
53
+ * Create a new PHPExcel_Cell_Hyperlink
54
+ *
55
+ * @param string $pUrl Url to link the cell to
56
+ * @param string $pTooltip Tooltip to display on the hyperlink
57
+ */
58
+ public function __construct($pUrl = '', $pTooltip = '')
59
+ {
60
+ // Initialise member variables
61
+ $this->_url = $pUrl;
62
+ $this->_tooltip = $pTooltip;
63
+ }
64
+
65
+ /**
66
+ * Get URL
67
+ *
68
+ * @return string
69
+ */
70
+ public function getUrl() {
71
+ return $this->_url;
72
+ }
73
+
74
+ /**
75
+ * Set URL
76
+ *
77
+ * @param string $value
78
+ * @return PHPExcel_Cell_Hyperlink
79
+ */
80
+ public function setUrl($value = '') {
81
+ $this->_url = $value;
82
+ return $this;
83
+ }
84
+
85
+ /**
86
+ * Get tooltip
87
+ *
88
+ * @return string
89
+ */
90
+ public function getTooltip() {
91
+ return $this->_tooltip;
92
+ }
93
+
94
+ /**
95
+ * Set tooltip
96
+ *
97
+ * @param string $value
98
+ * @return PHPExcel_Cell_Hyperlink
99
+ */
100
+ public function setTooltip($value = '') {
101
+ $this->_tooltip = $value;
102
+ return $this;
103
+ }
104
+
105
+ /**
106
+ * Is this hyperlink internal? (to another worksheet)
107
+ *
108
+ * @return boolean
109
+ */
110
+ public function isInternal() {
111
+ return strpos($this->_url, 'sheet://') !== false;
112
+ }
113
+
114
+ /**
115
+ * Get hash code
116
+ *
117
+ * @return string Hash code
118
+ */
119
+ public function getHashCode() {
120
+ return md5(
121
+ $this->_url
122
+ . $this->_tooltip
123
+ . __CLASS__
124
+ );
125
+ }
126
+ }
libraries/PHPExcel/Cell/IValueBinder.php ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Cell
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Cell_IValueBinder
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Cell
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ interface PHPExcel_Cell_IValueBinder
37
+ {
38
+ /**
39
+ * Bind value to a cell
40
+ *
41
+ * @param PHPExcel_Cell $cell Cell to bind value to
42
+ * @param mixed $value Value to bind in cell
43
+ * @return boolean
44
+ */
45
+ public function bindValue(PHPExcel_Cell $cell, $value = NULL);
46
+ }
libraries/PHPExcel/Comment.php ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Comment
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Comment implements PHPExcel_IComparable
37
+ {
38
+ /**
39
+ * Author
40
+ *
41
+ * @var string
42
+ */
43
+ private $_author;
44
+
45
+ /**
46
+ * Rich text comment
47
+ *
48
+ * @var PHPExcel_RichText
49
+ */
50
+ private $_text;
51
+
52
+ /**
53
+ * Comment width (CSS style, i.e. XXpx or YYpt)
54
+ *
55
+ * @var string
56
+ */
57
+ private $_width = '96pt';
58
+
59
+ /**
60
+ * Left margin (CSS style, i.e. XXpx or YYpt)
61
+ *
62
+ * @var string
63
+ */
64
+ private $_marginLeft = '59.25pt';
65
+
66
+ /**
67
+ * Top margin (CSS style, i.e. XXpx or YYpt)
68
+ *
69
+ * @var string
70
+ */
71
+ private $_marginTop = '1.5pt';
72
+
73
+ /**
74
+ * Visible
75
+ *
76
+ * @var boolean
77
+ */
78
+ private $_visible = false;
79
+
80
+ /**
81
+ * Comment height (CSS style, i.e. XXpx or YYpt)
82
+ *
83
+ * @var string
84
+ */
85
+ private $_height = '55.5pt';
86
+
87
+ /**
88
+ * Comment fill color
89
+ *
90
+ * @var PHPExcel_Style_Color
91
+ */
92
+ private $_fillColor;
93
+
94
+ /**
95
+ * Alignment
96
+ *
97
+ * @var string
98
+ */
99
+ private $_alignment;
100
+
101
+ /**
102
+ * Create a new PHPExcel_Comment
103
+ *
104
+ * @throws PHPExcel_Exception
105
+ */
106
+ public function __construct()
107
+ {
108
+ // Initialise variables
109
+ $this->_author = 'Author';
110
+ $this->_text = new PHPExcel_RichText();
111
+ $this->_fillColor = new PHPExcel_Style_Color('FFFFFFE1');
112
+ $this->_alignment = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
113
+ }
114
+
115
+ /**
116
+ * Get Author
117
+ *
118
+ * @return string
119
+ */
120
+ public function getAuthor() {
121
+ return $this->_author;
122
+ }
123
+
124
+ /**
125
+ * Set Author
126
+ *
127
+ * @param string $pValue
128
+ * @return PHPExcel_Comment
129
+ */
130
+ public function setAuthor($pValue = '') {
131
+ $this->_author = $pValue;
132
+ return $this;
133
+ }
134
+
135
+ /**
136
+ * Get Rich text comment
137
+ *
138
+ * @return PHPExcel_RichText
139
+ */
140
+ public function getText() {
141
+ return $this->_text;
142
+ }
143
+
144
+ /**
145
+ * Set Rich text comment
146
+ *
147
+ * @param PHPExcel_RichText $pValue
148
+ * @return PHPExcel_Comment
149
+ */
150
+ public function setText(PHPExcel_RichText $pValue) {
151
+ $this->_text = $pValue;
152
+ return $this;
153
+ }
154
+
155
+ /**
156
+ * Get comment width (CSS style, i.e. XXpx or YYpt)
157
+ *
158
+ * @return string
159
+ */
160
+ public function getWidth() {
161
+ return $this->_width;
162
+ }
163
+
164
+ /**
165
+ * Set comment width (CSS style, i.e. XXpx or YYpt)
166
+ *
167
+ * @param string $value
168
+ * @return PHPExcel_Comment
169
+ */
170
+ public function setWidth($value = '96pt') {
171
+ $this->_width = $value;
172
+ return $this;
173
+ }
174
+
175
+ /**
176
+ * Get comment height (CSS style, i.e. XXpx or YYpt)
177
+ *
178
+ * @return string
179
+ */
180
+ public function getHeight() {
181
+ return $this->_height;
182
+ }
183
+
184
+ /**
185
+ * Set comment height (CSS style, i.e. XXpx or YYpt)
186
+ *
187
+ * @param string $value
188
+ * @return PHPExcel_Comment
189
+ */
190
+ public function setHeight($value = '55.5pt') {
191
+ $this->_height = $value;
192
+ return $this;
193
+ }
194
+
195
+ /**
196
+ * Get left margin (CSS style, i.e. XXpx or YYpt)
197
+ *
198
+ * @return string
199
+ */
200
+ public function getMarginLeft() {
201
+ return $this->_marginLeft;
202
+ }
203
+
204
+ /**
205
+ * Set left margin (CSS style, i.e. XXpx or YYpt)
206
+ *
207
+ * @param string $value
208
+ * @return PHPExcel_Comment
209
+ */
210
+ public function setMarginLeft($value = '59.25pt') {
211
+ $this->_marginLeft = $value;
212
+ return $this;
213
+ }
214
+
215
+ /**
216
+ * Get top margin (CSS style, i.e. XXpx or YYpt)
217
+ *
218
+ * @return string
219
+ */
220
+ public function getMarginTop() {
221
+ return $this->_marginTop;
222
+ }
223
+
224
+ /**
225
+ * Set top margin (CSS style, i.e. XXpx or YYpt)
226
+ *
227
+ * @param string $value
228
+ * @return PHPExcel_Comment
229
+ */
230
+ public function setMarginTop($value = '1.5pt') {
231
+ $this->_marginTop = $value;
232
+ return $this;
233
+ }
234
+
235
+ /**
236
+ * Is the comment visible by default?
237
+ *
238
+ * @return boolean
239
+ */
240
+ public function getVisible() {
241
+ return $this->_visible;
242
+ }
243
+
244
+ /**
245
+ * Set comment default visibility
246
+ *
247
+ * @param boolean $value
248
+ * @return PHPExcel_Comment
249
+ */
250
+ public function setVisible($value = false) {
251
+ $this->_visible = $value;
252
+ return $this;
253
+ }
254
+
255
+ /**
256
+ * Get fill color
257
+ *
258
+ * @return PHPExcel_Style_Color
259
+ */
260
+ public function getFillColor() {
261
+ return $this->_fillColor;
262
+ }
263
+
264
+ /**
265
+ * Set Alignment
266
+ *
267
+ * @param string $pValue
268
+ * @return PHPExcel_Comment
269
+ */
270
+ public function setAlignment($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) {
271
+ $this->_alignment = $pValue;
272
+ return $this;
273
+ }
274
+
275
+ /**
276
+ * Get Alignment
277
+ *
278
+ * @return string
279
+ */
280
+ public function getAlignment() {
281
+ return $this->_alignment;
282
+ }
283
+
284
+ /**
285
+ * Get hash code
286
+ *
287
+ * @return string Hash code
288
+ */
289
+ public function getHashCode() {
290
+ return md5(
291
+ $this->_author
292
+ . $this->_text->getHashCode()
293
+ . $this->_width
294
+ . $this->_height
295
+ . $this->_marginLeft
296
+ . $this->_marginTop
297
+ . ($this->_visible ? 1 : 0)
298
+ . $this->_fillColor->getHashCode()
299
+ . $this->_alignment
300
+ . __CLASS__
301
+ );
302
+ }
303
+
304
+ /**
305
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
306
+ */
307
+ public function __clone() {
308
+ $vars = get_object_vars($this);
309
+ foreach ($vars as $key => $value) {
310
+ if (is_object($value)) {
311
+ $this->$key = clone $value;
312
+ } else {
313
+ $this->$key = $value;
314
+ }
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Convert to string
320
+ *
321
+ * @return string
322
+ */
323
+ public function __toString() {
324
+ return $this->_text->getPlainText();
325
+ }
326
+
327
+ }
libraries/PHPExcel/DocumentProperties.php ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_DocumentProperties
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_DocumentProperties
37
+ {
38
+ /** constants */
39
+ const PROPERTY_TYPE_BOOLEAN = 'b';
40
+ const PROPERTY_TYPE_INTEGER = 'i';
41
+ const PROPERTY_TYPE_FLOAT = 'f';
42
+ const PROPERTY_TYPE_DATE = 'd';
43
+ const PROPERTY_TYPE_STRING = 's';
44
+ const PROPERTY_TYPE_UNKNOWN = 'u';
45
+
46
+ /**
47
+ * Creator
48
+ *
49
+ * @var string
50
+ */
51
+ private $_creator = 'Unknown Creator';
52
+
53
+ /**
54
+ * LastModifiedBy
55
+ *
56
+ * @var string
57
+ */
58
+ private $_lastModifiedBy;
59
+
60
+ /**
61
+ * Created
62
+ *
63
+ * @var datetime
64
+ */
65
+ private $_created;
66
+
67
+ /**
68
+ * Modified
69
+ *
70
+ * @var datetime
71
+ */
72
+ private $_modified;
73
+
74
+ /**
75
+ * Title
76
+ *
77
+ * @var string
78
+ */
79
+ private $_title = 'Untitled Spreadsheet';
80
+
81
+ /**
82
+ * Description
83
+ *
84
+ * @var string
85
+ */
86
+ private $_description = '';
87
+
88
+ /**
89
+ * Subject
90
+ *
91
+ * @var string
92
+ */
93
+ private $_subject = '';
94
+
95
+ /**
96
+ * Keywords
97
+ *
98
+ * @var string
99
+ */
100
+ private $_keywords = '';
101
+
102
+ /**
103
+ * Category
104
+ *
105
+ * @var string
106
+ */
107
+ private $_category = '';
108
+
109
+ /**
110
+ * Manager
111
+ *
112
+ * @var string
113
+ */
114
+ private $_manager = '';
115
+
116
+ /**
117
+ * Company
118
+ *
119
+ * @var string
120
+ */
121
+ private $_company = 'Microsoft Corporation';
122
+
123
+ /**
124
+ * Custom Properties
125
+ *
126
+ * @var string
127
+ */
128
+ private $_customProperties = array();
129
+
130
+
131
+ /**
132
+ * Create a new PHPExcel_DocumentProperties
133
+ */
134
+ public function __construct()
135
+ {
136
+ // Initialise values
137
+ $this->_lastModifiedBy = $this->_creator;
138
+ $this->_created = time();
139
+ $this->_modified = time();
140
+ }
141
+
142
+ /**
143
+ * Get Creator
144
+ *
145
+ * @return string
146
+ */
147
+ public function getCreator() {
148
+ return $this->_creator;
149
+ }
150
+
151
+ /**
152
+ * Set Creator
153
+ *
154
+ * @param string $pValue
155
+ * @return PHPExcel_DocumentProperties
156
+ */
157
+ public function setCreator($pValue = '') {
158
+ $this->_creator = $pValue;
159
+ return $this;
160
+ }
161
+
162
+ /**
163
+ * Get Last Modified By
164
+ *
165
+ * @return string
166
+ */
167
+ public function getLastModifiedBy() {
168
+ return $this->_lastModifiedBy;
169
+ }
170
+
171
+ /**
172
+ * Set Last Modified By
173
+ *
174
+ * @param string $pValue
175
+ * @return PHPExcel_DocumentProperties
176
+ */
177
+ public function setLastModifiedBy($pValue = '') {
178
+ $this->_lastModifiedBy = $pValue;
179
+ return $this;
180
+ }
181
+
182
+ /**
183
+ * Get Created
184
+ *
185
+ * @return datetime
186
+ */
187
+ public function getCreated() {
188
+ return $this->_created;
189
+ }
190
+
191
+ /**
192
+ * Set Created
193
+ *
194
+ * @param datetime $pValue
195
+ * @return PHPExcel_DocumentProperties
196
+ */
197
+ public function setCreated($pValue = null) {
198
+ if ($pValue === NULL) {
199
+ $pValue = time();
200
+ } elseif (is_string($pValue)) {
201
+ if (is_numeric($pValue)) {
202
+ $pValue = intval($pValue);
203
+ } else {
204
+ $pValue = strtotime($pValue);
205
+ }
206
+ }
207
+
208
+ $this->_created = $pValue;
209
+ return $this;
210
+ }
211
+
212
+ /**
213
+ * Get Modified
214
+ *
215
+ * @return datetime
216
+ */
217
+ public function getModified() {
218
+ return $this->_modified;
219
+ }
220
+
221
+ /**
222
+ * Set Modified
223
+ *
224
+ * @param datetime $pValue
225
+ * @return PHPExcel_DocumentProperties
226
+ */
227
+ public function setModified($pValue = null) {
228
+ if ($pValue === NULL) {
229
+ $pValue = time();
230
+ } elseif (is_string($pValue)) {
231
+ if (is_numeric($pValue)) {
232
+ $pValue = intval($pValue);
233
+ } else {
234
+ $pValue = strtotime($pValue);
235
+ }
236
+ }
237
+
238
+ $this->_modified = $pValue;
239
+ return $this;
240
+ }
241
+
242
+ /**
243
+ * Get Title
244
+ *
245
+ * @return string
246
+ */
247
+ public function getTitle() {
248
+ return $this->_title;
249
+ }
250
+
251
+ /**
252
+ * Set Title
253
+ *
254
+ * @param string $pValue
255
+ * @return PHPExcel_DocumentProperties
256
+ */
257
+ public function setTitle($pValue = '') {
258
+ $this->_title = $pValue;
259
+ return $this;
260
+ }
261
+
262
+ /**
263
+ * Get Description
264
+ *
265
+ * @return string
266
+ */
267
+ public function getDescription() {
268
+ return $this->_description;
269
+ }
270
+
271
+ /**
272
+ * Set Description
273
+ *
274
+ * @param string $pValue
275
+ * @return PHPExcel_DocumentProperties
276
+ */
277
+ public function setDescription($pValue = '') {
278
+ $this->_description = $pValue;
279
+ return $this;
280
+ }
281
+
282
+ /**
283
+ * Get Subject
284
+ *
285
+ * @return string
286
+ */
287
+ public function getSubject() {
288
+ return $this->_subject;
289
+ }
290
+
291
+ /**
292
+ * Set Subject
293
+ *
294
+ * @param string $pValue
295
+ * @return PHPExcel_DocumentProperties
296
+ */
297
+ public function setSubject($pValue = '') {
298
+ $this->_subject = $pValue;
299
+ return $this;
300
+ }
301
+
302
+ /**
303
+ * Get Keywords
304
+ *
305
+ * @return string
306
+ */
307
+ public function getKeywords() {
308
+ return $this->_keywords;
309
+ }
310
+
311
+ /**
312
+ * Set Keywords
313
+ *
314
+ * @param string $pValue
315
+ * @return PHPExcel_DocumentProperties
316
+ */
317
+ public function setKeywords($pValue = '') {
318
+ $this->_keywords = $pValue;
319
+ return $this;
320
+ }
321
+
322
+ /**
323
+ * Get Category
324
+ *
325
+ * @return string
326
+ */
327
+ public function getCategory() {
328
+ return $this->_category;
329
+ }
330
+
331
+ /**
332
+ * Set Category
333
+ *
334
+ * @param string $pValue
335
+ * @return PHPExcel_DocumentProperties
336
+ */
337
+ public function setCategory($pValue = '') {
338
+ $this->_category = $pValue;
339
+ return $this;
340
+ }
341
+
342
+ /**
343
+ * Get Company
344
+ *
345
+ * @return string
346
+ */
347
+ public function getCompany() {
348
+ return $this->_company;
349
+ }
350
+
351
+ /**
352
+ * Set Company
353
+ *
354
+ * @param string $pValue
355
+ * @return PHPExcel_DocumentProperties
356
+ */
357
+ public function setCompany($pValue = '') {
358
+ $this->_company = $pValue;
359
+ return $this;
360
+ }
361
+
362
+ /**
363
+ * Get Manager
364
+ *
365
+ * @return string
366
+ */
367
+ public function getManager() {
368
+ return $this->_manager;
369
+ }
370
+
371
+ /**
372
+ * Set Manager
373
+ *
374
+ * @param string $pValue
375
+ * @return PHPExcel_DocumentProperties
376
+ */
377
+ public function setManager($pValue = '') {
378
+ $this->_manager = $pValue;
379
+ return $this;
380
+ }
381
+
382
+ /**
383
+ * Get a List of Custom Property Names
384
+ *
385
+ * @return array of string
386
+ */
387
+ public function getCustomProperties() {
388
+ return array_keys($this->_customProperties);
389
+ }
390
+
391
+ /**
392
+ * Check if a Custom Property is defined
393
+ *
394
+ * @param string $propertyName
395
+ * @return boolean
396
+ */
397
+ public function isCustomPropertySet($propertyName) {
398
+ return isset($this->_customProperties[$propertyName]);
399
+ }
400
+
401
+ /**
402
+ * Get a Custom Property Value
403
+ *
404
+ * @param string $propertyName
405
+ * @return string
406
+ */
407
+ public function getCustomPropertyValue($propertyName) {
408
+ if (isset($this->_customProperties[$propertyName])) {
409
+ return $this->_customProperties[$propertyName]['value'];
410
+ }
411
+
412
+ }
413
+
414
+ /**
415
+ * Get a Custom Property Type
416
+ *
417
+ * @param string $propertyName
418
+ * @return string
419
+ */
420
+ public function getCustomPropertyType($propertyName) {
421
+ if (isset($this->_customProperties[$propertyName])) {
422
+ return $this->_customProperties[$propertyName]['type'];
423
+ }
424
+
425
+ }
426
+
427
+ /**
428
+ * Set a Custom Property
429
+ *
430
+ * @param string $propertyName
431
+ * @param mixed $propertyValue
432
+ * @param string $propertyType
433
+ * 'i' : Integer
434
+ * 'f' : Floating Point
435
+ * 's' : String
436
+ * 'd' : Date/Time
437
+ * 'b' : Boolean
438
+ * @return PHPExcel_DocumentProperties
439
+ */
440
+ public function setCustomProperty($propertyName,$propertyValue='',$propertyType=NULL) {
441
+ if (($propertyType === NULL) || (!in_array($propertyType,array(self::PROPERTY_TYPE_INTEGER,
442
+ self::PROPERTY_TYPE_FLOAT,
443
+ self::PROPERTY_TYPE_STRING,
444
+ self::PROPERTY_TYPE_DATE,
445
+ self::PROPERTY_TYPE_BOOLEAN)))) {
446
+ if ($propertyValue === NULL) {
447
+ $propertyType = self::PROPERTY_TYPE_STRING;
448
+ } elseif (is_float($propertyValue)) {
449
+ $propertyType = self::PROPERTY_TYPE_FLOAT;
450
+ } elseif(is_int($propertyValue)) {
451
+ $propertyType = self::PROPERTY_TYPE_INTEGER;
452
+ } elseif (is_bool($propertyValue)) {
453
+ $propertyType = self::PROPERTY_TYPE_BOOLEAN;
454
+ } else {
455
+ $propertyType = self::PROPERTY_TYPE_STRING;
456
+ }
457
+ }
458
+
459
+ $this->_customProperties[$propertyName] = array('value' => $propertyValue, 'type' => $propertyType);
460
+ return $this;
461
+ }
462
+
463
+ /**
464
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
465
+ */
466
+ public function __clone() {
467
+ $vars = get_object_vars($this);
468
+ foreach ($vars as $key => $value) {
469
+ if (is_object($value)) {
470
+ $this->$key = clone $value;
471
+ } else {
472
+ $this->$key = $value;
473
+ }
474
+ }
475
+ }
476
+
477
+ public static function convertProperty($propertyValue,$propertyType) {
478
+ switch ($propertyType) {
479
+ case 'empty' : // Empty
480
+ return '';
481
+ break;
482
+ case 'null' : // Null
483
+ return NULL;
484
+ break;
485
+ case 'i1' : // 1-Byte Signed Integer
486
+ case 'i2' : // 2-Byte Signed Integer
487
+ case 'i4' : // 4-Byte Signed Integer
488
+ case 'i8' : // 8-Byte Signed Integer
489
+ case 'int' : // Integer
490
+ return (int) $propertyValue;
491
+ break;
492
+ case 'ui1' : // 1-Byte Unsigned Integer
493
+ case 'ui2' : // 2-Byte Unsigned Integer
494
+ case 'ui4' : // 4-Byte Unsigned Integer
495
+ case 'ui8' : // 8-Byte Unsigned Integer
496
+ case 'uint' : // Unsigned Integer
497
+ return abs((int) $propertyValue);
498
+ break;
499
+ case 'r4' : // 4-Byte Real Number
500
+ case 'r8' : // 8-Byte Real Number
501
+ case 'decimal' : // Decimal
502
+ return (float) $propertyValue;
503
+ break;
504
+ case 'lpstr' : // LPSTR
505
+ case 'lpwstr' : // LPWSTR
506
+ case 'bstr' : // Basic String
507
+ return $propertyValue;
508
+ break;
509
+ case 'date' : // Date and Time
510
+ case 'filetime' : // File Time
511
+ return strtotime($propertyValue);
512
+ break;
513
+ case 'bool' : // Boolean
514
+ return ($propertyValue == 'true') ? True : False;
515
+ break;
516
+ case 'cy' : // Currency
517
+ case 'error' : // Error Status Code
518
+ case 'vector' : // Vector
519
+ case 'array' : // Array
520
+ case 'blob' : // Binary Blob
521
+ case 'oblob' : // Binary Blob Object
522
+ case 'stream' : // Binary Stream
523
+ case 'ostream' : // Binary Stream Object
524
+ case 'storage' : // Binary Storage
525
+ case 'ostorage' : // Binary Storage Object
526
+ case 'vstream' : // Binary Versioned Stream
527
+ case 'clsid' : // Class ID
528
+ case 'cf' : // Clipboard Data
529
+ return $propertyValue;
530
+ break;
531
+ }
532
+ return $propertyValue;
533
+ }
534
+
535
+ public static function convertPropertyType($propertyType) {
536
+ switch ($propertyType) {
537
+ case 'i1' : // 1-Byte Signed Integer
538
+ case 'i2' : // 2-Byte Signed Integer
539
+ case 'i4' : // 4-Byte Signed Integer
540
+ case 'i8' : // 8-Byte Signed Integer
541
+ case 'int' : // Integer
542
+ case 'ui1' : // 1-Byte Unsigned Integer
543
+ case 'ui2' : // 2-Byte Unsigned Integer
544
+ case 'ui4' : // 4-Byte Unsigned Integer
545
+ case 'ui8' : // 8-Byte Unsigned Integer
546
+ case 'uint' : // Unsigned Integer
547
+ return self::PROPERTY_TYPE_INTEGER;
548
+ break;
549
+ case 'r4' : // 4-Byte Real Number
550
+ case 'r8' : // 8-Byte Real Number
551
+ case 'decimal' : // Decimal
552
+ return self::PROPERTY_TYPE_FLOAT;
553
+ break;
554
+ case 'empty' : // Empty
555
+ case 'null' : // Null
556
+ case 'lpstr' : // LPSTR
557
+ case 'lpwstr' : // LPWSTR
558
+ case 'bstr' : // Basic String
559
+ return self::PROPERTY_TYPE_STRING;
560
+ break;
561
+ case 'date' : // Date and Time
562
+ case 'filetime' : // File Time
563
+ return self::PROPERTY_TYPE_DATE;
564
+ break;
565
+ case 'bool' : // Boolean
566
+ return self::PROPERTY_TYPE_BOOLEAN;
567
+ break;
568
+ case 'cy' : // Currency
569
+ case 'error' : // Error Status Code
570
+ case 'vector' : // Vector
571
+ case 'array' : // Array
572
+ case 'blob' : // Binary Blob
573
+ case 'oblob' : // Binary Blob Object
574
+ case 'stream' : // Binary Stream
575
+ case 'ostream' : // Binary Stream Object
576
+ case 'storage' : // Binary Storage
577
+ case 'ostorage' : // Binary Storage Object
578
+ case 'vstream' : // Binary Versioned Stream
579
+ case 'clsid' : // Class ID
580
+ case 'cf' : // Clipboard Data
581
+ return self::PROPERTY_TYPE_UNKNOWN;
582
+ break;
583
+ }
584
+ return self::PROPERTY_TYPE_UNKNOWN;
585
+ }
586
+
587
+ }
libraries/PHPExcel/DocumentSecurity.php ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_DocumentSecurity
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_DocumentSecurity
37
+ {
38
+ /**
39
+ * LockRevision
40
+ *
41
+ * @var boolean
42
+ */
43
+ private $_lockRevision;
44
+
45
+ /**
46
+ * LockStructure
47
+ *
48
+ * @var boolean
49
+ */
50
+ private $_lockStructure;
51
+
52
+ /**
53
+ * LockWindows
54
+ *
55
+ * @var boolean
56
+ */
57
+ private $_lockWindows;
58
+
59
+ /**
60
+ * RevisionsPassword
61
+ *
62
+ * @var string
63
+ */
64
+ private $_revisionsPassword;
65
+
66
+ /**
67
+ * WorkbookPassword
68
+ *
69
+ * @var string
70
+ */
71
+ private $_workbookPassword;
72
+
73
+ /**
74
+ * Create a new PHPExcel_DocumentSecurity
75
+ */
76
+ public function __construct()
77
+ {
78
+ // Initialise values
79
+ $this->_lockRevision = false;
80
+ $this->_lockStructure = false;
81
+ $this->_lockWindows = false;
82
+ $this->_revisionsPassword = '';
83
+ $this->_workbookPassword = '';
84
+ }
85
+
86
+ /**
87
+ * Is some sort of dcument security enabled?
88
+ *
89
+ * @return boolean
90
+ */
91
+ function isSecurityEnabled() {
92
+ return $this->_lockRevision ||
93
+ $this->_lockStructure ||
94
+ $this->_lockWindows;
95
+ }
96
+
97
+ /**
98
+ * Get LockRevision
99
+ *
100
+ * @return boolean
101
+ */
102
+ function getLockRevision() {
103
+ return $this->_lockRevision;
104
+ }
105
+
106
+ /**
107
+ * Set LockRevision
108
+ *
109
+ * @param boolean $pValue
110
+ * @return PHPExcel_DocumentSecurity
111
+ */
112
+ function setLockRevision($pValue = false) {
113
+ $this->_lockRevision = $pValue;
114
+ return $this;
115
+ }
116
+
117
+ /**
118
+ * Get LockStructure
119
+ *
120
+ * @return boolean
121
+ */
122
+ function getLockStructure() {
123
+ return $this->_lockStructure;
124
+ }
125
+
126
+ /**
127
+ * Set LockStructure
128
+ *
129
+ * @param boolean $pValue
130
+ * @return PHPExcel_DocumentSecurity
131
+ */
132
+ function setLockStructure($pValue = false) {
133
+ $this->_lockStructure = $pValue;
134
+ return $this;
135
+ }
136
+
137
+ /**
138
+ * Get LockWindows
139
+ *
140
+ * @return boolean
141
+ */
142
+ function getLockWindows() {
143
+ return $this->_lockWindows;
144
+ }
145
+
146
+ /**
147
+ * Set LockWindows
148
+ *
149
+ * @param boolean $pValue
150
+ * @return PHPExcel_DocumentSecurity
151
+ */
152
+ function setLockWindows($pValue = false) {
153
+ $this->_lockWindows = $pValue;
154
+ return $this;
155
+ }
156
+
157
+ /**
158
+ * Get RevisionsPassword (hashed)
159
+ *
160
+ * @return string
161
+ */
162
+ function getRevisionsPassword() {
163
+ return $this->_revisionsPassword;
164
+ }
165
+
166
+ /**
167
+ * Set RevisionsPassword
168
+ *
169
+ * @param string $pValue
170
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
171
+ * @return PHPExcel_DocumentSecurity
172
+ */
173
+ function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) {
174
+ if (!$pAlreadyHashed) {
175
+ $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue);
176
+ }
177
+ $this->_revisionsPassword = $pValue;
178
+ return $this;
179
+ }
180
+
181
+ /**
182
+ * Get WorkbookPassword (hashed)
183
+ *
184
+ * @return string
185
+ */
186
+ function getWorkbookPassword() {
187
+ return $this->_workbookPassword;
188
+ }
189
+
190
+ /**
191
+ * Set WorkbookPassword
192
+ *
193
+ * @param string $pValue
194
+ * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true
195
+ * @return PHPExcel_DocumentSecurity
196
+ */
197
+ function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) {
198
+ if (!$pAlreadyHashed) {
199
+ $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue);
200
+ }
201
+ $this->_workbookPassword = $pValue;
202
+ return $this;
203
+ }
204
+
205
+ /**
206
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
207
+ */
208
+ public function __clone() {
209
+ $vars = get_object_vars($this);
210
+ foreach ($vars as $key => $value) {
211
+ if (is_object($value)) {
212
+ $this->$key = clone $value;
213
+ } else {
214
+ $this->$key = $value;
215
+ }
216
+ }
217
+ }
218
+ }
libraries/PHPExcel/Exception.php ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Exception
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_Exception extends Exception {
37
+ /**
38
+ * Error handler callback
39
+ *
40
+ * @param mixed $code
41
+ * @param mixed $string
42
+ * @param mixed $file
43
+ * @param mixed $line
44
+ * @param mixed $context
45
+ */
46
+ public static function errorHandlerCallback($code, $string, $file, $line, $context) {
47
+ $e = new self($string, $code);
48
+ $e->line = $line;
49
+ $e->file = $file;
50
+ throw $e;
51
+ }
52
+ }
libraries/PHPExcel/HashTable.php ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_HashTable
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_HashTable
37
+ {
38
+ /**
39
+ * HashTable elements
40
+ *
41
+ * @var array
42
+ */
43
+ public $_items = array();
44
+
45
+ /**
46
+ * HashTable key map
47
+ *
48
+ * @var array
49
+ */
50
+ public $_keyMap = array();
51
+
52
+ /**
53
+ * Create a new PHPExcel_HashTable
54
+ *
55
+ * @param PHPExcel_IComparable[] $pSource Optional source array to create HashTable from
56
+ * @throws PHPExcel_Exception
57
+ */
58
+ public function __construct($pSource = null)
59
+ {
60
+ if ($pSource !== NULL) {
61
+ // Create HashTable
62
+ $this->addFromSource($pSource);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Add HashTable items from source
68
+ *
69
+ * @param PHPExcel_IComparable[] $pSource Source array to create HashTable from
70
+ * @throws PHPExcel_Exception
71
+ */
72
+ public function addFromSource($pSource = null) {
73
+ // Check if an array was passed
74
+ if ($pSource == null) {
75
+ return;
76
+ } else if (!is_array($pSource)) {
77
+ throw new PHPExcel_Exception('Invalid array parameter passed.');
78
+ }
79
+
80
+ foreach ($pSource as $item) {
81
+ $this->add($item);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Add HashTable item
87
+ *
88
+ * @param PHPExcel_IComparable $pSource Item to add
89
+ * @throws PHPExcel_Exception
90
+ */
91
+ public function add(PHPExcel_IComparable $pSource = null) {
92
+ $hash = $pSource->getHashCode();
93
+ if (!isset($this->_items[$hash])) {
94
+ $this->_items[$hash] = $pSource;
95
+ $this->_keyMap[count($this->_items) - 1] = $hash;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Remove HashTable item
101
+ *
102
+ * @param PHPExcel_IComparable $pSource Item to remove
103
+ * @throws PHPExcel_Exception
104
+ */
105
+ public function remove(PHPExcel_IComparable $pSource = null) {
106
+ $hash = $pSource->getHashCode();
107
+ if (isset($this->_items[$hash])) {
108
+ unset($this->_items[$hash]);
109
+
110
+ $deleteKey = -1;
111
+ foreach ($this->_keyMap as $key => $value) {
112
+ if ($deleteKey >= 0) {
113
+ $this->_keyMap[$key - 1] = $value;
114
+ }
115
+
116
+ if ($value == $hash) {
117
+ $deleteKey = $key;
118
+ }
119
+ }
120
+ unset($this->_keyMap[count($this->_keyMap) - 1]);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Clear HashTable
126
+ *
127
+ */
128
+ public function clear() {
129
+ $this->_items = array();
130
+ $this->_keyMap = array();
131
+ }
132
+
133
+ /**
134
+ * Count
135
+ *
136
+ * @return int
137
+ */
138
+ public function count() {
139
+ return count($this->_items);
140
+ }
141
+
142
+ /**
143
+ * Get index for hash code
144
+ *
145
+ * @param string $pHashCode
146
+ * @return int Index
147
+ */
148
+ public function getIndexForHashCode($pHashCode = '') {
149
+ return array_search($pHashCode, $this->_keyMap);
150
+ }
151
+
152
+ /**
153
+ * Get by index
154
+ *
155
+ * @param int $pIndex
156
+ * @return PHPExcel_IComparable
157
+ *
158
+ */
159
+ public function getByIndex($pIndex = 0) {
160
+ if (isset($this->_keyMap[$pIndex])) {
161
+ return $this->getByHashCode( $this->_keyMap[$pIndex] );
162
+ }
163
+
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * Get by hashcode
169
+ *
170
+ * @param string $pHashCode
171
+ * @return PHPExcel_IComparable
172
+ *
173
+ */
174
+ public function getByHashCode($pHashCode = '') {
175
+ if (isset($this->_items[$pHashCode])) {
176
+ return $this->_items[$pHashCode];
177
+ }
178
+
179
+ return null;
180
+ }
181
+
182
+ /**
183
+ * HashTable to array
184
+ *
185
+ * @return PHPExcel_IComparable[]
186
+ */
187
+ public function toArray() {
188
+ return $this->_items;
189
+ }
190
+
191
+ /**
192
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
193
+ */
194
+ public function __clone() {
195
+ $vars = get_object_vars($this);
196
+ foreach ($vars as $key => $value) {
197
+ if (is_object($value)) {
198
+ $this->$key = clone $value;
199
+ }
200
+ }
201
+ }
202
+ }
libraries/PHPExcel/IComparable.php ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * This library is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * This library is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with this library; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ *
19
+ * @category PHPExcel
20
+ * @package PHPExcel
21
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
22
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
23
+ * @version ##VERSION##, ##DATE##
24
+ */
25
+
26
+
27
+ /**
28
+ * PHPExcel_IComparable
29
+ *
30
+ * @category PHPExcel
31
+ * @package PHPExcel
32
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
33
+ */
34
+ interface PHPExcel_IComparable
35
+ {
36
+ /**
37
+ * Get hash code
38
+ *
39
+ * @return string Hash code
40
+ */
41
+ public function getHashCode();
42
+
43
+ }
libraries/PHPExcel/IOFactory.php ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+ /**
39
+ * PHPExcel_IOFactory
40
+ *
41
+ * @category PHPExcel
42
+ * @package PHPExcel
43
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
44
+ */
45
+ class PHPExcel_IOFactory
46
+ {
47
+ /**
48
+ * Search locations
49
+ *
50
+ * @var array
51
+ * @access private
52
+ * @static
53
+ */
54
+ private static $_searchLocations = array(
55
+ array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'PHPExcel_Writer_{0}' ),
56
+ array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'PHPExcel_Reader_{0}' )
57
+ );
58
+
59
+ /**
60
+ * Autoresolve classes
61
+ *
62
+ * @var array
63
+ * @access private
64
+ * @static
65
+ */
66
+ private static $_autoResolveClasses = array(
67
+ 'Excel2007',
68
+ 'Excel5',
69
+ 'Excel2003XML',
70
+ 'OOCalc',
71
+ 'SYLK',
72
+ 'Gnumeric',
73
+ 'HTML',
74
+ 'CSV',
75
+ );
76
+
77
+ /**
78
+ * Private constructor for PHPExcel_IOFactory
79
+ */
80
+ private function __construct() { }
81
+
82
+ /**
83
+ * Get search locations
84
+ *
85
+ * @static
86
+ * @access public
87
+ * @return array
88
+ */
89
+ public static function getSearchLocations() {
90
+ return self::$_searchLocations;
91
+ } // function getSearchLocations()
92
+
93
+ /**
94
+ * Set search locations
95
+ *
96
+ * @static
97
+ * @access public
98
+ * @param array $value
99
+ * @throws PHPExcel_Reader_Exception
100
+ */
101
+ public static function setSearchLocations($value) {
102
+ if (is_array($value)) {
103
+ self::$_searchLocations = $value;
104
+ } else {
105
+ throw new PHPExcel_Reader_Exception('Invalid parameter passed.');
106
+ }
107
+ } // function setSearchLocations()
108
+
109
+ /**
110
+ * Add search location
111
+ *
112
+ * @static
113
+ * @access public
114
+ * @param string $type Example: IWriter
115
+ * @param string $location Example: PHPExcel/Writer/{0}.php
116
+ * @param string $classname Example: PHPExcel_Writer_{0}
117
+ */
118
+ public static function addSearchLocation($type = '', $location = '', $classname = '') {
119
+ self::$_searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname );
120
+ } // function addSearchLocation()
121
+
122
+ /**
123
+ * Create PHPExcel_Writer_IWriter
124
+ *
125
+ * @static
126
+ * @access public
127
+ * @param PHPExcel $phpExcel
128
+ * @param string $writerType Example: Excel2007
129
+ * @return PHPExcel_Writer_IWriter
130
+ * @throws PHPExcel_Reader_Exception
131
+ */
132
+ public static function createWriter(PHPExcel $phpExcel, $writerType = '') {
133
+ // Search type
134
+ $searchType = 'IWriter';
135
+
136
+ // Include class
137
+ foreach (self::$_searchLocations as $searchLocation) {
138
+ if ($searchLocation['type'] == $searchType) {
139
+ $className = str_replace('{0}', $writerType, $searchLocation['class']);
140
+
141
+ $instance = new $className($phpExcel);
142
+ if ($instance !== NULL) {
143
+ return $instance;
144
+ }
145
+ }
146
+ }
147
+
148
+ // Nothing found...
149
+ throw new PHPExcel_Reader_Exception("No $searchType found for type $writerType");
150
+ } // function createWriter()
151
+
152
+ /**
153
+ * Create PHPExcel_Reader_IReader
154
+ *
155
+ * @static
156
+ * @access public
157
+ * @param string $readerType Example: Excel2007
158
+ * @return PHPExcel_Reader_IReader
159
+ * @throws PHPExcel_Reader_Exception
160
+ */
161
+ public static function createReader($readerType = '') {
162
+ // Search type
163
+ $searchType = 'IReader';
164
+
165
+ // Include class
166
+ foreach (self::$_searchLocations as $searchLocation) {
167
+ if ($searchLocation['type'] == $searchType) {
168
+ $className = str_replace('{0}', $readerType, $searchLocation['class']);
169
+
170
+ $instance = new $className();
171
+ if ($instance !== NULL) {
172
+ return $instance;
173
+ }
174
+ }
175
+ }
176
+
177
+ // Nothing found...
178
+ throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType");
179
+ } // function createReader()
180
+
181
+ /**
182
+ * Loads PHPExcel from file using automatic PHPExcel_Reader_IReader resolution
183
+ *
184
+ * @static
185
+ * @access public
186
+ * @param string $pFilename The name of the spreadsheet file
187
+ * @return PHPExcel
188
+ * @throws PHPExcel_Reader_Exception
189
+ */
190
+ public static function load($pFilename) {
191
+ $reader = self::createReaderForFile($pFilename);
192
+ return $reader->load($pFilename);
193
+ } // function load()
194
+
195
+ /**
196
+ * Identify file type using automatic PHPExcel_Reader_IReader resolution
197
+ *
198
+ * @static
199
+ * @access public
200
+ * @param string $pFilename The name of the spreadsheet file to identify
201
+ * @return string
202
+ * @throws PHPExcel_Reader_Exception
203
+ */
204
+ public static function identify($pFilename) {
205
+ $reader = self::createReaderForFile($pFilename);
206
+ $className = get_class($reader);
207
+ $classType = explode('_',$className);
208
+ unset($reader);
209
+ return array_pop($classType);
210
+ } // function identify()
211
+
212
+ /**
213
+ * Create PHPExcel_Reader_IReader for file using automatic PHPExcel_Reader_IReader resolution
214
+ *
215
+ * @static
216
+ * @access public
217
+ * @param string $pFilename The name of the spreadsheet file
218
+ * @return PHPExcel_Reader_IReader
219
+ * @throws PHPExcel_Reader_Exception
220
+ */
221
+ public static function createReaderForFile($pFilename) {
222
+
223
+ // First, lucky guess by inspecting file extension
224
+ $pathinfo = pathinfo($pFilename);
225
+
226
+ $extensionType = NULL;
227
+ if (isset($pathinfo['extension'])) {
228
+ switch (strtolower($pathinfo['extension'])) {
229
+ case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet
230
+ case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded)
231
+ case 'xltx': // Excel (OfficeOpenXML) Template
232
+ case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded)
233
+ $extensionType = 'Excel2007';
234
+ break;
235
+ case 'xls': // Excel (BIFF) Spreadsheet
236
+ case 'xlt': // Excel (BIFF) Template
237
+ $extensionType = 'Excel5';
238
+ break;
239
+ case 'ods': // Open/Libre Offic Calc
240
+ case 'ots': // Open/Libre Offic Calc Template
241
+ $extensionType = 'OOCalc';
242
+ break;
243
+ case 'slk':
244
+ $extensionType = 'SYLK';
245
+ break;
246
+ case 'xml': // Excel 2003 SpreadSheetML
247
+ $extensionType = 'Excel2003XML';
248
+ break;
249
+ case 'gnumeric':
250
+ $extensionType = 'Gnumeric';
251
+ break;
252
+ case 'htm':
253
+ case 'html':
254
+ $extensionType = 'HTML';
255
+ break;
256
+ case 'csv':
257
+ // Do nothing
258
+ // We must not try to use CSV reader since it loads
259
+ // all files including Excel files etc.
260
+ break;
261
+ default:
262
+ break;
263
+ }
264
+
265
+ if ($extensionType !== NULL) {
266
+ $reader = self::createReader($extensionType);
267
+ // Let's see if we are lucky
268
+ if (isset($reader) && $reader->canRead($pFilename)) {
269
+ return $reader;
270
+ }
271
+ }
272
+ }
273
+
274
+ // If we reach here then "lucky guess" didn't give any result
275
+ // Try walking through all the options in self::$_autoResolveClasses
276
+ foreach (self::$_autoResolveClasses as $autoResolveClass) {
277
+ // Ignore our original guess, we know that won't work
278
+ if ($autoResolveClass !== $extensionType) {
279
+ $reader = self::createReader($autoResolveClass);
280
+ if ($reader->canRead($pFilename)) {
281
+ return $reader;
282
+ }
283
+ }
284
+ }
285
+
286
+ throw new PHPExcel_Reader_Exception('Unable to identify a reader for this file');
287
+ } // function createReaderForFile()
288
+ }
libraries/PHPExcel/NamedRange.php ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_NamedRange
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ class PHPExcel_NamedRange
37
+ {
38
+ /**
39
+ * Range name
40
+ *
41
+ * @var string
42
+ */
43
+ private $_name;
44
+
45
+ /**
46
+ * Worksheet on which the named range can be resolved
47
+ *
48
+ * @var PHPExcel_Worksheet
49
+ */
50
+ private $_worksheet;
51
+
52
+ /**
53
+ * Range of the referenced cells
54
+ *
55
+ * @var string
56
+ */
57
+ private $_range;
58
+
59
+ /**
60
+ * Is the named range local? (i.e. can only be used on $this->_worksheet)
61
+ *
62
+ * @var bool
63
+ */
64
+ private $_localOnly;
65
+
66
+ /**
67
+ * Scope
68
+ *
69
+ * @var PHPExcel_Worksheet
70
+ */
71
+ private $_scope;
72
+
73
+ /**
74
+ * Create a new NamedRange
75
+ *
76
+ * @param string $pName
77
+ * @param PHPExcel_Worksheet $pWorksheet
78
+ * @param string $pRange
79
+ * @param bool $pLocalOnly
80
+ * @param PHPExcel_Worksheet|null $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope.
81
+ * @throws PHPExcel_Exception
82
+ */
83
+ public function __construct($pName = null, PHPExcel_Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null)
84
+ {
85
+ // Validate data
86
+ if (($pName === NULL) || ($pWorksheet === NULL) || ($pRange === NULL)) {
87
+ throw new PHPExcel_Exception('Parameters can not be null.');
88
+ }
89
+
90
+ // Set local members
91
+ $this->_name = $pName;
92
+ $this->_worksheet = $pWorksheet;
93
+ $this->_range = $pRange;
94
+ $this->_localOnly = $pLocalOnly;
95
+ $this->_scope = ($pLocalOnly == true) ?
96
+ (($pScope == null) ? $pWorksheet : $pScope) : null;
97
+ }
98
+
99
+ /**
100
+ * Get name
101
+ *
102
+ * @return string
103
+ */
104
+ public function getName() {
105
+ return $this->_name;
106
+ }
107
+
108
+ /**
109
+ * Set name
110
+ *
111
+ * @param string $value
112
+ * @return PHPExcel_NamedRange
113
+ */
114
+ public function setName($value = null) {
115
+ if ($value !== NULL) {
116
+ // Old title
117
+ $oldTitle = $this->_name;
118
+
119
+ // Re-attach
120
+ if ($this->_worksheet !== NULL) {
121
+ $this->_worksheet->getParent()->removeNamedRange($this->_name,$this->_worksheet);
122
+ }
123
+ $this->_name = $value;
124
+
125
+ if ($this->_worksheet !== NULL) {
126
+ $this->_worksheet->getParent()->addNamedRange($this);
127
+ }
128
+
129
+ // New title
130
+ $newTitle = $this->_name;
131
+ PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->_worksheet->getParent(), $oldTitle, $newTitle);
132
+ }
133
+ return $this;
134
+ }
135
+
136
+ /**
137
+ * Get worksheet
138
+ *
139
+ * @return PHPExcel_Worksheet
140
+ */
141
+ public function getWorksheet() {
142
+ return $this->_worksheet;
143
+ }
144
+
145
+ /**
146
+ * Set worksheet
147
+ *
148
+ * @param PHPExcel_Worksheet $value
149
+ * @return PHPExcel_NamedRange
150
+ */
151
+ public function setWorksheet(PHPExcel_Worksheet $value = null) {
152
+ if ($value !== NULL) {
153
+ $this->_worksheet = $value;
154
+ }
155
+ return $this;
156
+ }
157
+
158
+ /**
159
+ * Get range
160
+ *
161
+ * @return string
162
+ */
163
+ public function getRange() {
164
+ return $this->_range;
165
+ }
166
+
167
+ /**
168
+ * Set range
169
+ *
170
+ * @param string $value
171
+ * @return PHPExcel_NamedRange
172
+ */
173
+ public function setRange($value = null) {
174
+ if ($value !== NULL) {
175
+ $this->_range = $value;
176
+ }
177
+ return $this;
178
+ }
179
+
180
+ /**
181
+ * Get localOnly
182
+ *
183
+ * @return bool
184
+ */
185
+ public function getLocalOnly() {
186
+ return $this->_localOnly;
187
+ }
188
+
189
+ /**
190
+ * Set localOnly
191
+ *
192
+ * @param bool $value
193
+ * @return PHPExcel_NamedRange
194
+ */
195
+ public function setLocalOnly($value = false) {
196
+ $this->_localOnly = $value;
197
+ $this->_scope = $value ? $this->_worksheet : null;
198
+ return $this;
199
+ }
200
+
201
+ /**
202
+ * Get scope
203
+ *
204
+ * @return PHPExcel_Worksheet|null
205
+ */
206
+ public function getScope() {
207
+ return $this->_scope;
208
+ }
209
+
210
+ /**
211
+ * Set scope
212
+ *
213
+ * @param PHPExcel_Worksheet|null $value
214
+ * @return PHPExcel_NamedRange
215
+ */
216
+ public function setScope(PHPExcel_Worksheet $value = null) {
217
+ $this->_scope = $value;
218
+ $this->_localOnly = ($value == null) ? false : true;
219
+ return $this;
220
+ }
221
+
222
+ /**
223
+ * Resolve a named range to a regular cell range
224
+ *
225
+ * @param string $pNamedRange Named range
226
+ * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope
227
+ * @return PHPExcel_NamedRange
228
+ */
229
+ public static function resolveRange($pNamedRange = '', PHPExcel_Worksheet $pSheet) {
230
+ return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet);
231
+ }
232
+
233
+ /**
234
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
235
+ */
236
+ public function __clone() {
237
+ $vars = get_object_vars($this);
238
+ foreach ($vars as $key => $value) {
239
+ if (is_object($value)) {
240
+ $this->$key = clone $value;
241
+ } else {
242
+ $this->$key = $value;
243
+ }
244
+ }
245
+ }
246
+ }
libraries/PHPExcel/Reader/Abstract.php ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Reader
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /**
30
+ * PHPExcel_Reader_Abstract
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel_Reader
34
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ */
36
+ abstract class PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
37
+ {
38
+ /**
39
+ * Read data only?
40
+ * Identifies whether the Reader should only read data values for cells, and ignore any formatting information;
41
+ * or whether it should read both data and formatting
42
+ *
43
+ * @var boolean
44
+ */
45
+ protected $_readDataOnly = FALSE;
46
+
47
+ /**
48
+ * Read charts that are defined in the workbook?
49
+ * Identifies whether the Reader should read the definitions for any charts that exist in the workbook;
50
+ *
51
+ * @var boolean
52
+ */
53
+ protected $_includeCharts = FALSE;
54
+
55
+ /**
56
+ * Restrict which sheets should be loaded?
57
+ * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded.
58
+ *
59
+ * @var array of string
60
+ */
61
+ protected $_loadSheetsOnly = NULL;
62
+
63
+ /**
64
+ * PHPExcel_Reader_IReadFilter instance
65
+ *
66
+ * @var PHPExcel_Reader_IReadFilter
67
+ */
68
+ protected $_readFilter = NULL;
69
+
70
+ protected $_fileHandle = NULL;
71
+
72
+
73
+ /**
74
+ * Read data only?
75
+ * If this is true, then the Reader will only read data values for cells, it will not read any formatting information.
76
+ * If false (the default) it will read data and formatting.
77
+ *
78
+ * @return boolean
79
+ */
80
+ public function getReadDataOnly() {
81
+ return $this->_readDataOnly;
82
+ }
83
+
84
+ /**
85
+ * Set read data only
86
+ * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information.
87
+ * Set to false (the default) to advise the Reader to read both data and formatting for cells.
88
+ *
89
+ * @param boolean $pValue
90
+ *
91
+ * @return PHPExcel_Reader_IReader
92
+ */
93
+ public function setReadDataOnly($pValue = FALSE) {
94
+ $this->_readDataOnly = $pValue;
95
+ return $this;
96
+ }
97
+
98
+ /**
99
+ * Read charts in workbook?
100
+ * If this is true, then the Reader will include any charts that exist in the workbook.
101
+ * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
102
+ * If false (the default) it will ignore any charts defined in the workbook file.
103
+ *
104
+ * @return boolean
105
+ */
106
+ public function getIncludeCharts() {
107
+ return $this->_includeCharts;
108
+ }
109
+
110
+ /**
111
+ * Set read charts in workbook
112
+ * Set to true, to advise the Reader to include any charts that exist in the workbook.
113
+ * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value.
114
+ * Set to false (the default) to discard charts.
115
+ *
116
+ * @param boolean $pValue
117
+ *
118
+ * @return PHPExcel_Reader_IReader
119
+ */
120
+ public function setIncludeCharts($pValue = FALSE) {
121
+ $this->_includeCharts = (boolean) $pValue;
122
+ return $this;
123
+ }
124
+
125
+ /**
126
+ * Get which sheets to load
127
+ * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null
128
+ * indicating that all worksheets in the workbook should be loaded.
129
+ *
130
+ * @return mixed
131
+ */
132
+ public function getLoadSheetsOnly()
133
+ {
134
+ return $this->_loadSheetsOnly;
135
+ }
136
+
137
+ /**
138
+ * Set which sheets to load
139
+ *
140
+ * @param mixed $value
141
+ * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name.
142
+ * If NULL, then it tells the Reader to read all worksheets in the workbook
143
+ *
144
+ * @return PHPExcel_Reader_IReader
145
+ */
146
+ public function setLoadSheetsOnly($value = NULL)
147
+ {
148
+ if ($value === NULL)
149
+ return $this->setLoadAllSheets();
150
+
151
+ $this->_loadSheetsOnly = is_array($value) ?
152
+ $value : array($value);
153
+ return $this;
154
+ }
155
+
156
+ /**
157
+ * Set all sheets to load
158
+ * Tells the Reader to load all worksheets from the workbook.
159
+ *
160
+ * @return PHPExcel_Reader_IReader
161
+ */
162
+ public function setLoadAllSheets()
163
+ {
164
+ $this->_loadSheetsOnly = NULL;
165
+ return $this;
166
+ }
167
+
168
+ /**
169
+ * Read filter
170
+ *
171
+ * @return PHPExcel_Reader_IReadFilter
172
+ */
173
+ public function getReadFilter() {
174
+ return $this->_readFilter;
175
+ }
176
+
177
+ /**
178
+ * Set read filter
179
+ *
180
+ * @param PHPExcel_Reader_IReadFilter $pValue
181
+ * @return PHPExcel_Reader_IReader
182
+ */
183
+ public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) {
184
+ $this->_readFilter = $pValue;
185
+ return $this;
186
+ }
187
+
188
+ /**
189
+ * Open file for reading
190
+ *
191
+ * @param string $pFilename
192
+ * @throws PHPExcel_Reader_Exception
193
+ * @return resource
194
+ */
195
+ protected function _openFile($pFilename)
196
+ {
197
+ // Check if file exists
198
+ if (!file_exists($pFilename) || !is_readable($pFilename)) {
199
+ throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
200
+ }
201
+
202
+ // Open file
203
+ $this->_fileHandle = fopen($pFilename, 'r');
204
+ if ($this->_fileHandle === FALSE) {
205
+ throw new PHPExcel_Reader_Exception("Could not open file " . $pFilename . " for reading.");
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Can the current PHPExcel_Reader_IReader read the file?
211
+ *
212
+ * @param string $pFilename
213
+ * @return boolean
214
+ * @throws PHPExcel_Reader_Exception
215
+ */
216
+ public function canRead($pFilename)
217
+ {
218
+ // Check if file exists
219
+ try {
220
+ $this->_openFile($pFilename);
221
+ } catch (Exception $e) {
222
+ return FALSE;
223
+ }
224
+
225
+ $readable = $this->_isValidFormat();
226
+ fclose ($this->_fileHandle);
227
+ return $readable;
228
+ }
229
+
230
+ /**
231
+ * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks
232
+ *
233
+ * @param string $xml
234
+ * @throws PHPExcel_Reader_Exception
235
+ */
236
+ public function securityScan($xml)
237
+ {
238
+ $pattern = '/\\0?' . implode('\\0?', str_split('<!DOCTYPE')) . '\\0?/';
239
+ if (preg_match($pattern, $xml)) {
240
+ throw new PHPExcel_Reader_Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks');
241
+ }
242
+ return $xml;
243
+ }
244
+
245
+ /**
246
+ * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks
247
+ *
248
+ * @param string $filestream
249
+ * @throws PHPExcel_Reader_Exception
250
+ */
251
+ public function securityScanFile($filestream)
252
+ {
253
+ return $this->securityScan(file_get_contents($filestream));
254
+ }
255
+ }
libraries/PHPExcel/Reader/CSV.php ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Reader
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+ /**
39
+ * PHPExcel_Reader_CSV
40
+ *
41
+ * @category PHPExcel
42
+ * @package PHPExcel_Reader
43
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
44
+ */
45
+ class PHPExcel_Reader_CSV extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
46
+ {
47
+ /**
48
+ * Input encoding
49
+ *
50
+ * @access private
51
+ * @var string
52
+ */
53
+ private $_inputEncoding = 'UTF-8';
54
+
55
+ /**
56
+ * Delimiter
57
+ *
58
+ * @access private
59
+ * @var string
60
+ */
61
+ private $_delimiter = ',';
62
+
63
+ /**
64
+ * Enclosure
65
+ *
66
+ * @access private
67
+ * @var string
68
+ */
69
+ private $_enclosure = '"';
70
+
71
+ /**
72
+ * Sheet index to read
73
+ *
74
+ * @access private
75
+ * @var int
76
+ */
77
+ private $_sheetIndex = 0;
78
+
79
+ /**
80
+ * Load rows contiguously
81
+ *
82
+ * @access private
83
+ * @var int
84
+ */
85
+ private $_contiguous = false;
86
+
87
+ /**
88
+ * Row counter for loading rows contiguously
89
+ *
90
+ * @var int
91
+ */
92
+ private $_contiguousRow = -1;
93
+
94
+
95
+ /**
96
+ * Create a new PHPExcel_Reader_CSV
97
+ */
98
+ public function __construct() {
99
+ $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
100
+ }
101
+
102
+ /**
103
+ * Validate that the current file is a CSV file
104
+ *
105
+ * @return boolean
106
+ */
107
+ protected function _isValidFormat()
108
+ {
109
+ return TRUE;
110
+ }
111
+
112
+ /**
113
+ * Set input encoding
114
+ *
115
+ * @param string $pValue Input encoding
116
+ */
117
+ public function setInputEncoding($pValue = 'UTF-8')
118
+ {
119
+ $this->_inputEncoding = $pValue;
120
+ return $this;
121
+ }
122
+
123
+ /**
124
+ * Get input encoding
125
+ *
126
+ * @return string
127
+ */
128
+ public function getInputEncoding()
129
+ {
130
+ return $this->_inputEncoding;
131
+ }
132
+
133
+ /**
134
+ * Move filepointer past any BOM marker
135
+ *
136
+ */
137
+ protected function _skipBOM()
138
+ {
139
+ rewind($this->_fileHandle);
140
+
141
+ switch ($this->_inputEncoding) {
142
+ case 'UTF-8':
143
+ fgets($this->_fileHandle, 4) == "\xEF\xBB\xBF" ?
144
+ fseek($this->_fileHandle, 3) : fseek($this->_fileHandle, 0);
145
+ break;
146
+ case 'UTF-16LE':
147
+ fgets($this->_fileHandle, 3) == "\xFF\xFE" ?
148
+ fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
149
+ break;
150
+ case 'UTF-16BE':
151
+ fgets($this->_fileHandle, 3) == "\xFE\xFF" ?
152
+ fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0);
153
+ break;
154
+ case 'UTF-32LE':
155
+ fgets($this->_fileHandle, 5) == "\xFF\xFE\x00\x00" ?
156
+ fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
157
+ break;
158
+ case 'UTF-32BE':
159
+ fgets($this->_fileHandle, 5) == "\x00\x00\xFE\xFF" ?
160
+ fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0);
161
+ break;
162
+ default:
163
+ break;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
169
+ *
170
+ * @param string $pFilename
171
+ * @throws PHPExcel_Reader_Exception
172
+ */
173
+ public function listWorksheetInfo($pFilename)
174
+ {
175
+ // Open file
176
+ $this->_openFile($pFilename);
177
+ if (!$this->_isValidFormat()) {
178
+ fclose ($this->_fileHandle);
179
+ throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
180
+ }
181
+ $fileHandle = $this->_fileHandle;
182
+
183
+ // Skip BOM, if any
184
+ $this->_skipBOM();
185
+
186
+ $escapeEnclosures = array( "\\" . $this->_enclosure, $this->_enclosure . $this->_enclosure );
187
+
188
+ $worksheetInfo = array();
189
+ $worksheetInfo[0]['worksheetName'] = 'Worksheet';
190
+ $worksheetInfo[0]['lastColumnLetter'] = 'A';
191
+ $worksheetInfo[0]['lastColumnIndex'] = 0;
192
+ $worksheetInfo[0]['totalRows'] = 0;
193
+ $worksheetInfo[0]['totalColumns'] = 0;
194
+
195
+ // Loop through each line of the file in turn
196
+ while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) {
197
+ $worksheetInfo[0]['totalRows']++;
198
+ $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1);
199
+ }
200
+
201
+ $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
202
+ $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
203
+
204
+ // Close file
205
+ fclose($fileHandle);
206
+
207
+ return $worksheetInfo;
208
+ }
209
+
210
+ /**
211
+ * Loads PHPExcel from file
212
+ *
213
+ * @param string $pFilename
214
+ * @return PHPExcel
215
+ * @throws PHPExcel_Reader_Exception
216
+ */
217
+ public function load($pFilename)
218
+ {
219
+ // Create new PHPExcel
220
+ $objPHPExcel = new PHPExcel();
221
+
222
+ // Load into this instance
223
+ return $this->loadIntoExisting($pFilename, $objPHPExcel);
224
+ }
225
+
226
+ /**
227
+ * Loads PHPExcel from file into PHPExcel instance
228
+ *
229
+ * @param string $pFilename
230
+ * @param PHPExcel $objPHPExcel
231
+ * @return PHPExcel
232
+ * @throws PHPExcel_Reader_Exception
233
+ */
234
+ public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
235
+ {
236
+ $lineEnding = ini_get('auto_detect_line_endings');
237
+ ini_set('auto_detect_line_endings', true);
238
+
239
+ // Open file
240
+ $this->_openFile($pFilename);
241
+ if (!$this->_isValidFormat()) {
242
+ fclose ($this->_fileHandle);
243
+ throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
244
+ }
245
+ $fileHandle = $this->_fileHandle;
246
+
247
+ // Skip BOM, if any
248
+ $this->_skipBOM();
249
+
250
+ // Create new PHPExcel object
251
+ while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) {
252
+ $objPHPExcel->createSheet();
253
+ }
254
+ $sheet = $objPHPExcel->setActiveSheetIndex($this->_sheetIndex);
255
+
256
+ $escapeEnclosures = array( "\\" . $this->_enclosure,
257
+ $this->_enclosure . $this->_enclosure
258
+ );
259
+
260
+ // Set our starting row based on whether we're in contiguous mode or not
261
+ $currentRow = 1;
262
+ if ($this->_contiguous) {
263
+ $currentRow = ($this->_contiguousRow == -1) ? $sheet->getHighestRow(): $this->_contiguousRow;
264
+ }
265
+
266
+ // Loop through each line of the file in turn
267
+ while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) {
268
+ $columnLetter = 'A';
269
+ foreach($rowData as $rowDatum) {
270
+ if ($rowDatum != '' && $this->_readFilter->readCell($columnLetter, $currentRow)) {
271
+ // Unescape enclosures
272
+ $rowDatum = str_replace($escapeEnclosures, $this->_enclosure, $rowDatum);
273
+
274
+ // Convert encoding if necessary
275
+ if ($this->_inputEncoding !== 'UTF-8') {
276
+ $rowDatum = PHPExcel_Shared_String::ConvertEncoding($rowDatum, 'UTF-8', $this->_inputEncoding);
277
+ }
278
+
279
+ // Set cell value
280
+ $sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum);
281
+ }
282
+ ++$columnLetter;
283
+ }
284
+ ++$currentRow;
285
+ }
286
+
287
+ // Close file
288
+ fclose($fileHandle);
289
+
290
+ if ($this->_contiguous) {
291
+ $this->_contiguousRow = $currentRow;
292
+ }
293
+
294
+ ini_set('auto_detect_line_endings', $lineEnding);
295
+
296
+ // Return
297
+ return $objPHPExcel;
298
+ }
299
+
300
+ /**
301
+ * Get delimiter
302
+ *
303
+ * @return string
304
+ */
305
+ public function getDelimiter() {
306
+ return $this->_delimiter;
307
+ }
308
+
309
+ /**
310
+ * Set delimiter
311
+ *
312
+ * @param string $pValue Delimiter, defaults to ,
313
+ * @return PHPExcel_Reader_CSV
314
+ */
315
+ public function setDelimiter($pValue = ',') {
316
+ $this->_delimiter = $pValue;
317
+ return $this;
318
+ }
319
+
320
+ /**
321
+ * Get enclosure
322
+ *
323
+ * @return string
324
+ */
325
+ public function getEnclosure() {
326
+ return $this->_enclosure;
327
+ }
328
+
329
+ /**
330
+ * Set enclosure
331
+ *
332
+ * @param string $pValue Enclosure, defaults to "
333
+ * @return PHPExcel_Reader_CSV
334
+ */
335
+ public function setEnclosure($pValue = '"') {
336
+ if ($pValue == '') {
337
+ $pValue = '"';
338
+ }
339
+ $this->_enclosure = $pValue;
340
+ return $this;
341
+ }
342
+
343
+ /**
344
+ * Get sheet index
345
+ *
346
+ * @return integer
347
+ */
348
+ public function getSheetIndex() {
349
+ return $this->_sheetIndex;
350
+ }
351
+
352
+ /**
353
+ * Set sheet index
354
+ *
355
+ * @param integer $pValue Sheet index
356
+ * @return PHPExcel_Reader_CSV
357
+ */
358
+ public function setSheetIndex($pValue = 0) {
359
+ $this->_sheetIndex = $pValue;
360
+ return $this;
361
+ }
362
+
363
+ /**
364
+ * Set Contiguous
365
+ *
366
+ * @param boolean $contiguous
367
+ */
368
+ public function setContiguous($contiguous = FALSE)
369
+ {
370
+ $this->_contiguous = (bool) $contiguous;
371
+ if (!$contiguous) {
372
+ $this->_contiguousRow = -1;
373
+ }
374
+
375
+ return $this;
376
+ }
377
+
378
+ /**
379
+ * Get Contiguous
380
+ *
381
+ * @return boolean
382
+ */
383
+ public function getContiguous() {
384
+ return $this->_contiguous;
385
+ }
386
+
387
+ }
libraries/PHPExcel/Reader/DefaultReadFilter.php ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Reader
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+ /**
39
+ * PHPExcel_Reader_DefaultReadFilter
40
+ *
41
+ * @category PHPExcel
42
+ * @package PHPExcel_Reader
43
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
44
+ */
45
+ class PHPExcel_Reader_DefaultReadFilter implements PHPExcel_Reader_IReadFilter
46
+ {
47
+ /**
48
+ * Should this cell be read?
49
+ *
50
+ * @param $column String column index
51
+ * @param $row Row index
52
+ * @param $worksheetName Optional worksheet name
53
+ * @return boolean
54
+ */
55
+ public function readCell($column, $row, $worksheetName = '') {
56
+ return true;
57
+ }
58
+ }
libraries/PHPExcel/Reader/Excel2003XML.php ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * PHPExcel
4
+ *
5
+ * Copyright (c) 2006 - 2014 PHPExcel
6
+ *
7
+ * This library is free software; you can redistribute it and/or
8
+ * modify it under the terms of the GNU Lesser General Public
9
+ * License as published by the Free Software Foundation; either
10
+ * version 2.1 of the License, or (at your option) any later version.
11
+ *
12
+ * This library is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15
+ * Lesser General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU Lesser General Public
18
+ * License along with this library; if not, write to the Free Software
19
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
+ *
21
+ * @category PHPExcel
22
+ * @package PHPExcel_Reader
23
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
25
+ * @version ##VERSION##, ##DATE##
26
+ */
27
+
28
+
29
+ /** PHPExcel root directory */
30
+ if (!defined('PHPEXCEL_ROOT')) {
31
+ /**
32
+ * @ignore
33
+ */
34
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
35
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
36
+ }
37
+
38
+ /**
39
+ * PHPExcel_Reader_Excel2003XML
40
+ *
41
+ * @category PHPExcel
42
+ * @package PHPExcel_Reader
43
+ * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
44
+ */
45
+ class PHPExcel_Reader_Excel2003XML extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
46
+ {
47
+ /**
48
+ * Formats
49
+ *
50
+ * @var array
51
+ */
52
+ protected $_styles = array();
53
+
54
+ /**
55
+ * Character set used in the file
56
+ *
57
+ * @var string
58
+ */
59
+ protected $_charSet = 'UTF-8';
60
+
61
+
62
+ /**
63
+ * Create a new PHPExcel_Reader_Excel2003XML
64
+ */
65
+ public function __construct() {
66
+ $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter();
67
+ }
68
+
69
+
70
+ /**
71
+ * Can the current PHPExcel_Reader_IReader read the file?
72
+ *
73
+ * @param string $pFilename
74
+ * @return boolean
75
+ * @throws PHPExcel_Reader_Exception
76
+ */
77
+ public function canRead($pFilename)
78
+ {
79
+
80
+ // Office xmlns:o="urn:schemas-microsoft-com:office:office"
81
+ // Excel xmlns:x="urn:schemas-microsoft-com:office:excel"
82
+ // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
83
+ // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet"
84
+ // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
85
+ // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"
86
+ // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset"
87
+ // Rowset xmlns:z="#RowsetSchema"
88
+ //
89
+
90
+ $signature = array(
91
+ '<?xml version="1.0"',
92
+ '<?mso-application progid="Excel.Sheet"?>'
93
+ );
94
+
95
+ // Open file
96
+ $this->_openFile($pFilename);
97
+ $fileHandle = $this->_fileHandle;
98
+
99
+ // Read sample data (first 2 KB will do)
100
+ $data = fread($fileHandle, 2048);
101
+ fclose($fileHandle);
102
+
103
+ $valid = true;
104
+ foreach($signature as $match) {
105
+ // every part of the signature must be present
106
+ if (strpos($data, $match) === false) {
107
+ $valid = false;
108
+ break;
109
+ }
110
+ }
111
+
112
+ // Retrieve charset encoding
113
+ if(preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/um',$data,$matches)) {
114
+ $this->_charSet = strtoupper($matches[1]);
115
+ }
116
+ // echo 'Character Set is ',$this->_charSet,'<br />';
117
+
118
+ return $valid;
119
+ }
120
+
121
+
122
+ /**
123
+ * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object
124
+ *
125
+ * @param string $pFilename
126
+ * @throws PHPExcel_Reader_Exception
127
+ */
128
+ public function listWorksheetNames($pFilename)
129
+ {
130
+ // Check if file exists
131
+ if (!file_exists($pFilename)) {
132
+ throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
133
+ }
134
+ if (!$this->canRead($pFilename)) {
135
+ throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
136
+ }
137
+
138
+ $worksheetNames = array();
139
+
140
+ $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions());
141
+ $namespaces = $xml->getNamespaces(true);
142
+
143
+ $xml_ss = $xml->children($namespaces['ss']);
144
+ foreach($xml_ss->Worksheet as $worksheet) {
145
+ $worksheet_ss = $works