diff --git a/.htaccess b/.htaccess index 6c370407..c7c01254 100755 --- a/.htaccess +++ b/.htaccess @@ -6,6 +6,13 @@ Order allow,deny + + RewriteEngine On + # Protect hidden directory from vulnerability scanner + RewriteRule (^|/)\.([^/]+)(/|$) - [L,F] + RewriteRule (^|/)([^/]+)~(/|$) - [L,F] + + # Don't show directory listings for URLs which map to a directory. Options -Indexes diff --git a/README.md b/README.md index 3beee10d..fe4782f5 100755 --- a/README.md +++ b/README.md @@ -11,8 +11,10 @@ SLiMS is licensed under GNU GPL version 3. Please read "GPL-3.0 License.txt" to learn more about GPL. ### System Requirements -- PHP version 7.4; +- PHP version 8.1; - MySQL version 5.7 and or MariaDB version 10.3; - PHP GD enabled - PHP gettext enabled -- PHP mbstring enabled \ No newline at end of file +- PHP mbstring enabled +- PDO MySQL enabled +- YAZ Optional diff --git a/admin/admin_template/akasia-dz/index_template.inc.php b/admin/admin_template/akasia-dz/index_template.inc.php index 3ee56264..4c2bb8dc 100644 --- a/admin/admin_template/akasia-dz/index_template.inc.php +++ b/admin/admin_template/akasia-dz/index_template.inc.php @@ -86,7 +86,15 @@
- Photo <?php echo $_SESSION['realname']?> + + Photo <?php echo $_SESSION['realname'] ?>

diff --git a/admin/admin_template/akasia/index_template.inc.php b/admin/admin_template/akasia/index_template.inc.php index 8d3b7d77..cda818f6 100755 --- a/admin/admin_template/akasia/index_template.inc.php +++ b/admin/admin_template/akasia/index_template.inc.php @@ -85,7 +85,15 @@

diff --git a/admin/admin_template/default/index_template.inc.php b/admin/admin_template/default/index_template.inc.php index 99691d67..c502c8e4 100755 --- a/admin/admin_template/default/index_template.inc.php +++ b/admin/admin_template/default/index_template.inc.php @@ -34,8 +34,8 @@ - + @@ -64,7 +64,15 @@
diff --git a/admin/admin_template/nightmode/index_template.inc.php b/admin/admin_template/nightmode/index_template.inc.php index ba45809b..ae4f6c39 100755 --- a/admin/admin_template/nightmode/index_template.inc.php +++ b/admin/admin_template/nightmode/index_template.inc.php @@ -60,7 +60,15 @@
diff --git a/admin/index.php b/admin/index.php index d9eff033..0e3390d0 100755 --- a/admin/index.php +++ b/admin/index.php @@ -70,9 +70,10 @@ # ADV LOG SYSTEM - STIIL EXPERIMENTAL $log = new AlLibrarian('1101', array("username" => $_SESSION['uname'], "uid" => $_SESSION['uid'], "realname" => $_SESSION['realname'], "module" => $current_module)); // get content of module default content with AJAX + $default_menu = $module->getFirstMenu($current_module)[1] ?? AWB . 'default/home.php'; $sysconf['page_footer'] .= "\n" .''; } else { include 'default/home.php'; diff --git a/admin/logout.php b/admin/logout.php index de2423ef..4a7dd0e8 100755 --- a/admin/logout.php +++ b/admin/logout.php @@ -30,6 +30,8 @@ // start the session require SB.'admin/default/session.inc.php'; +if(!isset($_SESSION['uid'])) header('location: ../index.php'); + // write log utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'system', $_SESSION['realname'].' Log Out from application from address '.$_SERVER['REMOTE_ADDR']); # ADV LOG SYSTEM - STIIL EXPERIMENTAL diff --git a/admin/modules/bibliography/File/MARC.php b/admin/modules/bibliography/File/MARC.php index 74351fa2..35862cf3 100644 --- a/admin/modules/bibliography/File/MARC.php +++ b/admin/modules/bibliography/File/MARC.php @@ -40,14 +40,14 @@ */ require_once 'PEAR/Exception.php'; -require_once 'File/MARCBASE.php'; -require_once 'File/MARC/Record.php'; -require_once 'File/MARC/Field.php'; -require_once 'File/MARC/Control_Field.php'; -require_once 'File/MARC/Data_Field.php'; -require_once 'File/MARC/Subfield.php'; -require_once 'File/MARC/Exception.php'; -require_once 'File/MARC/List.php'; +require_once MDLBS . 'bibliography/File/MARCBASE.php'; +require_once MDLBS . 'bibliography/File/MARC/Record.php'; +require_once MDLBS . 'bibliography/File/MARC/Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Control_Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Data_Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Subfield.php'; +require_once MDLBS . 'bibliography/File/MARC/Exception.php'; +require_once MDLBS . 'bibliography/File/MARC/List.php'; // {{{ class File_MARC /** @@ -169,7 +169,7 @@ function __construct($source, $type = self::SOURCE_FILE, $record_class = null) case self::SOURCE_STRING: $this->type = self::SOURCE_STRING; - $this->source = explode(File_MARC::END_OF_RECORD, $source); + $this->source = explode(File_MARC::END_OF_RECORD, $source??''); break; default: diff --git a/admin/modules/bibliography/File/MARC/Control_Field.php b/admin/modules/bibliography/File/MARC/Control_Field.php index 30c0f6bb..97b94304 100644 --- a/admin/modules/bibliography/File/MARC/Control_Field.php +++ b/admin/modules/bibliography/File/MARC/Control_Field.php @@ -123,7 +123,7 @@ function getData() * * @return bool Returns true if the field is empty, otherwise false */ - function isEmpty() + function isEmpty():bool { return ($this->data) ? false : true; } diff --git a/admin/modules/bibliography/File/MARC/Data_Field.php b/admin/modules/bibliography/File/MARC/Data_Field.php index 67ffbc43..b434093a 100644 --- a/admin/modules/bibliography/File/MARC/Data_Field.php +++ b/admin/modules/bibliography/File/MARC/Data_Field.php @@ -400,7 +400,7 @@ function getSubfields($code = null, $pcre = null) * * @return bool Returns true if the field is empty, otherwise false */ - function isEmpty() + function isEmpty():bool { // If $this->subfields is null, we must have deleted it if (!$this->subfields) { diff --git a/admin/modules/bibliography/File/MARC/Field.php b/admin/modules/bibliography/File/MARC/Field.php index 24e6a5bd..b49413b0 100644 --- a/admin/modules/bibliography/File/MARC/Field.php +++ b/admin/modules/bibliography/File/MARC/Field.php @@ -36,7 +36,7 @@ * @link http://pear.php.net/package/File_MARC */ -require_once 'File/MARC/List.php'; +require_once MDLBS . 'bibliography/File/MARC/List.php'; // {{{ class File_MARC_Field extends File_MARC_List /** @@ -133,7 +133,7 @@ function setTag($tag) * * @return bool Returns true if the field is empty, otherwise false */ - function isEmpty() + function isEmpty():bool { if ($this->getTag()) { return false; diff --git a/admin/modules/bibliography/File/MARC/Lint.php b/admin/modules/bibliography/File/MARC/Lint.php index bf330dc2..c0b3ad08 100644 --- a/admin/modules/bibliography/File/MARC/Lint.php +++ b/admin/modules/bibliography/File/MARC/Lint.php @@ -35,7 +35,7 @@ * @version CVS: $Id: Record.php 308146 2011-02-08 20:36:20Z dbs $ * @link http://pear.php.net/package/File_MARC */ -require_once 'File/MARC/Lint/CodeData.php'; +require_once MDLBS . 'bibliography/File/MARC/Lint/CodeData.php'; require_once 'Validate/ISPN.php'; // {{{ class File_MARC_Lint diff --git a/admin/modules/bibliography/File/MARC/List.php b/admin/modules/bibliography/File/MARC/List.php index c5b30f9d..1ebef648 100644 --- a/admin/modules/bibliography/File/MARC/List.php +++ b/admin/modules/bibliography/File/MARC/List.php @@ -93,7 +93,7 @@ class File_MARC_List extends SplDoublyLinkedList * * @return string returns the tag or code */ - function key() + function key():int { if ($this->current() instanceof File_MARC_Field) { return $this->current()->getTag(); diff --git a/admin/modules/bibliography/File/MARC/Subfield.php b/admin/modules/bibliography/File/MARC/Subfield.php index 227d4af5..ca639a9e 100644 --- a/admin/modules/bibliography/File/MARC/Subfield.php +++ b/admin/modules/bibliography/File/MARC/Subfield.php @@ -237,7 +237,7 @@ function setPosition($pos) function isEmpty() { // There is data - if (strlen($this->data)) { + if (strlen($this->data??'')) { return false; } diff --git a/admin/modules/bibliography/File/MARCBASE.php b/admin/modules/bibliography/File/MARCBASE.php index 68dfaa6e..0f9d1bee 100644 --- a/admin/modules/bibliography/File/MARCBASE.php +++ b/admin/modules/bibliography/File/MARCBASE.php @@ -38,7 +38,7 @@ * @example marc_yaz.php Pretty print a MARC record retrieved through the PECL yaz extension */ -require_once 'File/MARC/Record.php'; +require_once MDLBS . 'bibliography/File/MARC/Record.php'; // {{{ class File_MARCBASE /** diff --git a/admin/modules/bibliography/File/MARCXML.php b/admin/modules/bibliography/File/MARCXML.php index a9d1cc72..f05eeb88 100755 --- a/admin/modules/bibliography/File/MARCXML.php +++ b/admin/modules/bibliography/File/MARCXML.php @@ -39,15 +39,15 @@ */ require_once 'PEAR/Exception.php'; -require_once 'File/MARCBASE.php'; -require_once 'File/MARC.php'; -require_once 'File/MARC/Record.php'; -require_once 'File/MARC/Field.php'; -require_once 'File/MARC/Control_Field.php'; -require_once 'File/MARC/Data_Field.php'; -require_once 'File/MARC/Subfield.php'; -require_once 'File/MARC/Exception.php'; -require_once 'File/MARC/List.php'; +require_once MDLBS . 'bibliography/File/MARCBASE.php'; +require_once MDLBS . 'bibliography/File/MARC.php'; +require_once MDLBS . 'bibliography/File/MARC/Record.php'; +require_once MDLBS . 'bibliography/File/MARC/Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Control_Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Data_Field.php'; +require_once MDLBS . 'bibliography/File/MARC/Subfield.php'; +require_once MDLBS . 'bibliography/File/MARC/Exception.php'; +require_once MDLBS . 'bibliography/File/MARC/List.php'; // {{{ class File_MARCXML /** diff --git a/admin/modules/bibliography/biblio.inc.php b/admin/modules/bibliography/biblio.inc.php index 5213b94a..71c0b3fe 100644 --- a/admin/modules/bibliography/biblio.inc.php +++ b/admin/modules/bibliography/biblio.inc.php @@ -89,8 +89,9 @@ public function getRecords($criteria = '', $offset = 0, $total = 10000) die(); return false; } else { + $this->records = []; while ($record = $_q->fetch_assoc()) { - $this->records[] = $record; + $this->records[] = $record; } // free the memory $_q->free_result(); diff --git a/admin/modules/bibliography/import.php b/admin/modules/bibliography/import.php index 2a10915d..36d9cf90 100755 --- a/admin/modules/bibliography/import.php +++ b/admin/modules/bibliography/import.php @@ -164,7 +164,7 @@ // first field is header if (isset($_POST['header']) && $n < 1) { - $n++; + $n++; continue; } else { // send query $dbs->query($sql_str); @@ -246,7 +246,7 @@

- Official Website'); ?> + Official Website'); ?>
@@ -294,4 +294,4 @@ let fileName = $(this).val().replace(/\\/g, '/').replace(/.*\//, ''); $(this).parent('.custom-file').find('.custom-file-label').text(fileName); }); - \ No newline at end of file + diff --git a/admin/modules/bibliography/index.php b/admin/modules/bibliography/index.php index f9f80b8b..651b4f46 100755 --- a/admin/modules/bibliography/index.php +++ b/admin/modules/bibliography/index.php @@ -226,8 +226,15 @@ function getimagesizefromstring($string_data) $image_upload->setAllowableFormat($sysconf['allowed_images']); $image_upload->setMaxSize($sysconf['max_image_upload'] * 1024); $image_upload->setUploadDir(IMGBS . 'docs'); + + $img_title = $data['title'].'_'.date("YmdHis"); + if(strlen($data['title']) > 70){ + $img_title = substr($data['title'], 0, 70).'_'.date("YmdHis"); + } + + $new_filename = strtolower('cover_'. preg_replace("/[^a-zA-Z0-9]+/", "-", $img_title)); // upload the file and change all space characters to underscore - $img_upload_status = $image_upload->doUpload('image', preg_replace('@\s+@i', '_', $_FILES['image']['name'])); + $img_upload_status = $image_upload->doUpload('image', $new_filename); if ($img_upload_status == UPLOAD_SUCCESS) { $data['image'] = $dbs->escape_string($image_upload->new_filename); // write log @@ -235,8 +242,9 @@ function getimagesizefromstring($string_data) utility::jsToastr('Bibliography', __('Image Uploaded Successfully'), 'success'); } else { // write log + $data['image'] = NULL; utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'bibliography', 'ERROR : ' . $_SESSION['realname'] . ' FAILED TO upload image file ' . $image_upload->new_filename . ', with error (' . $image_upload->error . ')'); - utility::jsToastr('Bibliography', __('Image Uploaded Failed'), 'error'); + utility::jsToastr('Bibliography', __('Image Uploaded Failed').'
'.$image_upload->error, 'error'); } } else if (!empty($_POST['base64picstring'])) { list($filedata, $filedom) = explode('#image/type#', $_POST['base64picstring']); @@ -261,6 +269,13 @@ function getimagesizefromstring($string_data) if ($sysconf['log']['biblio']) { $_prevrawdata = api::biblio_load($dbs, $_POST['updateRecordID']); } + + // Remove previous popular biblio data from cache if opac use default template + if ($sysconf['template']['theme'] == 'default' && $_POST['opacHide'] != $_POST['opacHideOrigin']) { + require SB . 'api/v1/helpers/Cache.php'; + Cache::destroy('biblio_popular'); + } + /* UPDATE RECORD MODE */ // remove input date unset($data['input_date']); @@ -1063,6 +1078,7 @@ function affectedDetail($obj_db, $array_data) // biblio hide from opac $hide_options[] = array('0', __('Show')); $hide_options[] = array('1', __('Hide')); + $form->addHidden('opacHideOrigin', $rec_d['opac_hide']??0); $form->addRadio('opacHide', __('Hide in OPAC'), $hide_options, isset($rec_d['opac_hide']) && $rec_d['opac_hide'] ? '1' : '0'); // biblio promote to front page $promote_options[] = array('0', __('Don\'t Promote')); diff --git a/admin/modules/bibliography/item.php b/admin/modules/bibliography/item.php index 9a1475ad..2fa8327d 100755 --- a/admin/modules/bibliography/item.php +++ b/admin/modules/bibliography/item.php @@ -260,7 +260,7 @@ // default biblio title and biblio ID $b_title = $rec_d['title']; $b_id = $rec_d['biblio_id']; - if (trim($rec_d['call_number']) == '') { + if (trim($rec_d['call_number']??'') == '') { $biblio_q = $dbs->query('SELECT call_number FROM biblio WHERE biblio_id='.$rec_d['biblio_id']); $biblio_d = $biblio_q->fetch_assoc(); $rec_d['call_number'] = $biblio_d['call_number']; diff --git a/admin/modules/bibliography/item_import.php b/admin/modules/bibliography/item_import.php index 42a12552..f0531f3a 100755 --- a/admin/modules/bibliography/item_import.php +++ b/admin/modules/bibliography/item_import.php @@ -133,30 +133,39 @@ $item_status = utility::getID($dbs, 'mst_item_status', 'item_status_id', 'item_status_name', $field[9], $stat_id_cache); $item_status = $item_status?'\''.$item_status.'\'':'NULL'; $site = $field[10]?'\''.$field[10].'\'':'NULL'; - $source = $field[11]?'\''.$field[11].'\'':'NULL'; + $source = $field[11]?'\''.$field[11].'\'':'0'; $invoice = $field[12]?'\''.$field[12].'\'':'NULL'; $price = $field[13]?'\''.$field[13].'\'':'NULL'; $price_currency = $field[14]?'\''.$field[14].'\'':'NULL'; $invoice_date = $field[15]?'\''.$field[15].'\'':'NULL'; - $input_date = '\''.$field[16].'\''; - $last_update = '\''.$field[17].'\''; - - // sql insert string - $sql_str = "INSERT INTO item (item_code, call_number, coll_type_id, - inventory_code, received_date, supplier_id, - order_no, location_id, order_date, item_status_id, site, - source, invoice, price, price_currency, invoice_date, - input_date, last_update) - VALUES ($item_code, $call_number, $coll_type, - $inventory_code, $received_date, $supplier, - $order_no, $location, $order_date, $item_status, $site, - $source, $invoice, $price, $price_currency, $invoice_date, - $input_date, $last_update)"; + $input_date = $field[16]?'\''.$field[16].'\'':'\''.date('Y-m-d H:i:s').'\''; + $last_update = $field[17]?'\''.$field[17].'\'':'\''.date('Y-m-d H:i:s').'\''; + $title = $field[18]; // first field is header if (isset($_POST['header']) && $n < 1) { $n++; + continue; } else { + + // get biblio_id + $b_q = $dbs->query(sprintf("select biblio_id from biblio where title = '%s'", $title)); + if($b_q->num_rows < 1) continue; + $b_d = $b_q->fetch_row(); + $biblio_id = $b_d[0]; + + // sql insert string + $sql_str = "INSERT INTO item (biblio_id, item_code, call_number, coll_type_id, + inventory_code, received_date, supplier_id, + order_no, location_id, order_date, item_status_id, site, + source, invoice, price, price_currency, invoice_date, + input_date, last_update) + VALUES ($biblio_id, $item_code, $call_number, $coll_type, + $inventory_code, $received_date, $supplier, + $order_no, $location, $order_date, $item_status, $site, + $source, $invoice, $price, $price_currency, $invoice_date, + $input_date, $last_update)"; + // send query // die($sql_str); $dbs->query($sql_str); diff --git a/admin/modules/bibliography/marcexport.php b/admin/modules/bibliography/marcexport.php index 8fbf72cb..9eda19a6 100644 --- a/admin/modules/bibliography/marcexport.php +++ b/admin/modules/bibliography/marcexport.php @@ -45,7 +45,7 @@ // check if PEAR is installed ob_start(); -include 'File/MARC.php'; +include MDLBS . 'bibliography/File/MARC.php'; ob_end_clean(); if (!class_exists('File_MARC')) { die('
'.__('PEAR, File_MARC @@ -216,14 +216,14 @@ require LIB.'biblio_list_index.inc.php'; } // table spec - $table_spec = 'search_biblio'; + $table_spec = 'search_biblio AS `index`'; $datagrid->setSQLColumn('biblio_id', 'title AS \''.__('Title').'\'', 'author AS \''.__('Author').'\''); } else { require LIB.'biblio_list.inc.php'; // table spec - $table_spec = 'search_biblio'; + $table_spec = 'search_biblio AS `index`'; $datagrid->setSQLColumn('biblio_id', 'title AS \''.__('Title').'\'', 'author AS \''.__('Author').'\''); diff --git a/admin/modules/bibliography/pop_attach.php b/admin/modules/bibliography/pop_attach.php index 8cb9a2fb..487b6913 100755 --- a/admin/modules/bibliography/pop_attach.php +++ b/admin/modules/bibliography/pop_attach.php @@ -88,6 +88,8 @@ $fdata['file_url'] = $dbs->escape_string($url); $fdata['file_dir'] = $dbs->escape_string($file_dir); $fdata['file_desc'] = $dbs->escape_string(trim(strip_tags($_POST['fileDesc']))); + if(isset($_POST['fileKey']) && trim($_POST['fileKey']) !== '') + $fdata['file_key'] = $dbs->escape_string(trim(strip_tags($_POST['fileKey']))); $fdata['mime_type'] = $sysconf['mimetype'][$file_ext]; $fdata['input_date'] = date('Y-m-d H:i:s'); $fdata['last_update'] = $fdata['input_date']; @@ -110,6 +112,8 @@ $fdata['file_url'] = $dbs->escape_string($fdata['file_name']); $fdata['file_dir'] = 'literal{NULL}'; $fdata['file_desc'] = $dbs->escape_string(trim(strip_tags($_POST['fileDesc']))); + if(isset($_POST['fileKey']) && trim($_POST['fileKey']) !== '') + $fdata['file_key'] = $dbs->escape_string(trim(strip_tags($_POST['fileKey']))); $fdata['mime_type'] = 'text/uri-list'; $fdata['input_date'] = date('Y-m-d H:i:s'); $fdata['last_update'] = $fdata['input_date']; @@ -144,7 +148,10 @@ // file biblio access update $update1 = $sql_op->update('biblio_attachment', array('access_type' => $data['access_type'], 'access_limit' => $data['access_limit'], 'placement' => $data['placement']), 'biblio_id='.$updateBiblioID.' AND file_id='.$fileID); // file description update - $update2 = $sql_op->update('files', array('file_title' => $title, 'file_url' => $url, 'file_desc' => $dbs->escape_string(trim($_POST['fileDesc']))), 'file_id='.$fileID); + $file_desc_update = array('file_title' => $title, 'file_url' => $url, 'file_desc' => $dbs->escape_string(trim($_POST['fileDesc']))); + if(isset($_POST['fileKey'])) + $file_desc_update['file_key'] = $dbs->escape_string(trim(strip_tags($_POST['fileKey']))); + $update2 = $sql_op->update('files', $file_desc_update, 'file_id='.$fileID); if ($update1) { utility::jsToastr('File Attachment', __('File Attachment data updated!'), 'success'); echo ''; + exit; +} + +?> + + +setSQLColumn('c.comment_id', 'b.title', 'c.comment AS `' . __('Comment') . '`', 'm.member_name AS `' . __('Comment By') . '`', 'c.input_date AS `' . __('Comment At') . '`'); +$datagrid->setSQLorder('c.input_date DESC'); +$datagrid->invisible_fields = [0]; + +// is there any search +if (isset($_GET['keywords']) AND $_GET['keywords']) { + $keywords = utility::filterData('keywords', 'get', true, true, true); + $criteria_str = "c.comment LIKE '%{$keywords}%' OR m.member_name LIKE '%{$keywords}%'"; + $datagrid->setSQLCriteria($criteria_str); +} + +function addTitle($dbs, $data) +{ + return '' . __('Title') . ' :
' . $data[1] . '

'.$data[2].'
'; +} + +$datagrid->modifyColumnContent(2, 'callback{addTitle}'); + +// set table and table header attributes +$datagrid->table_attr = 'id="dataList" class="s-table table"'; +$datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"'; +// edit and checkbox property +$datagrid->edit_property = false; +$datagrid->chbox_property = array('itemID', __('Delete')); +// set delete proccess URL +$datagrid->chbox_form_URL = $_SERVER['PHP_SELF']; +$datagrid->column_width = array(0 => '5%', 1 => '75%'); +// put the result into variables +$datagrid_result = $datagrid->createDataGrid($dbs, $table, 20, $can_read); + +if (isset($_GET['keywords']) AND $_GET['keywords']) { + $msg = str_replace('{result->num_rows}', $datagrid->num_rows, __('Found {result->num_rows} from your keywords')); + echo '
' . $msg . ' : "' . htmlspecialchars($_GET['keywords']) . '"
' . __('Query took') . ' ' . $datagrid->query_time . ' ' . __('second(s) to complete') . '
'; +} +echo $datagrid_result; \ No newline at end of file diff --git a/admin/modules/master_file/submenu.php b/admin/modules/master_file/submenu.php index 87c2a976..9889ec22 100755 --- a/admin/modules/master_file/submenu.php +++ b/admin/modules/master_file/submenu.php @@ -41,6 +41,7 @@ $menu[] = array(__('Label'), MWB.'master_file/label.php', __('Special Labels for Titles to Show Up On Homepage')); $menu[] = array(__('Frequency'), MWB.'master_file/frequency.php', __('Frequency')); $menu[] = array('Header', __('TOOLS')); +$menu[] = array(__('Comment Management'), MWB.'master_file/detail_comment.php', __('List of members comment about biblio')); $menu[] = array(__('Cataloging Servers'), MWB.'master_file/p2pservers.php', __('List of available Copy Cataloging Servers')); $menu[] = array(__('Item Code Pattern'), MWB.'master_file/item_code_pattern.php', __('Manage item code pattern')); $menu[] = array(__('Orphaned Author'), MWB.'master_file/author.php?type=orphaned', __('Orphaned Authors')); diff --git a/admin/modules/membership/index.php b/admin/modules/membership/index.php index 3b18f52f..993e13ec 100755 --- a/admin/modules/membership/index.php +++ b/admin/modules/membership/index.php @@ -76,7 +76,7 @@ function getimagesizefromstring($string_data) $query_image = $dbs->query("SELECT member_id FROM member WHERE member_id='{$member_id}' AND member_image='{$image_name}'"); if (!empty($query_image->num_rows)) { - $_delete = $dbs->query(sprintf('UPDATE member SET member_image=NULL WHERE member_id=%d', $member_id)); + $_delete = $dbs->query(sprintf("UPDATE member SET member_image=NULL WHERE member_id='%s", $member_id)); if ($_delete) { $postImage = stripslashes($_POST['img']); $postImage = str_replace('/', '', $postImage); @@ -232,7 +232,7 @@ function getimagesizefromstring($string_data) // update custom data if (isset($custom_data)) { // check if custom data for this record exists - $_sql_check_custom_q = sprintf('SELECT member_id FROM member_custom WHERE member_id=%d', $updateRecordID); + $_sql_check_custom_q = sprintf("SELECT member_id FROM member_custom WHERE member_id='%s'", $updateRecordID); $check_custom_q = $dbs->query($_sql_check_custom_q); if ($check_custom_q->num_rows) { @$sql_op->update('member_custom', $custom_data, 'member_id=\''.$updateRecordID.'\''); @@ -431,7 +431,7 @@ function getimagesizefromstring($string_data) $form->submit_button_attr = 'name="saveData" value="'.__('Update').'" class="s-btn btn btn-primary"'; // custom field data query - $_sql_rec_cust_q = sprintf('SELECT * FROM member_custom WHERE member_id=%d', $itemID); + $_sql_rec_cust_q = sprintf("SELECT * FROM member_custom WHERE member_id='%s'", $itemID); $rec_cust_q = $dbs->query($_sql_rec_cust_q); $rec_cust_d = $rec_cust_q->fetch_assoc(); diff --git a/admin/modules/membership/member_base_lib.inc.php b/admin/modules/membership/member_base_lib.inc.php index baff807b..0e00fecb 100755 --- a/admin/modules/membership/member_base_lib.inc.php +++ b/admin/modules/membership/member_base_lib.inc.php @@ -1,233 +1,233 @@ -obj_db = $obj_db; - // get member data from database - $_member_q = $this->obj_db->query(sprintf("SELECT m.*,mt.* FROM member AS m - LEFT JOIN mst_member_type AS mt ON m.member_type_id=mt.member_type_id - WHERE member_id='%s'", $str_member_id)); - - if ($_member_q->num_rows > 0) { - // set the is_member property flag to TRUE - $this->is_member = true; - $_member_d = $_member_q->fetch_assoc(); - // assign database value to class properties - $this->member_id = $_member_d['member_id']; - $this->member_name = $_member_d['member_name']; - $this->member_type_id = $_member_d['member_type_id']; - $this->member_type_name = $_member_d['member_type_name']; - $this->register_date = $_member_d['register_date']; - $this->expire_date = $_member_d['expire_date']; - $this->member_email = $_member_d['member_email']; - $this->inst_name = $_member_d['inst_name']; - $this->member_image = $_member_d['member_image']; - $this->member_notes = $_member_d['member_notes']; - $this->is_pending = (bool)$_member_d['is_pending']; - $this->member_type_prop = array( - 'loan_limit' => $_member_d['loan_limit'], - 'loan_periode' => $_member_d['loan_periode'], - 'enable_reserve' => $_member_d['enable_reserve'], - 'reserve_limit' => $_member_d['reserve_limit'], - 'member_periode' => $_member_d['member_periode'], - 'reborrow_limit' => $_member_d['reborrow_limit'], - 'fine_each_day' => $_member_d['fine_each_day'], - 'grace_periode' => $_member_d['grace_periode'] - ); - - // is membership expired ? - // compare it with current date - $_current_date = date('Y-m-d'); - $_expired_date = simbio_date::compareDates($_current_date, $_member_d['expire_date']); - if ($_expired_date <= $_member_d['expire_date']) { - $this->is_expire = false; - } - } - } - - - # checking wether member is valid or not - # return : boolean - public function valid() - { - return $this->is_member; - } - - - # checking wether membership is already expired - # return : boolean - public function isExpired() - { - return $this->is_expire; - } - - - # checking wether membership is pending - # return : boolean - public function isPending() - { - return $this->is_pending; - } - - - # get all member properties - # retuen : array - public function getMemberTypeProp() - { - // return all member information as an array - return $this->member_type_prop; - } - - - # get info about item being lent by member - # return : array - protected function getItemLoan($int_loan_rules = 0) - { - $_arr_on_loan = array(); - // count how many items is in loan for this member - if ($int_loan_rules) { - $_sql_str = "SELECT item_code FROM loan AS l - WHERE member_id='".$this->member_id."' AND is_lent=1 AND is_return=0 AND loan_rules_id=$int_loan_rules"; - } else { - $_sql_str = "SELECT item_code FROM loan AS l - WHERE member_id='".$this->member_id."' AND is_lent=1 AND is_return=0"; - } - $_count_q = $this->obj_db->query($_sql_str); - while ($_count_d = $_count_q->fetch_row()) { - $_arr_on_loan[] = $_count_d[0]; - } - - return $_arr_on_loan; - } - - - # get an array of member's overdue data - public static function getOverduedLoan($obj_db, $str_member_id) - { // - - $_overdues = array(); - $_ovd_title_q = $obj_db->query(sprintf('SELECT l.loan_id, l.item_code, i.price, i.price_currency, - b.title, l.loan_date, - l.due_date, (TO_DAYS(DATE(NOW()))-TO_DAYS(due_date)) AS \'Overdue Days\' - FROM loan AS l - LEFT JOIN item AS i ON l.item_code=i.item_code - LEFT JOIN biblio AS b ON i.biblio_id=b.biblio_id - WHERE (l.is_lent=1 AND l.is_return=0 AND TO_DAYS(due_date) < TO_DAYS(\''.date('Y-m-d').'\')) AND l.member_id=\'%s\'', $str_member_id)); - while ($_ovd_title_d = $_ovd_title_q->fetch_assoc()) { - $_overdues[] = $_ovd_title_d; - } - - return $_overdues; - } - - - # send overdue notice e-mail - public function sendOverdueNotice() - { - global $sysconf; - $mail = new PHPMailer\PHPMailer\PHPMailer(true); - try { - //Server settings - //$mail->SMTPDebug = PHPMailer\PHPMailer\SMTP::DEBUG_SERVER; // Enable verbose debug output - $mail->isSMTP(); // Send using SMTP - $mail->Host = $sysconf['mail']['server']; // Set the SMTP server to send through - $mail->SMTPAuth = $sysconf['mail']['auth_enable']; // Enable SMTP authentication - $mail->Username = $sysconf['mail']['auth_username']; // SMTP username - $mail->Password = $sysconf['mail']['auth_password']; // SMTP password - if ($sysconf['mail']['SMTPSecure'] === 'tls') { // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged - $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; - } else if ($sysconf['mail']['SMTPSecure'] === 'ssl') { - $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; - } - $mail->Port = $sysconf['mail']['server_port']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above - - //Recipients - $mail->setFrom($sysconf['mail']['from'], $sysconf['mail']['from_name']); - $mail->addReplyTo($sysconf['mail']['reply_to'], $sysconf['mail']['reply_to_name']); - $mail->addAddress($this->member_email, $this->member_name); - - // Content - // get message template - ob_start(); - include SB . 'admin/admin_template/overdue-mail-tpl.php'; - require MDLBS . 'circulation/circulation_base_lib.inc.php'; - - $circulation = new circulation($this->obj_db, $this->member_id); - $circulation->ignore_holidays_fine_calc = $sysconf['ignore_holidays_fine_calc']; - $circulation->holiday_dayname = $_SESSION['holiday_dayname']; - $circulation->holiday_date = $_SESSION['holiday_date']; - - $_msg_tpl = ob_get_clean(); - - // date - $_curr_date = date('Y-m-d H:i:s'); - - // compile overdue data - $_overdue_data = '' . "\n"; - $_overdue_data .= '' . "\n"; - $_arr_overdued = self::getOverduedLoan($this->obj_db, $this->member_id); - foreach ($_arr_overdued as $_overdue) { - $_overdue_data .= ''; - $_overdue_data .= '' . "\n"; - $_overdue_data .= ''; - } - $_overdue_data .= '
' . __('Title') . '' . __('Item Code') . '' . __('Loan Date') . '' . __('Due Date') . '' . __('Overdue') . '
' . $_overdue['title'] . '' . $_overdue['item_code'] . '' . $_overdue['loan_date'] . '' . $_overdue['due_date'] . '' . $circulation->countOverdueValue($_overdue['loan_id'], date('Y-m-d'))['days'] . ' ' . __('days') . '
'; - - - // message - $_message = str_ireplace(array('', '', '', ''), - array($this->member_id, $this->member_name, $_overdue_data, $_curr_date), $_msg_tpl); - - $mail->isHTML(true); // Set email format to HTML - $mail->Subject = str_replace(array('{member_name}', '{member_email}'), array($this->member_name, $this->member_email), __('Overdue Notice for Member {member_name} ({member_email})')); - $mail->msgHTML($_message); - $mail->AltBody = strip_tags($_message); - - $mail->send(); - return array('status' => 'SENT', 'message' => 'Overdue notification E-Mail have been sent to ' . $this->member_email); - } catch (Exception $exception) { - return array('status' => 'ERROR', 'message' => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); - } - } -} +obj_db = $obj_db; + // get member data from database + $_member_q = $this->obj_db->query(sprintf("SELECT m.*,mt.* FROM member AS m + LEFT JOIN mst_member_type AS mt ON m.member_type_id=mt.member_type_id + WHERE member_id='%s'", $str_member_id)); + + if ($_member_q->num_rows > 0) { + // set the is_member property flag to TRUE + $this->is_member = true; + $_member_d = $_member_q->fetch_assoc(); + // assign database value to class properties + $this->member_id = $_member_d['member_id']; + $this->member_name = $_member_d['member_name']; + $this->member_type_id = $_member_d['member_type_id']; + $this->member_type_name = $_member_d['member_type_name']; + $this->register_date = $_member_d['register_date']; + $this->expire_date = $_member_d['expire_date']; + $this->member_email = $_member_d['member_email']; + $this->inst_name = $_member_d['inst_name']; + $this->member_image = $_member_d['member_image']; + $this->member_notes = $_member_d['member_notes']; + $this->is_pending = (bool)$_member_d['is_pending']; + $this->member_type_prop = array( + 'loan_limit' => $_member_d['loan_limit'], + 'loan_periode' => $_member_d['loan_periode'], + 'enable_reserve' => $_member_d['enable_reserve'], + 'reserve_limit' => $_member_d['reserve_limit'], + 'member_periode' => $_member_d['member_periode'], + 'reborrow_limit' => $_member_d['reborrow_limit'], + 'fine_each_day' => $_member_d['fine_each_day'], + 'grace_periode' => $_member_d['grace_periode'] + ); + + // is membership expired ? + // compare it with current date + $_current_date = date('Y-m-d'); + $_expired_date = simbio_date::compareDates($_current_date, $_member_d['expire_date']); + if ($_expired_date <= $_member_d['expire_date']) { + $this->is_expire = false; + } + } + } + + + # checking wether member is valid or not + # return : boolean + public function valid() + { + return $this->is_member; + } + + + # checking wether membership is already expired + # return : boolean + public function isExpired() + { + return $this->is_expire; + } + + + # checking wether membership is pending + # return : boolean + public function isPending() + { + return $this->is_pending; + } + + + # get all member properties + # retuen : array + public function getMemberTypeProp() + { + // return all member information as an array + return $this->member_type_prop; + } + + + # get info about item being lent by member + # return : array + protected function getItemLoan($int_loan_rules = 0) + { + $_arr_on_loan = array(); + // count how many items is in loan for this member + if ($int_loan_rules) { + $_sql_str = "SELECT item_code FROM loan AS l + WHERE member_id='".$this->member_id."' AND is_lent=1 AND is_return=0 AND loan_rules_id=$int_loan_rules"; + } else { + $_sql_str = "SELECT item_code FROM loan AS l + WHERE member_id='".$this->member_id."' AND is_lent=1 AND is_return=0"; + } + $_count_q = $this->obj_db->query($_sql_str); + while ($_count_d = $_count_q->fetch_row()) { + $_arr_on_loan[] = $_count_d[0]; + } + + return $_arr_on_loan; + } + + + # get an array of member's overdue data + public static function getOverduedLoan($obj_db, $str_member_id) + { // + + $_overdues = array(); + $_ovd_title_q = $obj_db->query(sprintf('SELECT l.loan_id, l.item_code, i.price, i.price_currency, + b.title, l.loan_date, + l.due_date, (TO_DAYS(DATE(NOW()))-TO_DAYS(due_date)) AS \'Overdue Days\' + FROM loan AS l + LEFT JOIN item AS i ON l.item_code=i.item_code + LEFT JOIN biblio AS b ON i.biblio_id=b.biblio_id + WHERE (l.is_lent=1 AND l.is_return=0 AND TO_DAYS(due_date) < TO_DAYS(\''.date('Y-m-d').'\')) AND l.member_id=\'%s\'', $str_member_id)); + while ($_ovd_title_d = $_ovd_title_q->fetch_assoc()) { + $_overdues[] = $_ovd_title_d; + } + + return $_overdues; + } + + + # send overdue notice e-mail + public function sendOverdueNotice() + { + global $sysconf; + $mail = new PHPMailer\PHPMailer\PHPMailer(true); + try { + //Server settings + $mail->SMTPDebug = $sysconf['mail']['debug']; // Enable verbose debug output + $mail->isSMTP(); // Send using SMTP + $mail->Host = $sysconf['mail']['server']; // Set the SMTP server to send through + $mail->SMTPAuth = $sysconf['mail']['auth_enable']; // Enable SMTP authentication + $mail->Username = $sysconf['mail']['auth_username']; // SMTP username + $mail->Password = $sysconf['mail']['auth_password']; // SMTP password + if ($sysconf['mail']['SMTPSecure'] === 'tls') { // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged + $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; + } else if ($sysconf['mail']['SMTPSecure'] === 'ssl') { + $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; + } + $mail->Port = $sysconf['mail']['server_port']; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above + + //Recipients + $mail->setFrom($sysconf['mail']['from'], $sysconf['mail']['from_name']); + $mail->addReplyTo($sysconf['mail']['reply_to'], $sysconf['mail']['reply_to_name']); + $mail->addAddress($this->member_email, $this->member_name); + + // Content + // get message template + ob_start(); + include SB . 'admin/admin_template/overdue-mail-tpl.php'; + require MDLBS . 'circulation/circulation_base_lib.inc.php'; + + $circulation = new circulation($this->obj_db, $this->member_id); + $circulation->ignore_holidays_fine_calc = $sysconf['ignore_holidays_fine_calc']; + $circulation->holiday_dayname = $_SESSION['holiday_dayname']; + $circulation->holiday_date = $_SESSION['holiday_date']; + + $_msg_tpl = ob_get_clean(); + + // date + $_curr_date = date('Y-m-d H:i:s'); + + // compile overdue data + $_overdue_data = '' . "\n"; + $_overdue_data .= '' . "\n"; + $_arr_overdued = self::getOverduedLoan($this->obj_db, $this->member_id); + foreach ($_arr_overdued as $_overdue) { + $_overdue_data .= ''; + $_overdue_data .= '' . "\n"; + $_overdue_data .= ''; + } + $_overdue_data .= '
' . __('Title') . '' . __('Item Code') . '' . __('Loan Date') . '' . __('Due Date') . '' . __('Overdue') . '
' . $_overdue['title'] . '' . $_overdue['item_code'] . '' . $_overdue['loan_date'] . '' . $_overdue['due_date'] . '' . $circulation->countOverdueValue($_overdue['loan_id'], date('Y-m-d'))['days'] . ' ' . __('days') . '
'; + + + // message + $_message = str_ireplace(array('', '', '', ''), + array($this->member_id, $this->member_name, $_overdue_data, $_curr_date), $_msg_tpl); + + $mail->isHTML(true); // Set email format to HTML + $mail->Subject = str_replace(array('{member_name}', '{member_email}'), array($this->member_name, $this->member_email), __('Overdue Notice for Member {member_name} ({member_email})')); + $mail->msgHTML($_message); + $mail->AltBody = strip_tags($_message); + + $mail->send(); + return array('status' => 'SENT', 'message' => 'Overdue notification E-Mail have been sent to ' . $this->member_email); + } catch (Exception $exception) { + return array('status' => 'ERROR', 'message' => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"); + } + } +} diff --git a/admin/modules/reporting/customs/dl_counter.php b/admin/modules/reporting/customs/dl_counter.php index 7b849031..40efaa02 100644 --- a/admin/modules/reporting/customs/dl_counter.php +++ b/admin/modules/reporting/customs/dl_counter.php @@ -135,7 +135,7 @@ } if (isset($_GET['author']) AND !empty($_GET['author'])) { $author = $dbs->escape_string($_GET['author']); - $criteria .= ' AND b.author_name LIKE \'%'.$author.'%\''; + $criteria .= ' AND b.author LIKE \'%'.$author.'%\''; } if (isset($_GET['publishYear']) AND !empty($_GET['publishYear'])) { $publish_year = $dbs->escape_string(trim($_GET['publishYear'])); diff --git a/admin/modules/reporting/customs/dl_detail.php b/admin/modules/reporting/customs/dl_detail.php index d23af741..5a791ced 100644 --- a/admin/modules/reporting/customs/dl_detail.php +++ b/admin/modules/reporting/customs/dl_detail.php @@ -142,7 +142,7 @@ } if (isset($_GET['author']) AND !empty($_GET['author'])) { $author = $dbs->escape_string($_GET['author']); - $criteria .= ' AND b.author_name LIKE \'%'.$author.'%\''; + $criteria .= ' AND b.author LIKE \'%'.$author.'%\''; } if (isset($_GET['publishYear']) AND !empty($_GET['publishYear'])) { $publish_year = $dbs->escape_string(trim($_GET['publishYear'])); diff --git a/admin/modules/reporting/customs/item_titles_list.php b/admin/modules/reporting/customs/item_titles_list.php index 0927f4b3..fd15e745 100755 --- a/admin/modules/reporting/customs/item_titles_list.php +++ b/admin/modules/reporting/customs/item_titles_list.php @@ -1,4 +1,5 @@ '.__('You don\'t have enough privileges to access this area!').'
'); + die('
' . __('You don\'t have enough privileges to access this area!') . '
'); } -require SIMBIO.'simbio_GUI/table/simbio_table.inc.php'; -require SIMBIO.'simbio_GUI/paging/simbio_paging.inc.php'; -require SIMBIO.'simbio_GUI/form_maker/simbio_form_element.inc.php'; -require SIMBIO.'simbio_DB/datagrid/simbio_dbgrid.inc.php'; -require MDLBS.'reporting/report_dbgrid.inc.php'; +require SIMBIO . 'simbio_GUI/table/simbio_table.inc.php'; +require SIMBIO . 'simbio_GUI/paging/simbio_paging.inc.php'; +require SIMBIO . 'simbio_GUI/form_maker/simbio_form_element.inc.php'; +require SIMBIO . 'simbio_DB/datagrid/simbio_dbgrid.inc.php'; +require MDLBS . 'reporting/report_dbgrid.inc.php'; $page_title = 'Items/Copies Report'; $reportView = false; @@ -58,7 +59,7 @@ ?>
-

+

@@ -86,7 +87,7 @@ while ($gmd_d = $gmd_q->fetch_row()) { $gmd_options[] = array($gmd_d[0], $gmd_d[1]); } - echo simbio_form_element::selectList('gmd[]', $gmd_options, '','multiple="multiple" size="5" class="form-control col-3"'); + echo simbio_form_element::selectList('gmd[]', $gmd_options, '', 'multiple="multiple" size="5" class="form-control col-3"'); ?>
@@ -110,7 +111,7 @@ while ($status_d = $status_q->fetch_row()) { $status_options[] = array($status_d[0], $status_d[1]); } - echo simbio_form_element::selectList('status', $status_options,'','class="form-control col-2"'); + echo simbio_form_element::selectList('status', $status_options, '', 'class="form-control col-2"'); ?>
@@ -122,7 +123,7 @@ while ($loc_d = $loc_q->fetch_row()) { $loc_options[] = array($loc_d[0], $loc_d[1]); } - echo simbio_form_element::selectList('location', $loc_options,'','class="form-control col-2"'); + echo simbio_form_element::selectList('location', $loc_options, '', 'class="form-control col-2"'); ?>
@@ -141,8 +142,10 @@
-
- +
+
+
+ table_attr = 'class="s-table table table-sm table-bordered"'; - $reportgrid->setSQLColumn('i.item_code AS \''.__('Item Code').'\'', - 'b.title AS \''.__('Title').'\'', - 'ct.coll_type_name AS \''.__('Collection Type').'\'', - 'i.item_status_id AS \''.__('Item Status').'\'', - 'b.call_number AS \''.__('Call Number').'\'', 'i.biblio_id'); + $reportgrid->setSQLColumn( + 'i.item_code AS \'' . __('Item Code') . '\'', + 'b.title AS \'' . __('Title') . '\'', + 'ct.coll_type_name AS \'' . __('Collection Type') . '\'', + 'i.item_status_id AS \'' . __('Item Status') . '\'', + 'b.call_number AS \'' . __('Call Number') . '\'', + 'i.biblio_id' + ); $reportgrid->setSQLorder('b.title ASC'); // is there any search $criteria = 'b.biblio_id IS NOT NULL '; - if (isset($_GET['title']) AND !empty($_GET['title'])) { + if (isset($_GET['title']) and !empty($_GET['title'])) { $keyword = $dbs->escape_string(trim($_GET['title'])); $words = explode(' ', $keyword); if (count($words) > 1) { @@ -176,17 +182,17 @@ $concat_sql .= ') '; $criteria .= $concat_sql; } else { - $criteria .= ' AND (b.title LIKE \'%'.$keyword.'%\' OR b.isbn_issn LIKE \'%'.$keyword.'%\')'; + $criteria .= ' AND (b.title LIKE \'%' . $keyword . '%\' OR b.isbn_issn LIKE \'%' . $keyword . '%\')'; } } - if (isset($_GET['itemCode']) AND !empty($_GET['itemCode'])) { + if (isset($_GET['itemCode']) and !empty($_GET['itemCode'])) { $item_code = $dbs->escape_string(trim($_GET['itemCode'])); - $criteria .= ' AND i.item_code LIKE \'%'.$item_code.'%\''; + $criteria .= ' AND i.item_code LIKE \'%' . $item_code . '%\''; } if (isset($_GET['collType'])) { $coll_type_IDs = ''; foreach ($_GET['collType'] as $id) { - $id = (integer)$id; + $id = (int)$id; if ($id) { $coll_type_IDs .= "$id,"; } @@ -196,10 +202,10 @@ $criteria .= " AND i.coll_type_id IN($coll_type_IDs)"; } } - if (isset($_GET['gmd']) AND !empty($_GET['gmd'])) { + if (isset($_GET['gmd']) and !empty($_GET['gmd'])) { $gmd_IDs = ''; foreach ($_GET['gmd'] as $id) { - $id = (integer)$id; + $id = (int)$id; if ($id) { $gmd_IDs .= "$id,"; } @@ -209,25 +215,25 @@ $criteria .= " AND b.gmd_id IN($gmd_IDs)"; } } - if (isset($_GET['status']) AND $_GET['status']!='0') { + if (isset($_GET['status']) and $_GET['status'] != '0') { $status = $dbs->escape_string(trim($_GET['status'])); - $criteria .= ' AND i.item_status_id=\''.$status.'\''; + $criteria .= ' AND i.item_status_id=\'' . $status . '\''; } - if (isset($_GET['class']) AND ($_GET['class'] != '')) { + if (isset($_GET['class']) and ($_GET['class'] != '')) { $class = $dbs->escape_string($_GET['class']); - $criteria .= ' AND b.classification LIKE \''.$class.'%\''; + $criteria .= ' AND b.classification LIKE \'' . $class . '%\''; } - if (isset($_GET['location']) AND !empty($_GET['location'])) { + if (isset($_GET['location']) and !empty($_GET['location'])) { $location = $dbs->escape_string(trim($_GET['location'])); - $criteria .= ' AND i.location_id=\''.$location.'\''; + $criteria .= ' AND i.location_id=\'' . $location . '\''; } - if (isset($_GET['publishYear']) AND !empty($_GET['publishYear'])) { + if (isset($_GET['publishYear']) and !empty($_GET['publishYear'])) { $publish_year = $dbs->escape_string(trim($_GET['publishYear'])); - $criteria .= ' AND b.publish_year LIKE \'%'.$publish_year.'%\''; + $criteria .= ' AND b.publish_year LIKE \'%' . $publish_year . '%\''; } if (isset($_GET['recsEachPage'])) { - $recsEachPage = (integer)$_GET['recsEachPage']; - $num_recs_show = ($recsEachPage >= 20 && $recsEachPage <= 200)?$recsEachPage:$num_recs_show; + $recsEachPage = (int)$_GET['recsEachPage']; + $num_recs_show = ($recsEachPage >= 20 && $recsEachPage <= 200) ? $recsEachPage : $num_recs_show; } $reportgrid->setSQLCriteria($criteria); @@ -242,21 +248,21 @@ function showTitleAuthors($obj_db, $array_data) $_biblio_q = $obj_db->query('SELECT b.title, a.author_name FROM biblio AS b LEFT JOIN biblio_author AS ba ON b.biblio_id=ba.biblio_id LEFT JOIN mst_author AS a ON ba.author_id=a.author_id - WHERE b.biblio_id='.$array_data[5]); + WHERE b.biblio_id=' . $array_data[5]); $_authors = ''; while ($_biblio_d = $_biblio_q->fetch_row()) { $_title = $_biblio_d[0]; - $_authors .= $_biblio_d[1].' - '; + $_authors .= $_biblio_d[1] . ' - '; } $_authors = substr_replace($_authors, '', -3); - $_output = $_title.'
'.$_authors.''."\n"; + $_output = $_title . '
' . $_authors . '' . "\n"; return $_output; } function showStatus($obj_db, $array_data) { $output = __('Available'); - $q = $obj_db->query('SELECT item_status_name FROM mst_item_status WHERE item_status_id=\''.$array_data[3].'\''); - if(!empty($q->num_rows)){ + $q = $obj_db->query('SELECT item_status_name FROM mst_item_status WHERE item_status_id=\'' . $array_data[3] . '\''); + if (!empty($q->num_rows)) { $d = $q->fetch_row(); $s = $d[0]; $output = $s; @@ -269,14 +275,28 @@ function showStatus($obj_db, $array_data) $reportgrid->modifyColumnContent(3, 'callback{showStatus}'); $reportgrid->invisible_fields = array(5); + // show spreadsheet export button + $reportgrid->show_spreadsheet_export = true; + // put the result into variables echo $reportgrid->createDataGrid($dbs, $table_spec, $num_recs_show); - echo ''; + $xlsquery = "SELECT i.item_code AS '" . __('Item Code') . "', + b.title AS '" . __('Title') . "', + ct.coll_type_name AS '" . __('Collection Type') . "', + i.item_status_id AS '" . __('Item Status') . "', + b.call_number AS '" . __('Call Number') . "' FROM " . + $table_spec . " WHERE " . $criteria; + // echo $xlsquery; + unset($_SESSION['xlsdata']); + $_SESSION['xlsquery'] = $xlsquery; + $_SESSION['tblout'] = "title_list_item"; + $content = ob_get_clean(); // include the page template - require SB.'/admin/'.$sysconf['admin_template']['dir'].'/printed_page_tpl.php'; + require SB . '/admin/' . $sysconf['admin_template']['dir'] . '/printed_page_tpl.php'; } diff --git a/admin/modules/system/app_user.php b/admin/modules/system/app_user.php index 6ff5be94..ab99f29d 100755 --- a/admin/modules/system/app_user.php +++ b/admin/modules/system/app_user.php @@ -74,6 +74,8 @@ function getUserType($obj_db, $array_data, $col) { if ($query_image->num_rows > 0) { $_delete = $dbs->query(sprintf('UPDATE user SET user_image=NULL WHERE user_id=%d', $_POST['uimg'])); if ($_delete) { + // Change upict + $_SESSION['upict'] = 'person.png'; $postImage = stripslashes($_POST['img']); $postImage = str_replace('/', '', $postImage); @unlink(sprintf(IMGBS.'persons/%s', $postImage)); @@ -177,6 +179,8 @@ function getUserType($obj_db, $array_data, $col) { // upload status alert if (isset($upload_status)) { if ($upload_status == UPLOAD_SUCCESS) { + // Change upict + $_SESSION['upict'] = $data['user_image']; // write log utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'system/user', $_SESSION['realname'].' upload image file '.$upload->new_filename, 'User image', 'Upload'); utility::jsAlert(__('Image Uploaded Successfully')); @@ -200,6 +204,8 @@ function getUserType($obj_db, $array_data, $col) { // upload status alert if (isset($upload_status)) { if ($upload_status == UPLOAD_SUCCESS) { + // Change upict + $_SESSION['upict'] = $data['user_image']; // write log utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'system/user', $_SESSION['realname'].' upload image file '.$upload->new_filename, 'User image', 'Upload'); utility::jsAlert(__('Image Uploaded Successfully')); diff --git a/admin/modules/system/backup.php b/admin/modules/system/backup.php index c7e6fc09..d017eeaf 100755 --- a/admin/modules/system/backup.php +++ b/admin/modules/system/backup.php @@ -123,19 +123,53 @@ ?>
- +
+ + +
- - +
+ setSQLColumn('bl.backup_log_id', - 'u.realname AS \''.__('Backup Executor').'\'', - 'bl.backup_time AS \''.__('Backup Time').'\'', - 'bl.backup_file AS \''.__('Backup File Location').'\'', - 'bl.backup_file AS \''.__('File Size').'\''); - $datagrid->setSQLorder('backup_time DESC'); - $datagrid->modifyColumnContent(4, 'callback{showFileSize}'); -}else{ - $datagrid->setSQLColumn( - 'u.realname AS \''.__('Backup Executor').'\'', +$datagrid->setSQLColumn('bl.backup_log_id', + 'u.realname AS \''.__('Backup Executor').'\'', 'bl.backup_time AS \''.__('Backup Time').'\'', 'bl.backup_file AS \''.__('Backup File Location').'\'', - 'bl.backup_file AS \''.__('File Size').'\''); - $datagrid->setSQLorder('backup_time DESC'); - $datagrid->modifyColumnContent(3, 'callback{showFileSize}'); -} + 'bl.backup_file AS \''.__('File Size').'\''); +$datagrid->setSQLorder('backup_time DESC'); +$datagrid->modifyColumnContent(4, 'callback{showFileSize}'); +if (!$can_write) $datagrid->invisible_fields = [0]; + // is there any search if (isset($_GET['keywords']) AND $_GET['keywords']) { $keywords = $dbs->escape_string($_GET['keywords']); diff --git a/admin/modules/system/backup_proc.php b/admin/modules/system/backup_proc.php index 098b092a..50e14571 100755 --- a/admin/modules/system/backup_proc.php +++ b/admin/modules/system/backup_proc.php @@ -47,10 +47,45 @@ die('
'.__('You don\'t have enough privileges to view this section').'
'); } +function color($message, $type = 'white') +{ + switch ($type) { + case 'success': + $color = 'green'; + break; + + case 'info': + $color = 'blue'; + break; + + case 'error': + $color = 'red'; + break; + + default: + $color = 'white'; + break; + } + + return '' . $message . ''; +} + +function outputWithFlush($message) +{ + if (isset($_POST['verbose']) && $_POST['verbose'] == 'yes') + { + echo str_replace('\n', ' ', $message) . '
'; + ob_flush(); + flush(); + } +} + // if backup process is invoked if (isset($_POST['start']) && isset($_POST['tkn']) && $_POST['tkn'] === $_SESSION['token']) { + outputWithFlush(color('Starting...')); sleep(2); $output = ''; + $error = false; // turn on implicit flush ob_implicit_flush(); @@ -97,12 +132,15 @@ @chdir($sysconf['backup_dir']); // compress the backup using tar gz if(function_exists('exec')){ + outputWithFlush(color('Compressing...')); + sleep(1); exec('tar cvzf backup_'.$time2append.'.sql.tar.gz backup_'.$time2append.'.sql', $outputs, $status); if ($status == COMMAND_SUCCESS) { // delete the original file @unlink($data['backup_file']); $output .= __("File is compressed using tar gz archive format"); $data['backup_file'] = $dbs->escape_string($sysconf['backup_dir'].'backup_'.$time2append.'.sql.tar.gz'); + outputWithFlush(color('Compressing Success', 'success')); } } // return to previous PHP working dir @@ -111,18 +149,27 @@ // input log to database $sql_op = new simbio_dbop($dbs); $sql_op->insert('backup_log', $data); + outputWithFlush(color($output, 'success')); } catch (\Exception $e) { + $error = true; $output = sprintf(__('Backup FAILED!,\n%s'),$e->getMessage()); + outputWithFlush(color($output, 'error')); } } else { - $output = __("Backup FAILED! The Backup directory is not exists or not writeable"); + $error = true; + $output = __("Backup FAILED! The Backup directory is not exists or not writeable") . '
'; $output .= __("Contact System Administrator for the right path of backup directory"); + outputWithFlush(color($output, 'error')); } // remove token unset($_SESSION['token']); - echo ''; - echo ''; + + if ($_POST['verbose'] == 'no') + { + utility::jsToastr(__('Backup'), $dbs->escape_string(strip_tags($output)), ($error ? 'error' : 'success')); + } + echo ''; exit(); } diff --git a/admin/modules/system/biblio_indexer.inc.php b/admin/modules/system/biblio_indexer.inc.php index 24fc0b27..138bafe7 100755 --- a/admin/modules/system/biblio_indexer.inc.php +++ b/admin/modules/system/biblio_indexer.inc.php @@ -139,7 +139,7 @@ public function makeIndex($int_biblio_id) { $data['publish_place'] = $this->obj_db->escape_string($rb_id['publish_place']); $data['isbn_issn'] = $this->obj_db->escape_string($rb_id['isbn_issn']); $data['language'] = $this->obj_db->escape_string($rb_id['language']); - $data['publish_year'] = $rb_id['publish_year']; + $data['publish_year'] = $this->obj_db->escape_string($rb_id['publish_year']); $data['classification'] = $this->obj_db->escape_string($rb_id['classification']); $data['spec_detail_info'] = $this->obj_db->escape_string($rb_id['spec_detail_info']); $data['call_number'] = $this->obj_db->escape_string($rb_id['call_number']); diff --git a/admin/modules/system/envinfo.php b/admin/modules/system/envinfo.php index abd4e1a1..54b79058 100644 --- a/admin/modules/system/envinfo.php +++ b/admin/modules/system/envinfo.php @@ -47,6 +47,7 @@ // require SIMBIO.'simbio_DB/simbio_dbop.inc.php'; $environment = array( + array('title' => __('SLiMS Environment Mode'), 'desc' => ucfirst(ENVIRONMENT)), array('title' => __('SLiMS Version'), 'desc' => SENAYAN_VERSION_TAG), array('title' => __('Operating System'), 'desc' => php_uname('a')), array('title' => __('OS Architecture'), 'desc' => php_uname('m').' '.(8 * PHP_INT_SIZE).' bit'), diff --git a/admin/modules/system/envsetting.php b/admin/modules/system/envsetting.php new file mode 100644 index 00000000..41b24ce1 --- /dev/null +++ b/admin/modules/system/envsetting.php @@ -0,0 +1,145 @@ +setTimeout(() => {parent.$(\'#mainContent\').simbioAJAX(\'' . $_SERVER['PHP_SELF'] . '\')}, 5000)'; + // utility::jsAlert(json_encode($write)); + exit; +} + +?> + + + +submit_button_attr = 'name="saveData" value="'.__('Save Settings').'" class="btn btn-default"'; + +// form table attributes +$form->table_attr = 'id="dataList" class="s-table table"'; +$form->table_header_attr = 'class="alterCell font-weight-bold"'; +$form->table_content_attr = 'class="alterCell2"'; + +// Your Environment +if ($BasedIp) +{ + $thisEnv = ucfirst((!in_array(getCurrentIp(), $RangeIp) ? $Environment : $ConditionEnvironment)); + $HTML = <<{$thisEnv} + HTML; + $form->addAnything('Your Environment Mode', $HTML); + + $Environment = $ConditionEnvironment; +} + +// Environment List +$EnvOptions = [ + [1, __('Production')], + [0, __('Development')] + ]; +$form->addSelectList('env', __('System Environment Mode'), $EnvOptions, ( $Environment == 'production' ? 1 : 0 ) ,'class="form-control col-3"'); +$BasedIpOptions = [ + [0, __('Disable')], + [1, __('Enable')] +]; +$form->addSelectList('basedIp', __('Environment for some IP?'), $BasedIpOptions, ( $BasedIp ? 1 : 0 ) ,'class="form-control col-3"'); +$form->addTextField('textarea', 'rangeIp', __('Range Ip wil be impacted with Environment. Example : 10.120.33.40;20.100.34.10. '), implode(';', $RangeIp), 'style="margin-top: 0px; margin-bottom: 0px; height: 149px;" class="form-control" placeholder="Leave it empty, if you want to set environment to impact for all IP"'); +// print out the object +echo $form->printOut(); \ No newline at end of file diff --git a/admin/modules/system/holiday.php b/admin/modules/system/holiday.php index 80873180..822cdc74 100755 --- a/admin/modules/system/holiday.php +++ b/admin/modules/system/holiday.php @@ -55,12 +55,12 @@ // check form validity $holDesc = trim($dbs->escape_string(strip_tags($_POST['holDesc']))); if (empty($holDesc)) { - utility::jsAlert(__('Holiday description can\'t be empty!')); + utility::jsToastr(__('Holiday Settings'),__('Holiday description can\'t be empty!'),'warning'); exit(); } else { $data['holiday_date'] = trim($_POST['holDate']); // remove extra whitespace if(!preg_match('@^[0-9]{4}-[0-9]{2}-[0-9]{2}$@', $data['holiday_date'])) { - utility::jsAlert(__('Holiday Date Start must have the format YYYY-MM-DD!')); + utility::jsToastr(__('Holiday Settings'),__('Holiday Date Start must have the format YYYY-MM-DD!'),'warning'); exit(); } $holiday_start_date = $data['holiday_date']; @@ -75,28 +75,28 @@ $updateRecordID = (integer)$_POST['updateRecordID']; if ($sql_op->update('holiday', $data, 'holiday_id='.$updateRecordID)) { utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' update holiday date for '.$data['description'], 'Holiday', 'Update'); - utility::jsAlert(__('Holiday Data Successfully updated')); + utility::jsToastr(__('Holiday Settings'),__('Holiday Data Successfully updated'),'success'); // update holiday_dayname session $_SESSION['holiday_date'][$data['holiday_date']] = $data['holiday_date']; echo ''; exit(); } else { utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' failed update holiday data for '.$data['description'], 'Holiday', 'Fail'); - utility::jsAlert(__('Holiday FAILED to update. Please Contact System Administrator')."\n".$sql_op->error); + utility::jsToastr(__('Holiday Settings'),__('Holiday FAILED to update. Please Contact System Administrator')."\n".$sql_op->error,'error'); } } else { /* INSERT RECORD MODE */ // insert the data if ($sql_op->insert('holiday', $data)) { utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' add holiday date for '.$data['description'], 'Holiday', 'Add'); - utility::jsAlert(__('New Holiday Successfully Saved')); + utility::jsToastr(__('Holiday Settings'),__('New Holiday Successfully Saved'),'success'); // update holiday_dayname session $_SESSION['holiday_date'][$data['holiday_date']] = $data['holiday_date']; // date range insert if (!empty($_POST['holDateEnd'])) { $holiday_end_date = trim($_POST['holDateEnd']); // remove extra whitespace if(!preg_match('@^[0-9]{4}-[0-9]{2}-[0-9]{2}$@', $holiday_end_date)) { - utility::jsAlert(__('Holiday Date End must have the format YYYY-MM-DD if it is not empty!')); + utility::jsToastr(__('Holiday Settings'),__('Holiday Date End must have the format YYYY-MM-DD if it is not empty!'),'warning'); exit(); } // check if holiday end date is more than holiday start date @@ -121,7 +121,7 @@ exit(); } else { utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' failed to add holiday data for '.$data['description'], 'Holiday', 'Fail'); - utility::jsAlert(__('Holiday FAILED to Save. Please Contact System Administrator')."\n".$sql_op->error); + utility::jsToastr(__('Holiday Settings'),__('Holiday FAILED to Save. Please Contact System Administrator')."\n".$sql_op->error,'error'); } } } @@ -157,10 +157,10 @@ // error alerting if ($error_num == 0) { utility::writeLogs($dbs, 'staff', $_SESSION['uid'], 'System', $_SESSION['realname'].' remove holiday date with id '.$_log, 'Holiday', 'Delete'); - utility::jsAlert(__('All Data Successfully Deleted')); + utility::jsToastr(__('Holiday Settings'),__('All Data Successfully Deleted'),'success'); echo ''; } else { - utility::jsAlert(__('Some or All Data NOT deleted successfully!\nPlease contact system administrator')); + utility::jsToastr(__('Holiday Settings'),__('Some or All Data NOT deleted successfully!\nPlease contact system administrator'),'warning'); echo ''; } exit(); @@ -170,16 +170,15 @@ ?> '; + + return $message; + } + + function isPdoOk() + { + return class_exists('PDO') && in_array('mysql', \PDO::getAvailableDrivers()); + } + function isPhpOk($expectedVersion) { // Is this version of PHP greater than minimum version required? @@ -94,8 +119,17 @@ function isGdOk() $gd_info = gd_info(); $gd_version = preg_replace('/[^0-9\.]/', '', $gd_info['GD Version']); + // Image extension Support + $Need = ['GIF Read Support','GIF Create Support','JPEG Support','PNG Support']; + $extensionCheck = array_filter($Need, function($Extension) use($gd_info) { + if (isset($gd_info[$Extension]) && ($gd_info[$Extension])) + { + return true; + } + }); + // If the GD version is at least 1.0 - return ($gd_version >= 1); + return ($gd_version >= 1 && count($extensionCheck) == 4); } function isYazOk() @@ -374,6 +408,7 @@ function queryTrigger($array) function updateAdmin($username, $password) { + $username = $this->db->escape_string($username); $sql_update = " UPDATE user set username = '" . $username . "', passwd = '" . password_hash($password, PASSWORD_BCRYPT) . "', @@ -431,4 +466,4 @@ function rollbackSqlMode() { return $this->db->query(sprintf("SET @@sql_mode := '%s' ;", $this->sql_mode)); } -} \ No newline at end of file +} diff --git a/install/Upgrade.inc.php b/install/Upgrade.inc.php index 3a7521e2..c0741d02 100644 --- a/install/Upgrade.inc.php +++ b/install/Upgrade.inc.php @@ -21,7 +21,7 @@ class Upgrade * * @var int */ - private $version = 29; + private $version = 31; /** * @param SLiMS $slims @@ -751,7 +751,7 @@ function upgrade_role_20() ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $sql['insert'][] = " - INSERT INTO `loan_history` + INSERT IGNORE INTO `loan_history` (`loan_id`, `item_code`, `biblio_id`, @@ -1006,4 +1006,25 @@ function upgrade_role_29() { } + /** + * Upgrade role to v9.4.2 + */ + function upgrade_role_30() + { + } + + /** + * Upgrade role to v9.x.x + */ + function upgrade_role_31() + { + $sql['alter'][] = "ALTER TABLE `files` ADD `file_key` text COLLATE 'utf8_unicode_ci' NULL AFTER `file_desc`;"; + if($_POST['oldVersion'] > 19) { + $sql['alter'][] = "ALTER TABLE `biblio` DROP `update_date`;"; + } + $sql['alter'][] = "ALTER TABLE `mst_topic` CHANGE `classification` `classification` varchar(50) COLLATE 'utf8_unicode_ci' NULL COMMENT 'Classification Code' AFTER `auth_list`;"; + + return $this->slims->query($sql, ['alter']); + } + } \ No newline at end of file diff --git a/install/api.php b/install/api.php index 7ab3e0c3..293df2c5 100644 --- a/install/api.php +++ b/install/api.php @@ -40,13 +40,11 @@ $data = [ 'is_pass' => $slims->isPhpOk($php_minimum_version) && $slims->databaseDriverType() && - $slims->isGdOk() && - $slims->isGettextOk() && - $check_dir['status'] && - $slims->isMbStringOk(), + $slims->phpExtensionCheck('bool') && + $check_dir['status'], 'data' => [ 'php' => [ - 'title' => 'PHP', + 'title' => 'PHP Version', 'status' => $slims->isPhpOk($php_minimum_version), 'version' => phpversion(), 'message' => 'Minimum PHP version to install SLiMS is ' . $php_minimum_version . '. Please upgrade it first!' @@ -57,29 +55,11 @@ 'version' => $slims->databaseDriverType(), 'message' => 'SLiMS required MYSQL for database management. Please install it first!' ], - 'gd' => [ - 'title' => 'PHP GD', - 'status' => $slims->isGdOk(), - 'version' => '', - 'message' => 'PHP GD required for image processing!' - ], - 'gettext' => [ - 'title' => 'PHP gettext', - 'status' => $slims->isGettextOk(), - 'version' => '', - 'message' => 'PHP gettext required for translation to other language' - ], - 'mbstring' => [ - 'title' => 'PHP mbstring', - 'status' => $slims->isMbStringOk(), - 'version' => '', - 'message' => 'Mbstring is used to convert strings to different encodings.' - ], - 'yaz' => [ - 'title' => 'YAZ', - 'status' => $slims->isYazOk(), - 'version' => '', - 'message' => 'YAZ not installed. It\'s optional, but will be needed if you want to use Z39.50 protocol.' + 'phpextension' => [ + 'title' => 'PHP Extension', + 'status' => '', + 'version' => '*', + 'data' => $slims->phpExtensionCheck() ], 'chkdir' => [ 'title' => 'Pre-Installation Step', diff --git a/install/index.php b/install/index.php index 3a8e9d1e..b0661a00 100644 --- a/install/index.php +++ b/install/index.php @@ -87,6 +87,10 @@ transform: rotate(360deg); } } + + .min-h-screen { + min-height: 100vh; + } diff --git a/install/install.sql.php b/install/install.sql.php index d0cb8923..67ae4632 100644 --- a/install/install.sql.php +++ b/install/install.sql.php @@ -124,6 +124,7 @@ `file_dir` text collate utf8_unicode_ci, `mime_type` varchar(100) collate utf8_unicode_ci default NULL, `file_desc` text collate utf8_unicode_ci, + `file_key` text collate utf8_unicode_ci, `uploader_id` int(11) NOT NULL, `input_date` datetime NOT NULL, `last_update` datetime NOT NULL, diff --git a/install/sections/Install.js b/install/sections/Install.js index 2a0319c0..2e37281c 100644 --- a/install/sections/Install.js +++ b/install/sections/Install.js @@ -58,7 +58,7 @@ export default { }) } }, - template: `
+ template: `
diff --git a/install/sections/SelectVersion.js b/install/sections/SelectVersion.js index e5bd02a3..47af6d3c 100644 --- a/install/sections/SelectVersion.js +++ b/install/sections/SelectVersion.js @@ -50,6 +50,8 @@ export default { {value: 26, text: 'SLiMS 9.3.0 | Bulian'}, {value: 27, text: 'SLiMS 9.3.1 | Bulian'}, {value: 28, text: 'SLiMS 9.4.0 | Bulian'}, + {value: 29, text: 'SLiMS 9.4.1 | Bulian'}, + {value: 30, text: 'SLiMS 9.4.2 | Bulian'}, ] } }, diff --git a/install/sections/System.js b/install/sections/System.js index d5d9be60..a2c207a3 100644 --- a/install/sections/System.js +++ b/install/sections/System.js @@ -41,7 +41,7 @@ export default { }) } }, - template: `
+ template: `
@@ -51,12 +51,14 @@ export default {

System requirements

Checking the minimum system requirements to install SLiMS

Loading...
-
-

{{d.title}}

-
{{d.version || (d.status ? 'installed' : 'not installed')}}
-
{{d.data}}
-
{{d.message}}
-
+
+
+

{{d.title}}

+
{{d.version || (d.status ? 'installed' : 'not installed')}}
+
{{d.data}}
+
{{d.message}}
+
+
diff --git a/install/sections/Upgrade.js b/install/sections/Upgrade.js index 13667d80..1713653e 100644 --- a/install/sections/Upgrade.js +++ b/install/sections/Upgrade.js @@ -58,7 +58,7 @@ export default { }) } }, - template: `
+ template: `
diff --git a/install/senayan.sql b/install/senayan.sql index 8725d7c9..9ef05af2 100755 --- a/install/senayan.sql +++ b/install/senayan.sql @@ -185,6 +185,7 @@ CREATE TABLE IF NOT EXISTS `files` ( `file_dir` text collate utf8_unicode_ci, `mime_type` varchar(100) collate utf8_unicode_ci default NULL, `file_desc` text collate utf8_unicode_ci, + `file_key` text collate utf8_unicode_ci, `uploader_id` int(11) NOT NULL, `input_date` datetime NOT NULL, `last_update` datetime NOT NULL, @@ -1452,7 +1453,7 @@ DROP TABLE IF EXISTS `files_read`; CREATE TABLE `files_read` ( `filelog_id` int(11) NOT NULL AUTO_INCREMENT, `file_id` int(11) NOT NULL, - `date_read` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP, + `date_read` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP DEFAULT NOW(), `member_id` varchar(20) NULL, `user_id` int(11) DEFAULT NULL, `client_ip` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, diff --git a/install/tables.php b/install/tables.php index c789df20..0157e2d5 100644 --- a/install/tables.php +++ b/install/tables.php @@ -201,7 +201,7 @@ 'default' => '' ], [ - 'field' => 'update_date', + 'field' => 'last_update', 'type' => 'datetime', 'null' => true, 'default' => '' @@ -533,6 +533,12 @@ 'null' => true, 'default' => null ], + [ + 'field' => 'file_key', + 'type' => 'text', + 'null' => true, + 'default' => null + ], [ 'field' => 'uploader_id', 'type' => 'int(11)', diff --git a/js/pdfjs/build/ObjectPdf.js b/js/pdfjs/build/ObjectPdf.js new file mode 100644 index 00000000..f482d216 --- /dev/null +++ b/js/pdfjs/build/ObjectPdf.js @@ -0,0 +1 @@ +var ObjectPdf={t:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"abcdefghijklmnopqrstuvwxyz0123456789+/=",decode:function(t){var i="";var e,r,n;var c,a,s,h;var f=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f>4;r=(a&15)<<4|s>>2;n=(s&3)<<6|h;i=i+String.fromCharCode(e);if(s!=64){i=i+String.fromCharCode(r)}if(h!=64){i=i+String.fromCharCode(n)}}i=this.i(i);return i},i:function(t){var i="";var e=0;var r=c1=c2=0;while(e191&&r<224){c2=t.charCodeAt(e+1);i+=String.fromCharCode((r&31)<<6|c2&63);e+=2}else{c2=t.charCodeAt(e+1);c3=t.charCodeAt(e+2);i+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);e+=3}}return i},create:async function(t){let i=new FormData;i.append("init",t);const e=await fetch(`index.php?p=fstream&initialize=true`,{method:"post",body:i});let r=await e.text();const n=Object.create(null);n.password=this.decode(this.decode(r).replace(t,""));return n}}; \ No newline at end of file diff --git a/js/pdfjs/mobile/index.php b/js/pdfjs/mobile/index.php index 8c70bbb5..0d304f85 100644 --- a/js/pdfjs/mobile/index.php +++ b/js/pdfjs/mobile/index.php @@ -23,9 +23,11 @@ + diff --git a/js/pdfjs/mobile/js/viewer.js b/js/pdfjs/mobile/js/viewer.js index 66de5559..5e5fb092 100644 --- a/js/pdfjs/mobile/js/viewer.js +++ b/js/pdfjs/mobile/js/viewer.js @@ -47,7 +47,7 @@ var PDFViewerApplication = { * @returns {Promise} - Returns the promise, which is resolved when document * is opened. */ - open: function (params) { + open: async function (params) { if (this.pdfLoadingTask) { // We need to destroy already opened document return this.close().then( @@ -63,12 +63,14 @@ var PDFViewerApplication = { this.setTitleUsingUrl(url); // Loading document. - var loadingTask = pdfjsLib.getDocument({ + var obj = await ObjectPdf.create(params.loaderInit) + var initTask = { url: url, maxImageSize: MAX_IMAGE_SIZE, cMapUrl: CMAP_URL, - cMapPacked: CMAP_PACKED, - }); + cMapPacked: CMAP_PACKED + } + var loadingTask = pdfjsLib.getDocument({...obj, ...initTask}); this.pdfLoadingTask = loadingTask; loadingTask.onProgress = function (progressData) { @@ -446,6 +448,7 @@ document.addEventListener( PDFViewerApplication.animationStartedPromise.then(function () { PDFViewerApplication.open({ url: DEFAULT_URL, + loaderInit: LOADER_INIT }); }); diff --git a/js/pdfjs/web/viewer.js b/js/pdfjs/web/viewer.js index 71f92e7b..75ecfebb 100755 --- a/js/pdfjs/web/viewer.js +++ b/js/pdfjs/web/viewer.js @@ -1031,7 +1031,7 @@ var workerParameters, key, parameters, apiParameters, _key, prop, loadingTask; - return _regenerator2.default.wrap(function _callee7$(_context7) { + return _regenerator2.default.wrap(async function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: @@ -1049,8 +1049,8 @@ for (key in workerParameters) { _pdfjsLib.GlobalWorkerOptions[key] = workerParameters[key]; } - parameters = Object.create(null); - + parameters = await ObjectPdf.create(loaderInit); + if (typeof file === 'string') { this.setTitleUsingUrl(file); parameters.url = file; diff --git a/js/pdfjs/web/viewer.php b/js/pdfjs/web/viewer.php index 2b190ad7..93aae6d7 100755 --- a/js/pdfjs/web/viewer.php +++ b/js/pdfjs/web/viewer.php @@ -35,11 +35,12 @@ + diff --git a/lib/Config.php b/lib/Config.php index ced9dc11..8f31c88b 100644 --- a/lib/Config.php +++ b/lib/Config.php @@ -34,7 +34,7 @@ class Config public function __construct() { // load default config folder - $this->load(__DIR__ . '/../config'); + $this->load(__DIR__ . '/../config', ['sysconfig.local.inc.php', 'sysconfig.local.inc-sample.php']); } /** @@ -77,13 +77,13 @@ function loadFromDatabase() { $query = DB::getInstance()->query('SELECT setting_name, setting_value FROM setting'); while ($data = $query->fetch(PDO::FETCH_OBJ)) { - $value = unserialize($data->setting_value); + $value = @unserialize($data->setting_value); if (is_array($value)) { foreach ($value as $id => $current_value) { $this->configs[$data->setting_name][$id] = $current_value; } } else { - $this->configs[$data->setting_name] = stripslashes($value); + $this->configs[$data->setting_name] = stripslashes($value??''); } } } @@ -111,6 +111,30 @@ public function get($key, $default = null) $config = $default; } } + + // if result is null, try to get global $sysconf + if (is_null($config)) $config = $this->getGlobal($key, $default); + + return $config; + } + + public function getGlobal($key, $default = null) + { + global $sysconf; + $keys = explode('.', $key); + $config = $default; + foreach ($keys as $index => $_key) { + if ($index < 1) { + $config = $sysconf[$_key] ?? $default; + continue; + } + if ($config === $default) break; + if (isset($config[$_key])) { + $config = $config[$_key]; + } else { + $config = $default; + } + } return $config; } } \ No newline at end of file diff --git a/lib/GroupMenu.php b/lib/GroupMenu.php new file mode 100644 index 00000000..66f32d70 --- /dev/null +++ b/lib/GroupMenu.php @@ -0,0 +1,82 @@ +uniq_id = $uniq_id; + return $this; + } + + function group($group_name) + { + if (!is_null($this->uniq_id)) { + $this->group[strtolower($group_name)][] = $this->uniq_id; + $this->plugin_in_group[] = $this->uniq_id; + $this->uniq_id = null; + } + return GroupMenuOrder::getInstance()->bind($group_name); + } + + /** + * @return array + */ + public function getGroup(): array + { + return $this->group; + } + + public function getPluginInGroup(): array + { + return $this->plugin_in_group; + } + + function getGroupName($uniq_id) + { + foreach ($this->group as $key => $group) { + if (in_array($uniq_id, $group)) return $key; + } + return null; + } +} \ No newline at end of file diff --git a/lib/GroupMenuOrder.php b/lib/GroupMenuOrder.php new file mode 100644 index 00000000..f6a9d2fb --- /dev/null +++ b/lib/GroupMenuOrder.php @@ -0,0 +1,72 @@ +current_group = strtolower($current_group); + return $this; + } + + public function before($group_name) + { + $this->order('before', $group_name); + } + + public function after($group_name) + { + $this->order('after', $group_name); + } + + public function order($position, $group_name) + { + if (!is_null($this->current_group)) { + $this->order[$this->current_group] = ['position' => $position, 'group' => strtolower($group_name)]; + } + + $this->current_group = null; + } + + public function getOrder() + { + return $this->order; + } +} diff --git a/lib/Plugins.php b/lib/Plugins.php index 7dd21f58..79285943 100644 --- a/lib/Plugins.php +++ b/lib/Plugins.php @@ -1,4 +1,5 @@ hooks[$hook][] = $callback; } + public function registerHook($hook, $callback) + { + $this->register($hook, $callback); + } + public function registerMenu($module_name, $label, $path, $description = null) { $hash = md5(realpath($path)); if ($module_name === 'opac') { $name = strtolower(implode('_', explode(' ', $label))); - $this->menus[$module_name][$name] = [$label, SWB . 'index.php?p=' . $module_name, $description, realpath($path)]; + $this->menus[$module_name][$name] = [$label, SWB . 'index.php?p=' . $name, $description, realpath($path)]; } else { $this->menus[$module_name][$hash] = [$label, AWB . 'plugin_container.php?mod=' . $module_name . '&id=' . $hash, $description, realpath($path)]; } + + $group_instance = GroupMenu::getInstance()->bind($hash); + if (!is_null($this->group_name)) $group_instance->group($this->group_name); + + return $group_instance; + } + + public function registerSearchEngine($class_name) + { + Engine::init()->set($class_name); + } + + public static function group($group_name, $callback): GroupMenuOrder + { + self::getInstance()->setGroupName($group_name); + $callback(); + self::getInstance()->setGroupName(null); + return GroupMenuOrder::getInstance()->bind($group_name); + } + + public static function menu($module_name, $label, $path, $description = null) + { + return self::getInstance()->registerMenu($module_name, $label, $path, $description = null); + } + + public static function hook($hook, $callback) + { + self::getInstance()->registerHook($hook, $callback); + } + + public function setGroupName($group_name) + { + $this->group_name = $group_name; } public function execute($hook, $params = []) @@ -231,5 +272,4 @@ public function getMenus($module = null): array if (is_null($module)) return $this->menus; return $this->menus[$module] ?? []; } - -} \ No newline at end of file +} diff --git a/lib/SearchEngine/Contract.php b/lib/SearchEngine/Contract.php new file mode 100644 index 00000000..43534622 --- /dev/null +++ b/lib/SearchEngine/Contract.php @@ -0,0 +1,90 @@ +page = abs((int)($_GET['page'] ?? 1)); + // setup offset + $this->offset = ($this->page - 1) * $this->limit; + } + + /** + * @param Criteria $criteria + */ + public function setCriteria(Criteria $criteria): void + { + $this->criteria = $criteria; + } + + /** + * @param int $limit + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + /** + * @return int + */ + public function getLimit(): int + { + return $this->limit; + } + + /** + * @return int + */ + public function getNumRows(): int + { + return $this->num_rows; + } + + abstract function getDocuments(); + + abstract function toArray(); + + abstract function toJSON(); + + abstract function toHTML(); + + abstract function toXML(); + + abstract function toRSS(); +} \ No newline at end of file diff --git a/lib/SearchEngine/Criteria.php b/lib/SearchEngine/Criteria.php new file mode 100644 index 00000000..ea5159b5 --- /dev/null +++ b/lib/SearchEngine/Criteria.php @@ -0,0 +1,165 @@ +properties[$name] ?? null; + } + + public function __set($name, $value) + { + $this->properties[$name] = trim($value); + return $this; + } + + public function exact($field, $value) + { + if (!empty($this->queries)) $this->queries[] = ['boolean', 'exact']; + $this->addCriteria($field, $value); + } + + public function and($field, $value) + { + if (!empty($this->queries)) $this->queries[] = ['boolean', 'and']; + $this->addCriteria($field, $value); + } + + public function or($field, $value) + { + if (!empty($this->queries)) $this->queries[] = ['boolean', 'or']; + $this->addCriteria($field, $value); + } + + public function not($field, $value) + { + if (!empty($this->queries)) $this->queries[] = ['boolean', 'not']; + $this->addCriteria($field, $value); + } + + private function addCriteria($field, $value) { + $this->queries[] = [$field, $value]; + $this->{$field} = $value; + } + + public function getQueries(): string + { + $q = []; + foreach ($this->queries as $query) { + if ($query[0] !== 'boolean') $q[] = implode('=', $query); + } + return implode('&', $q); + } + + /** + * CQL Tokenizer + * Tokenize CQL string to array for easy processing + * + * This method implement simbio_tokenizeCQL by Arie Nugraha (dicarve@yahoo.com) + * + * @param array $stop_words + * @param int $max_words + * @return Generator + */ + function toCQLToken(array $stop_words = [], int $max_words = 20): Generator + { + // simple search by default search to title, author and subject field + if (empty($this->queries) && !is_null($this->keywords) && $this->keywords !== '') + foreach (['title', 'author', 'subject'] as $item) $this->or($item, $this->keywords); + + $inside_quote = false; + $phrase = ''; + $last_boolean = '+'; + $word_count = 0; + foreach ($this->queries as $item) { + // SAFEGUARD! + if ($word_count > $max_words) break; + + list($key, $value) = $item; + + // check for stop words + if (in_array($value, $stop_words)) continue; + + // check for boolean mode + if (preg_match('@\b(exact|and|or|not)\b@i', $value)) { + $bool = strtolower($value); + $last_boolean = '+'; + if (!$inside_quote) { + switch ($bool) { + case 'exact': + $last_boolean = '++'; + break; + case 'or': + $last_boolean = '*'; + break; + case 'not': + $last_boolean = '-'; + break; + } + } + + yield ['f' => 'boolean', 'b' => $last_boolean]; + + continue; + } + + // check if we are inside quotes + if ($value[0] === '"') { + $inside_quote = true; + // remove the first quote + $value = substr_replace($value, '', 0, 1); + } + if ($inside_quote) { + if (strpos($value, "") === strlen($value) - 1) { + $inside_quote = false; + $phrase .= str_replace('"', '', $value); + yield ['f' => $key, 'b' => $last_boolean, 'q' => $phrase, 'is_phrase' => true]; + // reset phrase + $phrase = ''; + } else { + $phrase .= str_replace('"', '', $value) . ' '; + continue; + } + } else { + if (stripos($value, '(') === true) { + yield ['f' => 'opengroup', 'b' => $last_boolean]; + } elseif (stripos($value, ')') === true) { + yield ['f' => 'closegroup', 'b' => $last_boolean]; + } else { + yield ['f' => $key, 'b' => $last_boolean, 'q' => $value]; + } + } + $word_count++; + } + yield ['f' => 'cql_end']; + } +} \ No newline at end of file diff --git a/lib/SearchEngine/DefaultEngine.php b/lib/SearchEngine/DefaultEngine.php new file mode 100644 index 00000000..ad7ca532 --- /dev/null +++ b/lib/SearchEngine/DefaultEngine.php @@ -0,0 +1,479 @@ +buildSQL(); + + // execute query + $db = DB::getInstance(); + $count = $db->query($sql['count']); + $query = $db->query($sql['query']); + + // get results + $this->num_rows = ($count->fetch(\PDO::FETCH_NUM))[0] ?? 0; + $this->documents = $query->fetchAll(\PDO::FETCH_ASSOC); + + // end time + $end = microtime(true); + $this->query_time = round($end - $start, 5); + } + + function buildSQL(): array + { + $sql_select = 'select b.biblio_id, b.title, b.image, b.isbn_issn, b.publish_year, mp.publisher_name as `publisher`, mpl.place_name as `publish_place`, b.labels, b.input_date'; + + // checking custom front page fields file + $file_path = SB; + $file_path .= config('template.dir', 'template') . DS; + $file_path .= config('template.theme', 'default') . DS; + $file_path .= 'custom_frontpage_record.inc.php'; + if (file_exists($file_path)) { + include $file_path; + $this->custom_fields = $custom_fields ?? []; + foreach ($this->custom_fields as $field => $field_opts) { + if ($field_opts[0] == 1 && !in_array($field, array('availability', 'isbn_issn'))) { + $sql_select .= ", b.$field"; + } + } + } + + $sql_join = 'left join mst_publisher as mp on b.publisher_id=mp.publisher_id '; + $sql_join .= 'left join mst_place as mpl on b.publish_place_id=mpl.place_id '; + + // location + $sql_group = ''; + if (!is_null($this->criteria->location) || !is_null($this->criteria->colltype)) { + $sql_join .= 'left join item as i on b.biblio_id=i.biblio_id '; + $sql_group = 'group by b.biblio_id'; + } + + $sql_criteria = 'where b.opac_hide=0 '; + $sql_criteria .= ($c = $this->buildCriteria($this->criteria)) !== '' ? 'and (' . $c . ') ' : ''; + + $sql_query = $sql_select . ' from biblio as b ' . $sql_join . $sql_criteria . $sql_group . ' order by b.last_update desc limit ' . $this->limit . ' offset ' . $this->offset; + $sql_count = 'select count(b.biblio_id)' . ' from biblio as b ' . $sql_join . $sql_criteria . $sql_group; + + return [ + 'count' => $sql_count, + 'query' => $sql_query + ]; + } + + function buildCriteria(): string + { + $title_buffer = ''; + $boolean = ''; + $sql_criteria = ''; + foreach ($this->criteria->toCQLToken($this->stop_words) as $token) { + $field = $token['f']; + + if ($title_buffer === '' && $field !== 'boolean') + $sql_criteria .= ' ' . $boolean . ' '; + + // flush title string concatenation + if ($field !== 'title' && $title_buffer !== '') { + $title_buffer = trim($title_buffer); + $sql_criteria .= " b.biblio_id in(select distinct biblio_id from biblio where match (title, series_title) against ('" . $title_buffer . "' in boolean mode)) "; + // reset title buffer + $title_buffer = ''; + } + + // break the loop if we meet cql_end field + if ($field === 'cql_end') break; + + // boolean mode + $bool = $token['b'] ?? $token; + $boolean = ($bool === '*') ? 'or' : 'and'; + + // search value + $query = $token['q'] ?? null; + switch ($field) { + case 'title': + if (strlen($query) < 4) { + $sql_criteria .= " b.title like '%" . $query . "%' "; + $title_buffer = ''; + } else { + if ($token['is_phrase'] ?? false) { + $title_buffer .= ' ' . $bool . '"' . $query . '"'; + } else { + $title_buffer .= ' ' . $bool . $query; + } + } + break; + + case 'author': + $sub_query = "select ba.biblio_id from biblio_author as ba left join mst_author as ma on ba.author_id=ma.author_id where ma.author_name like '%" . $query . "%'"; + if ($bool === '-') { + $sql_criteria .= ' b.biblio_id not in(' . $sub_query . ')'; + } else { + $sql_criteria .= ' b.biblio_id in(' . $sub_query . ')'; + } + break; + + case 'subject': + $sub_query = "select bt.biblio_id from biblio_topic as bt left join mst_topic as mt on bt.topic_id=mt.topic_id where mt.topic like '%" . $query . "%'"; + if ($bool === '-') { + $sql_criteria .= ' b.biblio_id not in(' . $sub_query . ')'; + } else { + $sql_criteria .= ' b.biblio_id in(' . $sub_query . ')'; + } + // reset title buffer + $title_buffer = ''; + break; + + case 'location': + $sub_query = "select location_id from mst_location where location_name = '" . $query . "'"; + if ($bool === '-') { + $sql_criteria .= ' i.location_id not in(' . $sub_query . ')'; + } else { + $sql_criteria .= ' i.location_id in(' . $sub_query . ')'; + } + break; + + case 'colltype': + $sub_query = "select coll_type_id from mst_coll_type where coll_type_name = '" . $query . "'"; + if ($bool === '-') { + $sql_criteria .= ' i.coll_type_id not in(' . $sub_query . ')'; + } else { + $sql_criteria .= ' i.coll_type_id in(' . $sub_query . ')'; + } + break; + + case 'itemcode': + if ($bool === '-') { + $sql_criteria .= " i.item_code != '" . $query . "'"; + } else { + $sql_criteria .= " i.item_code = '" . $query . "'"; + } + break; + + case 'callnumber': + if ($bool === '-') { + $sql_criteria .= " b.call_number not like '" . $query . "%'"; + } else { + $sql_criteria .= " b.call_number like '" . $query . "%'"; + } + break; + + case 'itemcallnumber': + if ($bool === '-') { + $sql_criteria .= " i.call_number not like '" . $query . "%'"; + } else { + $sql_criteria .= " i.call_number like '" . $query . "%'"; + } + break; + + case 'class': + if ($bool === '-') { + $sql_criteria .= " b.classification not like '" . $query . "%'"; + } else { + $sql_criteria .= " b.classification like '" . $query . "%'"; + } + break; + + case 'isbn': + if ($bool === '-') { + $sql_criteria .= " b.isbn_issn != '" . $query . "'"; + } else { + $sql_criteria .= " b.isbn_issn = '" . $query . "'"; + } + break; + + case 'publisher': + $sub_query = "select publisher_id from mst_publisher where publisher_name like '%" . $query . "%'"; + if ($bool === '-') { + $sql_criteria .= ' b.publisher_id not in (' . $sub_query . ')'; + } else { + $sql_criteria .= ' b.publisher_id in (' . $sub_query . ')'; + } + break; + + case 'publishyear': + if ($bool === '-') { + $sql_criteria .= " b.publish_year != '" . $query . "'"; + } else { + $sql_criteria .= " b.publish_year = '" . $query . "'"; + } + break; + + case 'gmd': + $sub_query = "select gmd_id from mst_gmd where gmd_name like '%" . $query . "%'"; + if ($bool === '-') { + $sql_criteria .= ' b.gmd_id not in (' . $sub_query . ')'; + } else { + $sql_criteria .= ' b.gmd_id in (' . $sub_query . ')'; + } + break; + + case 'notes': + $query = isset($query['is_phrase']) ? '"' . $query . '"' : $query; + if ($bool === '-') { + $sql_criteria .= " not (match (b.notes) against ('" . $query . "' in boolean mode))"; + } else { + $sql_criteria .= " (match (b.notes) against ('" . $query . "' in boolean mode))"; + } + break; + } + } + return preg_replace('@^(AND|OR|NOT)\s*|\s+(AND|OR|NOT)$@i', '', trim($sql_criteria)); + } + + function toArray() + { + // TODO: Implement toArray() method. + } + + function toJSON() + { + $jsonld = [ + '@context' => 'http://schema.org', + '@type' => 'Book', + 'total_rows' => $this->num_rows, + 'page' => $this->page, + 'records_each_page' => $this->limit, + '@graph' => [], + ]; + + $db = DB::getInstance(); + + foreach ($this->documents as $document) + { + $record = []; + $record['@id'] = 'http://' . $_SERVER['SERVER_NAME']. SWB . 'index.php?p=show_detail&id=' . $document['biblio_id']; + $record['name'] = trim($document['title']); + + // get the authors data + $_biblio_authors_q = $db->prepare('SELECT a.*,ba.level FROM mst_author AS a' + .' LEFT JOIN biblio_author AS ba ON a.author_id=ba.author_id WHERE ba.biblio_id=?'); + $_biblio_authors_q->execute([$document['biblio_id']]); + + $record['author'] = []; + + while ($_auth_d = $_biblio_authors_q->fetch(\PDO::FETCH_ASSOC)) { + $record['author']['name'][] = trim($_auth_d['author_name']); + } + + // ISBN + $record['isbn'] = $document['isbn_issn']; + + // publisher + $record['publisher'] = $document['publisher']; + + // publish date + $record['dateCreated'] = $document['publish_year']; + + // doc images + $_image = ''; + if (!empty($document['image'])) { + $_image = urlencode($document['image']); + $record['image'] = $_image; + } + + $jsonld['@graph'][] = $record; + } + + return json_encode($jsonld); + } + + function toHTML() + { + $buffer = ''; + // include biblio list html template callback + $path = SB . config('template.dir', 'template') . DS; + $path .= config('template.theme', 'default') . DS . 'biblio_list_template.php'; + include $path; + + foreach ($this->documents as $i => $document) { + $buffer .= \biblio_list_format(DB::getInstance('mysqli'), $document, $i, [ + 'keywords' => $this->criteria->keywords, + 'enable_custom_frontpage' => true, + 'custom_fields' => $this->custom_fields + ]); + } + return $buffer; + } + + function toXML() + { + $xml = new \XMLWriter(); + $xml->openMemory(); + $xml->setIndent(true); + $xml->startElement('modsCollection'); + $xml->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $xml->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $xml->writeAttribute('xmlns', 'http://www.loc.gov/mods/v3'); + $xml->writeAttribute('xmlns:slims', 'http://slims.web.id'); + $xml->writeAttribute('xsi:schemaLocation', 'http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd'); + + $xml->startElementNS('slims', 'resultInfo', null); + $xml->startElementNS('slims', 'modsResultNum', null); + $xml->text($this->num_rows); + $xml->endElement(); // -- modsResultNum + $xml->startElementNS('slims', 'modsResultPage', null); + $xml->text($this->page); + $xml->endElement(); // -- modsResultPage + $xml->startElementNS('slims', 'modsResultShowed', null); + $xml->text($this->limit); + $xml->endElement(); // -- modsResultShowed + $xml->endElement(); // -- resultInfo + + foreach ($this->documents as $document) { + $xml->startElement('mods'); + $xml->writeAttribute('version', '3.3'); + $xml->writeAttribute('ID', $document['biblio_id']); + + // parsing title + $title_main = $document['title']; + $title_sub = ''; + if (stripos($document['title'], '/') !== false) { + $title_main = trim(substr_replace($document['title'], '', stripos($document['title'], '/') + 1)); + } + if (stripos($document['title'], ':') !== false) { + $title_main = trim(substr_replace($document['title'], '', stripos($document['title'], ':') + 1)); + $title_sub = trim(substr_replace($document['title'], '', 0, stripos($document['title'], ':') + 1)); + } + if (stripos($title_sub, '/') !== false) { + $title_sub = trim(substr_replace($title_sub, '', stripos($title_sub, '/') + 1)); + } + + $xml->startElement('titleInfo'); + $xml->startElement('title'); + $xml->text($title_main); + $xml->endElement(); // -- title + if ($title_sub !== '') { + $xml->startElement('subTitle'); + $xml->text($title_sub); + $xml->endElement(); // -- subTitle + } + $xml->endElement(); // -- titleInfo + + // authors + $this->xmlAuthor($xml, $document['biblio_id']); + + $xml->startElement('typeOfResource'); + $xml->writeAttribute('collection', 'yes'); + $xml->text('mixed material'); + $xml->endElement(); // -- typeOfResource + $xml->startElement('identifier'); + $xml->writeAttribute('type', 'isbn'); + $xml->text(str_replace(array('-', ' '), '', $document['isbn_issn'])); + $xml->endElement(); // -- identifier + + $xml->startElement('originInfo'); + $xml->startElement('place'); + $xml->startElement('placeTerm'); + $xml->writeAttribute('type', 'text'); + $xml->text($document['publish_place']??''); + $xml->endElement(); // -- placeTerm + $xml->startElement('publisher'); + $xml->text($document['publisher']); + $xml->endElement(); // -- publisher + $xml->startElement('dateIssued'); + $xml->text($document['publish_year']); + $xml->endElement(); // -- dateIssued + $xml->endElement(); // -- place + $xml->endElement(); // -- originInfo + + // digital file + $this->xmlAttachment($xml, $document['biblio_id']); + + // images + if (!empty($document['image'])) { + $xml->startElementNS('slims', 'image', null); + $xml->text(urlencode($document['image'])); + $xml->endElement(); + } + + $xml->endElement(); // -- mods + } + + $xml->endElement(); // -- modsCollection + + return $xml->flush(); + } + + function xmlAuthor(&$xml, $biblio_id) + { + $query = DB::getInstance()->query('SELECT a.*,ba.level FROM mst_author AS a' + . ' LEFT JOIN biblio_author AS ba ON a.author_id=ba.author_id WHERE ba.biblio_id=' . $biblio_id); + while ($author = $query->fetch()) { + $xml->startElement('name'); + $xml->writeAttribute('type', config('authority_type')[$author['authority_type']] ?? ''); + $xml->writeAttribute('authority', $author['auth_list']??''); + $xml->startElement('namePart'); + $xml->text($author['author_name']); + $xml->endElement(); // -- namePart + $xml->startElement('role'); + $xml->startElement('roleTerm'); + $xml->writeAttribute('type', 'text'); + $xml->text(config('authority_level')[$author['level']] ?? ''); + $xml->endElement(); // -- roleTerm + $xml->endElement(); // -- role + $xml->endElement(); // -- name + } + } + + function xmlAttachment(&$xml, $biblio_id) + { + $query = DB::getInstance()->query('SELECT att.*, f.* FROM biblio_attachment AS att + LEFT JOIN files AS f ON att.file_id=f.file_id WHERE att.biblio_id=' . $biblio_id . ' AND att.access_type=\'public\' LIMIT 20'); + if ($query->rowCount() > 0) { + $xml->startElementNS('slims', 'digitals', null); + while ($attachment_d = $query->fetch()) { + // check member type privileges + if ($attachment_d['access_limit']) continue; + $xml->startElementNS('slims', 'digital_item', null); + $xml->writeAttribute('id', $attachment_d['file_id']); + $xml->writeAttribute('url', trim($attachment_d['file_url'])); + $xml->writeAttribute('path', $attachment_d['file_dir'] . '/' . $attachment_d['file_name']); + $xml->writeAttribute('mimetype', $attachment_d['mime_type']); + $xml->text($attachment_d['file_title']); + $xml->endElement(); // -- digital_item + } + $xml->endElement(); // -- digitals + } + } + + function toRSS() + { + // TODO: Implement toRSS() method. + } +} diff --git a/lib/SearchEngine/Engine.php b/lib/SearchEngine/Engine.php new file mode 100644 index 00000000..cd345792 --- /dev/null +++ b/lib/SearchEngine/Engine.php @@ -0,0 +1,52 @@ +engine[] = $class_name; + return $this; + } + + function get(): array + { + return $this->engine; + } +} \ No newline at end of file diff --git a/lib/SearchEngine/SearchBiblioEngine.php b/lib/SearchEngine/SearchBiblioEngine.php new file mode 100644 index 00000000..f0e52516 --- /dev/null +++ b/lib/SearchEngine/SearchBiblioEngine.php @@ -0,0 +1,465 @@ +buildSQL(); + + // execute query + $db = DB::getInstance(); + $count = $db->query($sql['count']); + $query = $db->query($sql['query']); + + // get results + $this->num_rows = ($count->fetch(\PDO::FETCH_NUM))[0] ?? 0; + $this->documents = $query->fetchAll(\PDO::FETCH_ASSOC); + + // end time + $end = microtime(true); + $this->query_time = round($end - $start, 5); + } + + function buildSQL() + { + $sql_select = 'select sb.biblio_id, sb.title, sb.author, sb.topic, sb.image, sb.isbn_issn, sb.publisher, sb.publish_place, sb.publish_year, sb.labels, sb.input_date'; + + // checking custom front page fields file + $file_path = SB; + $file_path .= config('template.dir', 'template') . DS; + $file_path .= config('template.theme', 'default') . DS; + $file_path .= 'custom_frontpage_record.inc.php'; + if (file_exists($file_path)) { + include $file_path; + $this->custom_fields = $custom_fields ?? []; + foreach ($this->custom_fields as $field => $field_opts) { + if ($field_opts[0] == 1 && !in_array($field, array('availability', 'isbn_issn'))) { + $sql_select .= ", sb.$field"; + } + } + } + + $sql_criteria = 'where sb.opac_hide=0 '; + $sql_criteria .= ($c = $this->buildCriteria($this->criteria)) !== '' ? 'and (' . $c . ') ' : ''; + + $sql_query = $sql_select . ' from search_biblio as sb ' . $sql_criteria . ' order by sb.last_update desc limit ' . $this->limit . ' offset ' . $this->offset; + $sql_count = 'select count(sb.biblio_id)' . ' from search_biblio as sb ' . $sql_criteria; + + return [ + 'count' => $sql_count, + 'query' => $sql_query + ]; + } + + function buildCriteria() + { + $boolean = ''; + $sql_criteria = ''; + foreach ($this->criteria->toCQLToken($this->stop_words) as $token) { + $field = $token['f']; + + $is_phrase = isset($token['is_phrase']); + + // break the loop if we meet cql_end field + if ($field === 'cql_end') break; + + // boolean mode + if ($field == 'boolean') { + if ($token['b'] == '*') { + $boolean = 'or'; + } else { + $boolean = 'and'; + } + continue; + } else { + if ($boolean) { + $sql_criteria .= " $boolean "; + } else { + if ($token['b'] == '*') { + $sql_criteria .= " or "; + } else { + $sql_criteria .= " and "; + } + } + $bool = $token['b']; + $query = $token['q']; + if (in_array($field, array('title', 'author', 'subject', 'notes'))) { + $query = '+' . ($is_phrase ? '"' . $query . '"' : $query); + if (!$is_phrase) { + $query = preg_replace('@\s+@i', ' +', $query); + } + } + $boolean = ''; + } + + // check fields + switch ($field) { + case 'author': + if ($bool == '-') { + $sql_criteria .= " not (match (sb.author) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " (match (sb.author) against ('$query' in boolean mode))"; + } + break; + case 'subject': + if ($bool == '-') { + $sql_criteria .= " not (match (sb.topic) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " (match (sb.topic) against ('$query' in boolean mode))"; + } + break; + case 'location': + if (!$this->disable_item_data) { + if ($bool == '-') { + $sql_criteria .= " not (match (sb.location) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " (match (sb.location) against ('$query' in boolean mode))"; + } + } else { + if ($bool == '-') { + $sql_criteria .= " sb.node !='$query'"; + } else { + $sql_criteria .= " sb.node = '$query'"; + } + } + break; + case 'colltype': + if (!$this->disable_item_data) { + if ($bool == '-') { + $sql_criteria .= " not (match (sb.collection_types) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " match (sb.collection_types) against ('$query' in boolean mode)"; + } + } + break; + case 'itemcode': + if (!$this->disable_item_data) { + if ($bool == '-') { + $sql_criteria .= " not (match (sb.items) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " match (sb.items) against ('$query' in boolean mode)"; + } + } + break; + case 'callnumber': + if ($bool == '-') { + $sql_criteria .= ' biblio.call_number not LIKE \'' . $query . '%\''; + } else { + $sql_criteria .= ' sb.call_number LIKE \'' . $query . '%\''; + } + break; + case 'itemcallnumber': + if (!$this->disable_item_data) { + if ($bool == '-') { + $sql_criteria .= ' item.call_number not LIKE \'' . $query . '%\''; + } else { + $sql_criteria .= ' item.call_number LIKE \'' . $query . '%\''; + } + } + break; + case 'class': + if ($bool == '-') { + $sql_criteria .= ' sb.classification not LIKE \'' . $query . '%\''; + } else { + $sql_criteria .= ' sb.classification LIKE \'' . $query . '%\''; + } + break; + case 'isbn': + if ($bool == '-') { + $sql_criteria .= ' sb.isbn_issn not LIKE \'' . $query . '%\''; + } else { + $sql_criteria .= ' sb.isbn_issn LIKE \'' . $query . '%\''; + } + break; + case 'publisher': + if ($bool == '-') { + $sql_criteria .= " sb.publisher!='$query'"; + } else { + $sql_criteria .= " sb.publisher LIKE '$query%'"; + } + break; + case 'publishyear': + if ($bool == '-') { + $sql_criteria .= ' sb.publish_year!=\'' . $query . '\''; + } else { + $sql_criteria .= ' sb.publish_year LIKE \'' . $query . '\''; + } + break; + case 'gmd': + if ($bool == '-') { + $sql_criteria .= " sb.gmd!='$query'"; + } else { + $sql_criteria .= " sb.gmd='$query'"; + } + break; + case 'notes': + if ($bool == '-') { + $sql_criteria .= " not (match (sb.notes) against ('" . $query . "' in boolean mode))"; + } else { + $sql_criteria .= " (match (sb.notes) against ('" . $query . "' in boolean mode))"; + } + break; + case 'opengroup': + $sql_criteria .= "("; + break; + case 'closegroup': + $sql_criteria .= ")"; + break; + default: + if ($bool == '-') { + $sql_criteria .= " not (match (sb.title, sb.series_title) against ('$query' in boolean mode))"; + } else { + $sql_criteria .= " (match (sb.title, sb.series_title) against ('$query' in boolean mode))"; + } + break; + } + } + return preg_replace('@^(AND|OR|NOT)\s*|\s+(AND|OR|NOT)$@i', '', trim($sql_criteria)); + } + + function toArray() + { + // TODO: Implement toArray() method. + } + + function toJSON() + { + $jsonld = [ + '@context' => 'http://schema.org', + '@type' => 'Book', + 'total_rows' => $this->num_rows, + 'page' => $this->page, + 'records_each_page' => $this->limit, + '@graph' => [], + ]; + + $db = DB::getInstance(); + + foreach ($this->documents as $document) + { + $record = []; + $record['@id'] = 'http://' . $_SERVER['SERVER_NAME']. SWB . 'index.php?p=show_detail&id=' . $document['biblio_id']; + $record['name'] = trim($document['title']); + + $record['author'] = []; + + foreach(explode('-', $document['author']) as $author) + { + $record['author']['name'][] = trim($author); + } + + // ISBN + $record['isbn'] = $document['isbn_issn']; + + // publisher + $record['publisher'] = $document['publisher']; + + // publish date + $record['dateCreated'] = $document['publish_year']; + + // doc images + $_image = ''; + if (!empty($document['image'])) { + $_image = urlencode($document['image']); + $record['image'] = $_image; + } + + $jsonld['@graph'][] = $record; + } + + return json_encode($jsonld); + } + + function toHTML() + { + $buffer = ''; + // include biblio list html template callback + $path = SB . config('template.dir', 'template') . DS; + $path .= config('template.theme', 'default') . DS . 'biblio_list_template.php'; + include $path; + + foreach ($this->documents as $i => $document) { + $buffer .= \biblio_list_format(DB::getInstance('mysqli'), $document, $i, [ + 'keywords' => $this->criteria->keywords, + 'enable_custom_frontpage' => true, + 'custom_fields' => $this->custom_fields + ]); + } + return $buffer; + } + + function toXML() + { + $xml = new \XMLWriter(); + $xml->openMemory(); + $xml->setIndent(true); + $xml->startElement('modsCollection'); + $xml->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $xml->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $xml->writeAttribute('xmlns', 'http://www.loc.gov/mods/v3'); + $xml->writeAttribute('xmlns:slims', 'http://slims.web.id'); + $xml->writeAttribute('xsi:schemaLocation', 'http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd'); + + $xml->startElementNS('slims', 'resultInfo', null); + $xml->startElementNS('slims', 'modsResultNum', null); + $xml->text($this->num_rows); + $xml->endElement(); // -- modsResultNum + $xml->startElementNS('slims', 'modsResultPage', null); + $xml->text($this->page); + $xml->endElement(); // -- modsResultPage + $xml->startElementNS('slims', 'modsResultShowed', null); + $xml->text($this->limit); + $xml->endElement(); // -- modsResultShowed + $xml->endElement(); // -- resultInfo + + foreach ($this->documents as $document) { + $xml->startElement('mods'); + $xml->writeAttribute('version', '3.3'); + $xml->writeAttribute('ID', $document['biblio_id']); + + // parsing title + $title_main = $document['title']; + $title_sub = ''; + if (stripos($document['title'], '/') !== false) { + $title_main = trim(substr_replace($document['title'], '', stripos($document['title'], '/') + 1)); + } + if (stripos($document['title'], ':') !== false) { + $title_main = trim(substr_replace($document['title'], '', stripos($document['title'], ':') + 1)); + $title_sub = trim(substr_replace($document['title'], '', 0, stripos($document['title'], ':') + 1)); + } + if (stripos($title_sub, '/') !== false) { + $title_sub = trim(substr_replace($title_sub, '', stripos($title_sub, '/') + 1)); + } + + $xml->startElement('titleInfo'); + $xml->startElement('title'); + $xml->text($title_main); + $xml->endElement(); // -- title + if ($title_sub !== '') { + $xml->startElement('subTitle'); + $xml->text($title_sub); + $xml->endElement(); // -- subTitle + } + $xml->endElement(); // -- titleInfo + + // authors + $this->xmlAuthor($xml, $document['biblio_id']); + + $xml->startElement('typeOfResource'); + $xml->writeAttribute('collection', 'yes'); + $xml->text('mixed material'); + $xml->endElement(); // -- typeOfResource + $xml->startElement('identifier'); + $xml->writeAttribute('type', 'isbn'); + $xml->text(str_replace(array('-', ' '), '', $document['isbn_issn'])); + $xml->endElement(); // -- identifier + + $xml->startElement('originInfo'); + $xml->startElement('place'); + $xml->startElement('placeTerm'); + $xml->writeAttribute('type', 'text'); + $xml->text($document['publish_place']); + $xml->endElement(); // -- placeTerm + $xml->startElement('publisher'); + $xml->text($document['publisher']); + $xml->endElement(); // -- publisher + $xml->startElement('dateIssued'); + $xml->text($document['publish_year']); + $xml->endElement(); // -- dateIssued + $xml->endElement(); // -- place + $xml->endElement(); // -- originInfo + + // digital file + $this->xmlAttachment($xml, $document['biblio_id']); + + // images + if (!empty($document['image'])) { + $xml->startElementNS('slims', 'image', null); + $xml->text(urlencode($document['image'])); + $xml->endElement(); + } + + $xml->endElement(); // -- mods + } + + $xml->endElement(); // -- modsCollection + + return $xml->flush(); + } + + function xmlAuthor(&$xml, $biblio_id) + { + $query = DB::getInstance()->query('SELECT a.*,ba.level FROM mst_author AS a' + . ' LEFT JOIN biblio_author AS ba ON a.author_id=ba.author_id WHERE ba.biblio_id=' . $biblio_id); + while ($author = $query->fetch()) { + $xml->startElement('name'); + $xml->writeAttribute('type', config('authority_type')[$author['authority_type']] ?? ''); + $xml->writeAttribute('authority', $author['auth_list']??''); + $xml->startElement('namePart'); + $xml->text($author['author_name']); + $xml->endElement(); // -- namePart + $xml->startElement('role'); + $xml->startElement('roleTerm'); + $xml->writeAttribute('type', 'text'); + $xml->text(config('authority_level')[$author['level']] ?? ''); + $xml->endElement(); // -- roleTerm + $xml->endElement(); // -- role + $xml->endElement(); // -- name + } + } + + function xmlAttachment(&$xml, $biblio_id) + { + $query = DB::getInstance()->query('SELECT att.*, f.* FROM biblio_attachment AS att + LEFT JOIN files AS f ON att.file_id=f.file_id WHERE att.biblio_id=' . $biblio_id . ' AND att.access_type=\'public\' LIMIT 20'); + if ($query->rowCount() > 0) { + $xml->startElementNS('slims', 'digitals', null); + while ($attachment_d = $query->fetch()) { + // check member type privileges + if ($attachment_d['access_limit']) continue; + $xml->startElementNS('slims', 'digital_item', null); + $xml->writeAttribute('id', $attachment_d['file_id']); + $xml->writeAttribute('url', trim($attachment_d['file_url'])); + $xml->writeAttribute('path', $attachment_d['file_dir'] . '/' . $attachment_d['file_name']); + $xml->writeAttribute('mimetype', $attachment_d['mime_type']); + $xml->text($attachment_d['file_title']); + $xml->endElement(); // -- digital_item + } + $xml->endElement(); // -- digitals + } + } + + function toRSS() + { + // TODO: Implement toRSS() method. + } +} diff --git a/lib/Table/Blueprint.php b/lib/Table/Blueprint.php new file mode 100644 index 00000000..b9a1917e --- /dev/null +++ b/lib/Table/Blueprint.php @@ -0,0 +1,357 @@ + [], + 'rdbmsOpt' => ['engine' => '', 'charset' => '', 'collation' => ''], + 'options' => [], + ]; + + /** + * Grammar supported + * + * @var string + */ + private $rdbmsGrammar = 'Mysql'; + + /** + * Grammar class + * + * @var [type] + */ + private $grammarClass = null; + + /** + * Set grammar class for static + * call + * + * @return void + */ + private function setGrammarClass() + { + $rdbmsGrammarClass = '\SLiMS\Table\Grammar\\' . $this->rdbmsGrammar; + + if (!class_exists($rdbmsGrammarClass)) throw new RuntimeException("Error : grammar {$rdbmsGrammarClass} not found!"); + + if (is_null($this->grammarClass)) $this->grammarClass = $rdbmsGrammarClass; + } + + /** + * Get detail table data + * + * @return void + */ + public function getData() + { + return $this->data; + } + + /** + * Magic method to processing + * method call in this object or in the + * grammar + * + * @param string $method + * @param array $params + * @return void + */ + public function __call(string $method = '', array $params = []) + { + $this->setGrammarClass(); + + /** + * Column type checking + */ + if (!is_null($type = $this->grammarClass::getType($method))) + { + $columnName = $params[0]; + $constraint = isset($params[1]) ? '(' . $params[1] . ')' : ''; + + $this->data['columns'][] = trim(<<grammarClass, $method)) + { + $this->data['columns'][] = trim($this->grammarClass::$method($params[0], $params[1])); + return $this; + } + + /** + * If method not exists in Grammar, chekck in scope + */ + $scopeMethod = 'scope' . ucfirst($method); + if (method_exists($this, $scopeMethod) && !is_null($value = call_user_func_array([$this, $scopeMethod], $params))) + { + $this->data['columns'][] = $value; + return $this; + } + + return $this; + } + + /** + * Set a property for rdmsOpt + * + * @param string $key + * @param [type] $value + */ + public function __set(string $key, $value) + { + if (isset($this->data['rdbmsOpt'][$key])) + { + $this->data['rdbmsOpt'][$key] = $value; + } + } + + /** + * Default migrations table architecture + * + * @return void + */ + public static function migrationArchitecture() + { + $static = new static; + $static->engine = 'MyISAM'; + $static->autoIncrement('id'); + $static->string('filehash', 256)->nullable(); + $static->string('filepath', 256)->nullable(); + $static->string('class', 256)->nullable(); + $static->string('version', 50)->nullable(); + $static->index('class'); + $static->timestamps(); + return $static->grammarClass::create('migrations', $static->getData(), true); + } + + /** + * Compile a data with grammar compiler and created + * SQL text + * + * @param string $tableName + * @return void + */ + public function create(string $tableName) + { + if (!class_exists($this->grammarClass)) return; + + return $this->grammarClass::create($tableName, $this->getData()); + } + + /** + * Alter existing table + * + * @param string $tableName + * @return void + */ + public function alter(string $tableName) + { + if (!class_exists($this->grammarClass)) return; + + return $this->grammarClass::alter($tableName, $this->getData()); + } + + /** + * Scope for id column + * + * @return void + */ + private function scopeId() + { + return '`id` int(11) NOT NULL'; + } + + /** + * Scope for autoincrement column + * + * @param string $columnName + * @return void + */ + private function scopeAutoIncrement(string $columnName) + { + return '`' . $columnName . '` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY'; + } + + /** + * Create timestamps column + * by default created_at and updated_at as + * default column name + * + * @return void + */ + private function scopeTimestamps() + { + return '`created_at` timestamp NULL, `updated_at` timestamp DEFAULT NOW()'; + } + + /** + * Create fulltext key + * + * @param string $columnName + * @return void + */ + private function scopeFulltext(string $columnName) + { + $this->data['options'][] = 'FULLTEXT KEY `' . $columnName . '_fulltext` (`' . $columnName . '`)'; + } + + /** + * Create index key + * + * @param string $columnName + * @return void + */ + private function scopeIndex(string $columnName) + { + $this->data['options'][] = 'KEY `' . $columnName . '_index` (`' . $columnName . '`)'; + } + + /** + * Set primarykey + * + * @param string $columnName + * @return void + */ + private function scopePrimary($columnName = '') + { + if (empty($columnName) && !is_array($columnName)) + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' PRIMARY KEY'; + } + else if (is_array($columnName)) + { + + $this->data['options'][] = 'PRIMARY KEY (`' . implode('`,`', $columnName) . '`)'; + } + else + { + $this->data['options'][] = 'PRIMARY KEY (`' . $columnName . '`)'; + } + } + + /** + * Set null as default value + * + * @return void + */ + private function scopeNullable() + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' DEFAULT NULL'; + } + + /** + * Set not null as default value + * + * @return void + */ + private function scopeNotNull() + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' NOT NULL'; + } + + /** + * Set column after existsting column + * + * @param string $columnName + * @return void + */ + private function scopeAfter(string $columnName) + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' AFTER `' . $columnName . '`'; + } + + /** + * Set a columnt at first order of table + * + * @return void + */ + private function scopeFirst() + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' FIRST'; + } + + /** + * Change column attribute + * + * @return void + */ + private function scopeChange(string $newColumnName = '') + { + $lastIndexData = array_key_last($this->data['columns']); + + $perWord = explode(' ', $this->data['columns'][$lastIndexData]); // 0 as column name + $this->data['columns'][$lastIndexData] = 'CHANGE ' . $perWord[0] . ' ' . (!empty($newColumnName) ? $newColumnName : $this->data['columns'][$lastIndexData]); + } + + /** + * Add column into existing table + */ + private function scopeAdd() + { + $lastIndexData = array_key_last($this->data['columns']); + + $perWord = explode(' ', $this->data['columns'][$lastIndexData]); // 0 as column name + $this->data['columns'][$lastIndexData] = 'ADD ' . $this->data['columns'][$lastIndexData]; + } + + /** + * Delete existing column + * + * @param string $columnName + * @return void + */ + private function scopeDrop(string $columnName) + { + $lastIndexData = array_key_last($this->data['columns']); + + if (count($this->data['columns']) === 0) $lastIndexData = 0; + if (count($this->data['columns']) > 0) ++$lastIndexData; + + $this->data['columns'][$lastIndexData] = 'DROP ' . $columnName; + } + + /** + * Set default value with specific data + * + * @param string $value + * @return void + */ + private function scopeDefault(string $value) + { + $lastIndexData = array_key_last($this->data['columns']); + + $this->data['columns'][$lastIndexData] = $this->data['columns'][$lastIndexData] . ' DEFAULT \'' . $value . '\''; + } +} \ No newline at end of file diff --git a/lib/Table/Grammar/Mysql.php b/lib/Table/Grammar/Mysql.php new file mode 100644 index 00000000..ce8a19be --- /dev/null +++ b/lib/Table/Grammar/Mysql.php @@ -0,0 +1,169 @@ + 'varchar', + 'fixstring' => 'char', + 'text' => 'text', + 'json' => 'json', + 'longtext' => 'longtext', + // number + 'number' => 'int', + 'smallnumber' => 'smallint', + 'tinynumber' => 'tinyint', + 'bignumber' => 'bigint', + 'decimal' => 'decimal', + 'float' => 'float', + 'double' => 'double', + // Date + 'date' => 'date', + 'datetime' => 'datetime' + ]; + + /** + * Compiler method to generate + * 'create' query + * + * @param string $tableName + * @param array $attributes + * @param boolean $ifNotExists + * @return void + */ + public static function create(string $tableName, array $attributes, bool $ifNotExists = false) + { + extract($attributes); + + // set state + $state = $ifNotExists ? 'createItNotExists' : 'create'; + $columns = implode(',', $columns); + $options = count($options) ? ', ' . implode(',', $options) : ''; + + return self::compile($state, $tableName, $columns, $options, $rdbmsOpt); + } + + /** + * Compiler method to generate + * 'alter' query + * + * @param string $tableName + * @param array $attributes + * @param boolean $ifNotExists + * @return void + */ + public static function alter(string $tableName, array $attributes) + { + extract($attributes); + + // set state + $columns = implode(',', $columns); + $options = count($options) ? ', ' . implode(',', $options) : ''; + + return self::compile('alter', $tableName, $columns, $options, $rdbmsOpt); + } + + /** + * Main method to generate + * query attribute like state, column, + * engine etc. + * + * @param string $state + * @param string $tableName + * @param string $columns + * @param string $options + * @param array $rdbmsOpt + * @return void + */ + private static function compile(string $state, string $tableName, string $columns, string $options, array $rdbmsOpt) + { + $engineOpt = ';'; + + if (count($rdbmsOpt) > 0) + { + $optionMap = ['engine' => 'ENGINE=', 'charset' => 'CHARSET=', 'collation' => 'COLLATE=']; + $engineOpt = []; + foreach ($rdbmsOpt as $key => $value) { + if (!empty($rdbmsOpt[$key])) + { + $engineOpt[] = $optionMap[$key] . $value; + } + } + + $engineOpt = implode(' ', $engineOpt); + } + + switch ($state) { + case 'create': + $SQL = << {tipe_kolom} -> {isi bawaan} + + // storage engine + $table->engine = 'MyISAM'; + + // character set + $table->charset = 'utf8mb4'; + + // Collate + $table->collation = 'utf8mb4_unicode_ci'; + + // membuat kolom beranam id dengan fungsi ikrement + $table->autoIncrement('id'); + + // membuat kolom bernama item_code tipe varchar dengan + // lebar data 20 dan tidak nulll + $table->string('item_code', 20)->notNull(); + $table->string('title', 255)->notNull(); + + // Membuat kolom dengan tipe datetime bernama created_at + $table->datetime('created_at')->notNull(); + + // pentunjuk selengkapnya ada di lib/Table/Blueprint.php + }); +} +``` + +### Menghapus tabel +```PHP + {tipe_kolom} -> {isi bawaan} -> {pernyataan (drop,change, add)} + + // Merubah lebar data + $table->string('item_code', 50)->notNull()->change(); + + // Menghapus kolom + $table->drop('kolom_test'); + + // Menambah kolom baru + $table->string('gmd', 5)->nullable()->after('title')->add(); + }); +} +``` \ No newline at end of file diff --git a/lib/Table/Schema.php b/lib/Table/Schema.php new file mode 100644 index 00000000..8a287235 --- /dev/null +++ b/lib/Table/Schema.php @@ -0,0 +1,162 @@ +getMessage()); + } + } + + /** + * Use singleton pattern + * + * @return void + */ + public static function getInstance() + { + if (is_null(self::$instance)) self::$instance = new Schema; + + return self::$instance; + } + + /** + * Create and table schema + * with Blueprint as designer based on + * rdbms grammar + * + * @param string $tableName + * @param Closure $callBack + * @return void + */ + public static function create(string $tableName, Closure $callBack) + { + if (self::hasTable($tableName)) return; + + $bluePrint = new Blueprint; + $callBack($bluePrint); + + $static = new static; + try { + $createQuery = $bluePrint->create($tableName); + $static->verbose = $createQuery; + DB::getInstance()->query($createQuery); + } catch (Exception $e) { + die('Error : ' . $e->getMessage()); + } + + return $static; + } + + /** + * Modify existing table + * + * @param string $tableName + * @param Closure $callBack + * @return void + */ + public static function table(string $tableName, Closure $callBack) + { + if (!self::hasTable($tableName)) return "Table {$tableName} is not found!"; + + $bluePrint = new Blueprint; + $callBack($bluePrint); + + $static = new static; + try { + $alterQuery = $bluePrint->alter($tableName); + $static->verbose = $alterQuery; + DB::getInstance()->query($alterQuery); + } catch (Exception $e) { + die('Error : ' . $e->getMessage()); + } + + return $static; + } + + /** + * Drop table + * just type table name and drop it. + * + * @param string $tableName + * @return void + */ + public static function drop(string $tableName) + { + DB::getInstance()->query('DROP TABLE `' . $tableName . '`'); + } + + /** + * Emptying table + * + * @param string $tableName + * @return void + */ + public static function truncate(string $tableName) + { + DB::getInstance()->query('TRUNCATE TABLE `' . $tableName . '`'); + } + + /** + * CHeck if table is exists or not + * + * @param string $tableName + * @return boolean + */ + public static function hasTable(string $tableName):bool + { + // set database instance + self::getInstance(); + + // Create table state + $tableState = self::$connection->prepare('SELECT * FROM `TABLES` WHERE `TABLE_SCHEMA` = :database_name AND `TABLE_NAME` = :table_name'); + $tableState->execute(['database_name' => DB_NAME, 'table_name' => $tableName]); + + return (bool) $tableState->rowCount(); + } + + /** + * Check if column exists or not + * + * @param string $tableName + * @param string $columnName + * @return boolean + */ + public static function hasColumn(string $tableName, string $columnName):bool + { + // set database instance + self::getInstance(); + + // Create table state + $tableState = self::$connection->prepare('SELECT * FROM `COLUMNS` WHERE `TABLE_SCHEMA` = :database_name AND `TABLE_NAME` = :table_name AND `COLUMN_NAME` = :column_name'); + $tableState->execute(['database_name' => DB_NAME, 'table_name' => $tableName, ':column_name' => $columnName]); + + return (bool) $tableState->rowCount(); + } +} \ No newline at end of file diff --git a/lib/Table/Utils.php b/lib/Table/Utils.php new file mode 100644 index 00000000..d112cea0 --- /dev/null +++ b/lib/Table/Utils.php @@ -0,0 +1,60 @@ +migrationFile = $filePath; + } + + public static function getMigrationFilePath() + { + return self::getInstance()->migrationFile; + } + + public static function isDetailExists(string $hash) + { + $data = \SLiMS\DB::getInstance()->prepare('SELECT `id` FROM `migrations` WHERE `filehash` = :filehash'); + $data->execute(['filehash' => $hash]); + + return (bool) $data->rowCount(); + } + + public static function createMigrationDetail(string $filePath) + { + $fileDetail = explode('_', basename($filePath)); + + return [ + 'filepath' => $filePath, + 'filehash' => md5($filePath), + 'class' => isset($fileDetail[1]) ? str_replace('.php', '', $fileDetail[1]) : null, + 'version' => $fileDetail[0]??0, + 'created_at' => date('Y-m-d H:i:s') + ]; + } + + public static function getLastVersion() + { + $version = \SLiMS\DB::getInstance()->query('SELECT `version` FROM `migrations` ORDER BY `version` DESC LIMIT 1'); + + return $version->rowCount() ? intval($version->fetch(\PDO::FETCH_OBJ)->version) : 0; + } + + public function debug() + { + echo $this->verbose . PHP_EOL; + } +} \ No newline at end of file diff --git a/lib/api.inc.php b/lib/api.inc.php index c1e2c385..c6463407 100755 --- a/lib/api.inc.php +++ b/lib/api.inc.php @@ -59,6 +59,7 @@ public static function biblio_load($obj_db, $biblio_id) $s_bib .= ''; $q_bib = $obj_db->query($s_bib); if (!$obj_db->errno) { + $_return = []; while ($r_bib = $q_bib->fetch_assoc()) { $_return['id'] = $r_bib['biblio_id']; $_return['_id'] = $r_bib['biblio_id']; diff --git a/lib/autoload.php b/lib/autoload.php index 406265ef..3903766e 100644 --- a/lib/autoload.php +++ b/lib/autoload.php @@ -17,6 +17,17 @@ "Brick\\Math\\" => "/math/src/", "Ifsnop\\Mysqldump\\" => "/mysqldump-php/src/Ifsnop/Mysqldump/", "PHPMailer\\PHPMailer\\" => "/PHPMailer/src/", + "GuzzleHttp" => "/guzzlehttp/guzzle/src", + "GuzzleHttp\\Psr7\\" => "/guzzlehttp/psr7/src", + "GuzzleHttp\\Exception\\" => "/guzzle/src/", + "GuzzleHttp\Promise" => "/guzzlehttp/promises/src", + "Psr\\Http\\Message\\" => "/psr/http-message/src", + "Psr\\Http\\Client\\" => "/psr/http-client/src", + "Complex\\" => "/markbaker/comples/classes/src/", + "Matrix\\" => "/markbaker/matrix/classes/src/", + "MyCLabs\\Enum\\" => "/myclabs/php-enum/src/", + "Symfony\\Polyfill\\Mbstring\\" => "/symfony/polyfill-mbstring/", + "ZipStream\\" => "/maennchen/zipstream-php/src/" ]; foreach ($namespaces as $namespace => $classpaths) { @@ -40,5 +51,7 @@ | Load library with self autoload |-------------------------------------------------------------------------- */ -include "markbaker/complex/classes/Autoloader.php"; -include "markbaker/matrix/classes/Autoloader.php"; \ No newline at end of file +// Ezyang +include "ezyang/htmlpurifier/library/HTMLPurifier.auto.php"; +// Symfony +include "symfony/polyfill-mbstring/bootstrap.php"; \ No newline at end of file diff --git a/lib/collection/CHANGELOG.md b/lib/collection/CHANGELOG.md deleted file mode 100644 index fa5559f4..00000000 --- a/lib/collection/CHANGELOG.md +++ /dev/null @@ -1,114 +0,0 @@ -# ramsey/collection Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). - -## [Unreleased] -### Added -### Changed -### Deprecated -### Removed -### Fixed -### Security - -## [1.1.0] - 2020-08-10 - -### Fixed - -* Fixed `AbstractCollection::diff()`, `AbstractCollection::intersect()` and - `AbstractCollection::merge()` when used with Generic collections. -* Fixed `AbstractCollection::diff()` and `AbstractCollection::intersect()` - returning inconsistent results when used on collections containing objects. -* Removed warning about deprecated dependency when running `composer install` - -## [1.0.1] - 2020-01-04 - -### Fixed - -* Fixed `AbstractCollection::offsetSet()` so that it uses the provided `$offset` - when setting `$value` in the array. - -## [1.0.0] - 2018-12-31 - -### Added - -* Added support for *queue* data structures to represent collections of ordered - entities. Together with *double-ended queues* (a.k.a. *deques*), - first-in-first-out (FIFO), last-in-first-out (LIFO), and other queue and stack - behaviors may be implemented. This functionality includes interfaces - `QueueInterface` and `DoubleEndedQueueInterface` and classes `Queue` and - `DoubleEndedQueue`. -* Added support for *set* data structures, representing collections that cannot - contain any duplicated elements; includes classes `AbstractSet` and `Set`. -* Added support for *typed map* data structures to represent maps of elements - where both keys and values have specified data types; includes - `TypedMapInterface` and the classes `AbstractTypedMap` and `TypedMap`. -* Added new manipulation and analyze methods for collections: `column()`, - `first()`, `last()`, `sort()`, `filter()`, `where()`, `map()`, `diff()`, - `intersect()`, and `merge()`. See [CollectionInterface](https://github.com/ramsey/collection/blob/master/src/CollectionInterface.php) - for more information. -* Added the following new exceptions specific to the ramsey/collection library: - `CollectionMismatchException`, `InvalidArgumentException`, - `InvalidSortOrderException`, `NoSuchElementException`, `OutOfBoundsException`, - `UnsupportedOperationException`, and `ValueExtractionException`. - -### Changed - -* Minimum PHP version supported is 7.2. -* Strict types are enforced throughout. - -### Removed - -* Removed support for HHVM. - -### Security - -* Fixed possible exploit using `AbstractArray::unserialize()` - (see [#47](https://github.com/ramsey/collection/issues/47)). - -## [0.3.0] - 2016-05-23 - -### Added - -* Added `MapInterface::keys()` method to return the keys from a `MapInterface` - object. This was added to the `AbstractMap` class. - -### Removed - -* Removed `getType()` and constructor methods from `AbstractCollection`. Children - of `AbstractCollection` must now implement `getType()`, which should return a - string value that defines the data type of items for the collection. - -### Fixed - -* Improve error messages in exceptions when `Collection` and `NamedParameterMap` - items fail type checks. - -## [0.2.1] - 2016-02-22 - -### Fixed - -* Allow non-strict checking of values in typed collections. - -## [0.2.0] - 2016-02-05 - -### Added - -* Support typed collections. - -## [0.1.0] - 2015-10-27 - -### Added - -* Support generic arrays and maps. - -[Unreleased]: https://github.com/ramsey/collection/compare/1.1.0...HEAD -[1.1.0]: https://github.com/ramsey/collection/compare/1.0.1...1.1.0 -[1.0.1]: https://github.com/ramsey/collection/compare/1.0.0...1.0.1 -[1.0.0]: https://github.com/ramsey/collection/compare/0.3.0...1.0.0 -[0.3.0]: https://github.com/ramsey/collection/compare/0.2.1...0.3.0 -[0.2.1]: https://github.com/ramsey/collection/compare/0.2.0...0.2.1 -[0.2.0]: https://github.com/ramsey/collection/compare/0.1.0...0.2.0 -[0.1.0]: https://github.com/ramsey/collection/commits/0.1.0 diff --git a/lib/collection/LICENSE b/lib/collection/LICENSE index 0efc999b..ae15f590 100644 --- a/lib/collection/LICENSE +++ b/lib/collection/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2015-2020 Ben Ramsey +Copyright (c) 2015-2021 Ben Ramsey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/lib/collection/README.md b/lib/collection/README.md index 1b7897eb..9124dd77 100644 --- a/lib/collection/README.md +++ b/lib/collection/README.md @@ -1,14 +1,22 @@ -# ramsey/collection +

ramsey/collection

-[![Source Code][badge-source]][source] -[![Latest Version][badge-release]][packagist] -[![Software License][badge-license]][license] -[![PHP Version][badge-php]][php] -[![Build Status][badge-build]][build] -[![Coverage Status][badge-coverage]][coverage] -[![Total Downloads][badge-downloads]][downloads] +

+ A PHP library for representing and manipulating collections. +

-ramsey/collection is a PHP 7.2+ library for representing and manipulating collections. +

+ Source Code + Download Package + PHP Programming Language + Read License + Build Status + Codecov Code Coverage + Psalm Type Coverage +

+ +## About + +ramsey/collection is a PHP library for representing and manipulating collections. Much inspiration for this library came from the [Java Collections Framework][java]. @@ -16,7 +24,6 @@ This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). By participating in this project and its community, you are expected to uphold this code. - ## Installation Install this package as a dependency using [Composer](https://getcomposer.org). @@ -27,8 +34,6 @@ composer require ramsey/collection ## Usage -The [latest class API documentation][apidocs] is available online. - Examples of how to use this framework can be found in the [Wiki pages](https://github.com/ramsey/collection/wiki/Examples). @@ -37,7 +42,7 @@ Examples of how to use this framework can be found in the Contributions are welcome! Before contributing to this project, familiarize yourself with [CONTRIBUTING.md](CONTRIBUTING.md). -To develop this project, you will need [PHP](https://www.php.net) 7.2 or greater +To develop this project, you will need [PHP](https://www.php.net) 7.3 or greater and [Composer](https://getcomposer.org). After cloning this repository locally, execute the following commands: @@ -49,99 +54,22 @@ composer install Now, you are ready to develop! -### Tooling - -This project uses [CaptainHook](https://github.com/CaptainHookPhp/captainhook) -to validate all staged changes prior to commit. - -#### Composer Commands - -To see all the commands available in the project `br` namespace for -Composer, type: - -``` bash -composer list br -``` - -##### Composer Command Autocompletion - -If you'd like to have Composer command auto-completion, you may use -[bamarni/symfony-console-autocomplete](https://github.com/bamarni/symfony-console-autocomplete). -Install it globally with Composer: - -``` bash -composer global require bamarni/symfony-console-autocomplete -``` - -Then, in your shell configuration file — usually `~/.bash_profile` or `~/.zshrc`, -but it could be different depending on your settings — ensure that your global -Composer `bin` directory is in your `PATH`, and evaluate the -`symfony-autocomplete` command. This will look like this: - -``` bash -export PATH="$(composer config home)/vendor/bin:$PATH" -eval "$(symfony-autocomplete)" -``` +## Coordinated Disclosure -Now, you can use the `tab` key to auto-complete Composer commands: - -``` bash -composer br:[TAB][TAB] -``` - -#### Coding Standards - -This project follows a superset of [PSR-12](https://www.php-fig.org/psr/psr-12/) -coding standards, enforced by [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer). -The project PHP_CodeSniffer configuration may be found in `phpcs.xml.dist`. - -CaptainHook will run PHP_CodeSniffer before committing. It will attempt to fix -any errors it can, and it will reject the commit if there are any un-fixable -issues. Many issues can be fixed automatically and will be done so pre-commit. - -You may lint the entire codebase using PHP_CodeSniffer with the following -commands: - -``` bash -# Lint -composer br:lint - -# Lint and autofix -composer br:lint:fix -``` - -#### Static Analysis - -This project uses a combination of [PHPStan](https://github.com/phpstan/phpstan) -and [Psalm](https://github.com/vimeo/psalm) to provide static analysis of PHP -code. Configurations for these are in `phpstan.neon.dist` and `psalm.xml`, -respectively. - -CaptainHook will run PHPStan and Psalm before committing. The pre-commit hook -does not attempt to fix any static analysis errors. Instead, the commit will -fail, and you must fix the errors manually. - -You may run static analysis manually across the whole codebase with the -following command: - -``` bash -# Static analysis -composer br:analyze -``` +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. If you believe you've found a +security issue in software that is maintained in this repository, please read +[SECURITY.md][] for instructions on submitting a vulnerability report. -### Project Structure +## ramsey/collection for Enterprise -This project uses [pds/skeleton](https://github.com/php-pds/skeleton) as its -base folder structure and layout. +Available as part of the Tidelift Subscription. -| Name | Description | -| ------------------| ---------------------------------------------- | -| **bin/** | Commands and scripts for this project | -| **build/** | Cache, logs, reports, etc. for project builds | -| **docs/** | Project-specific documentation | -| **resources/** | Additional resources for this project | -| **src/** | Project library and application source code | -| **tests/** | Tests for this project | +The maintainers of ramsey/collection and thousands of other packages are working +with Tidelift to deliver commercial support and maintenance for the open source +packages you use to build your applications. Save time, reduce risk, and improve +code health, while paying the maintainers of the exact packages you use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-ramsey-collection?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Copyright and License @@ -151,20 +79,4 @@ MIT License (MIT). Please see [LICENSE](LICENSE) for more information. [java]: http://docs.oracle.com/javase/8/docs/technotes/guides/collections/index.html -[apidocs]: https://docs.benramsey.com/ramsey-collection/latest/ - -[badge-source]: http://img.shields.io/badge/source-ramsey/collection-blue.svg?style=flat-square -[badge-release]: https://img.shields.io/packagist/v/ramsey/collection.svg?style=flat-square&label=release -[badge-license]: https://img.shields.io/packagist/l/ramsey/collection.svg?style=flat-square -[badge-php]: https://img.shields.io/packagist/php-v/ramsey/collection.svg?style=flat-square -[badge-build]: https://img.shields.io/travis/ramsey/collection/master.svg?style=flat-square -[badge-coverage]: https://img.shields.io/coveralls/github/ramsey/collection/master.svg?style=flat-square -[badge-downloads]: https://img.shields.io/packagist/dt/ramsey/collection.svg?style=flat-square&colorB=mediumvioletred - -[source]: https://github.com/ramsey/collection -[packagist]: https://packagist.org/packages/ramsey/collection -[license]: https://github.com/ramsey/collection/blob/master/LICENSE -[php]: https://php.net -[build]: https://travis-ci.org/ramsey/collection -[coverage]: https://coveralls.io/r/ramsey/collection?branch=master -[downloads]: https://packagist.org/packages/ramsey/collection +[security.md]: https://github.com/ramsey/collection/blob/master/SECURITY.md diff --git a/lib/collection/SECURITY.md b/lib/collection/SECURITY.md new file mode 100644 index 00000000..b052f3b6 --- /dev/null +++ b/lib/collection/SECURITY.md @@ -0,0 +1,113 @@ + + +# Vulnerability Disclosure Policy + +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. + +## Scope + +If you believe you've found a security issue in software that is maintained in +this repository, we encourage you to notify us. + +| Version | In scope | Source code | +| :-----: | :------: | :---------- | +| latest | ✅ | https://github.com/ramsey/collection | + +## How to Submit a Report + +To submit a vulnerability report, please contact us at . +Your submission will be reviewed and validated by a member of our team. + +## Safe Harbor + +We support safe harbor for security researchers who: + +* Make a good faith effort to avoid privacy violations, destruction of data, and + interruption or degradation of our services. +* Only interact with accounts you own or with explicit permission of the account + holder. If you do encounter Personally Identifiable Information (PII) contact + us immediately, do not proceed with access, and immediately purge any local + information. +* Provide us with a reasonable amount of time to resolve vulnerabilities prior + to any disclosure to the public or a third-party. + +We will consider activities conducted consistent with this policy to constitute +"authorized" conduct and will not pursue civil action or initiate a complaint to +law enforcement. We will help to the extent we can if legal action is initiated +by a third party against you. + +Please submit a report to us before engaging in conduct that may be inconsistent +with or unaddressed by this policy. + +## Preferences + +* Please provide detailed reports with reproducible steps and a clearly defined + impact. +* Include the version number of the vulnerable package in your report +* Social engineering (e.g. phishing, vishing, smishing) is prohibited. + +## Encryption Key for security@ramsey.dev + +For increased privacy when reporting sensitive issues, you may encrypt your +messages using the following key: + +``` +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBF+Z9gEBEACbT/pIx8RR0K18t8Z2rDnmEV44YdT7HNsMdq+D6SAlx8UUb6AU +jGIbV9dgBgGNtOLU1pxloaJwL9bWIRbj+X/Qb2WNIP//Vz1Y40ox1dSpfCUrizXx +kb4p58Xml0PsB8dg3b4RDUgKwGC37ne5xmDnigyJPbiB2XJ6Xc46oPCjh86XROTK +wEBB2lY67ClBlSlvC2V9KmbTboRQkLdQDhOaUosMb99zRb0EWqDLaFkZVjY5HI7i +0pTveE6dI12NfHhTwKjZ5pUiAZQGlKA6J1dMjY2unxHZkQj5MlMfrLSyJHZxccdJ +xD94T6OTcTHt/XmMpI2AObpewZDdChDQmcYDZXGfAhFoJmbvXsmLMGXKgzKoZ/ls +RmLsQhh7+/r8E+Pn5r+A6Hh4uAc14ApyEP0ckKeIXw1C6pepHM4E8TEXVr/IA6K/ +z6jlHORixIFX7iNOnfHh+qwOgZw40D6JnBfEzjFi+T2Cy+JzN2uy7I8UnecTMGo3 +5t6astPy6xcH6kZYzFTV7XERR6LIIVyLAiMFd8kF5MbJ8N5ElRFsFHPW+82N2HDX +c60iSaTB85k6R6xd8JIKDiaKE4sSuw2wHFCKq33d/GamYezp1wO+bVUQg88efljC +2JNFyD+vl30josqhw1HcmbE1TP3DlYeIL5jQOlxCMsgai6JtTfHFM/5MYwARAQAB +tBNzZWN1cml0eUByYW1zZXkuZGV2iQJUBBMBCAA+FiEE4drPD+/ofZ570fAYq0bv +vXQCywIFAl+Z9gECGwMFCQeGH4AFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AACgkQ +q0bvvXQCywIkEA//Qcwv8MtTCy01LHZd9c7VslwhNdXQDYymcTyjcYw8x7O22m4B +3hXE6vqAplFhVxxkqXB2ef0tQuzxhPHNJgkCE4Wq4i+V6qGpaSVHQT2W6DN/NIhL +vS8OdScc6zddmIbIkSrzVVAtjwehFNEIrX3DnbbbK+Iku7vsKT5EclOluIsjlYoX +goW8IeReyDBqOe2H3hoCGw6EA0D/NYV2bJnfy53rXVIyarsXXeOLp7eNEH6Td7aW +PVSrMZJe1t+knrEGnEdrXWzlg4lCJJCtemGv+pKBUomnyISXSdqyoRCCzvQjqyig +2kRebUX8BXPW33p4OXPj9sIboUOjZwormWwqqbFMO+J4TiVCUoEoheI7emPFRcNN +QtPJrjbY1++OznBc0GRpfeUkGoU1cbRl1bnepnFIZMTDLkrVW6I1Y4q8ZVwX3BkE +N81ctFrRpHBlU36EdHvjPQmGtuiL77Qq3fWmMv7yTvK1wHJAXfEb0ZJWHZCbck3w +l0CVq0Z+UUAOM8Rp1N0N8m92xtapav0qCFU9qzf2J5qX6GRmWv+d29wPgFHzDWBm +nnrYYIA4wJLx00U6SMcVBSnNe91B+RfGY5XQhbWPjQQecOGCSDsxaFAq2MeOVJyZ +bIjLYfG9GxoLKr5R7oLRJvZI4nKKBc1Kci/crZbdiSdQhSQGlDz88F1OHeCIdQQQ +EQgAHRYhBOhdAxHd+lus86YQ57Atl5icjAcbBQJfmfdIAAoJELAtl5icjAcbFVcA +/1LqB3ZjsnXDAvvAXZVjSPqofSlpMLeRQP6IM/A9Odq0AQCZrtZc1knOMGEcjppK +Rk+sy/R0Mshy8TDuaZIRgh2Ux7kCDQRfmfYBARAAmchKzzVz7IaEq7PnZDb3szQs +T/+E9F3m39yOpV4fEB1YzObonFakXNT7Gw2tZEx0eitUMqQ/13jjfu3UdzlKl2bR +qA8LrSQRhB+PTC9A1XvwxCUYhhjGiLzJ9CZL6hBQB43qHOmE9XJPme90geLsF+gK +u39Waj1SNWzwGg+Gy1Gl5f2AJoDTxznreCuFGj+Vfaczt/hlfgqpOdb9jsmdoE7t +3DSWppA9dRHWwQSgE6J28rR4QySBcqyXS6IMykqaJn7Z26yNIaITLnHCZOSY8zhP +ha7GFsN549EOCgECbrnPt9dmI2+hQE0RO0e7SOBNsIf5sz/i7urhwuj0CbOqhjc2 +X1AEVNFCVcb6HPi/AWefdFCRu0gaWQxn5g+9nkq5slEgvzCCiKYzaBIcr8qR6Hb4 +FaOPVPxO8vndRouq57Ws8XpAwbPttioFuCqF4u9K+tK/8e2/R8QgRYJsE3Cz/Fu8 ++pZFpMnqbDEbK3DL3ss+1ed1sky+mDV8qXXeI33XW5hMFnk1JWshUjHNlQmE6ftC +U0xSTMVUtwJhzH2zDp8lEdu7qi3EsNULOl68ozDr6soWAvCbHPeTdTOnFySGCleG +/3TonsoZJs/sSPPJnxFQ1DtgQL6EbhIwa0ZwU4eKYVHZ9tjxuMX3teFzRvOrJjgs ++ywGlsIURtEckT5Y6nMAEQEAAYkCPAQYAQgAJhYhBOHazw/v6H2ee9HwGKtG7710 +AssCBQJfmfYBAhsMBQkHhh+AAAoJEKtG7710AssC8NcP/iDAcy1aZFvkA0EbZ85p +i7/+ywtE/1wF4U4/9OuLcoskqGGnl1pJNPooMOSBCfreoTB8HimT0Fln0CoaOm4Q +pScNq39JXmf4VxauqUJVARByP6zUfgYarqoaZNeuFF0S4AZJ2HhGzaQPjDz1uKVM +PE6tQSgQkFzdZ9AtRA4vElTH6yRAgmepUsOihk0b0gUtVnwtRYZ8e0Qt3ie97a73 +DxLgAgedFRUbLRYiT0vNaYbainBsLWKpN/T8odwIg/smP0Khjp/ckV60cZTdBiPR +szBTPJESMUTu0VPntc4gWwGsmhZJg/Tt/qP08XYo3VxNYBegyuWwNR66zDWvwvGH +muMv5UchuDxp6Rt3JkIO4voMT1JSjWy9p8krkPEE4V6PxAagLjdZSkt92wVLiK5x +y5gNrtPhU45YdRAKHr36OvJBJQ42CDaZ6nzrzghcIp9CZ7ANHrI+QLRM/csz+AGA +szSp6S4mc1lnxxfbOhPPpebZPn0nIAXoZnnoVKdrxBVedPQHT59ZFvKTQ9Fs7gd3 +sYNuc7tJGFGC2CxBH4ANDpOQkc5q9JJ1HSGrXU3juxIiRgfA26Q22S9c71dXjElw +Ri584QH+bL6kkYmm8xpKF6TVwhwu5xx/jBPrbWqFrtbvLNrnfPoapTihBfdIhkT6 +nmgawbBHA02D5xEqB5SU3WJu +=eJNx +-----END PGP PUBLIC KEY BLOCK----- +``` diff --git a/lib/collection/composer.json b/lib/collection/composer.json index 9e443d93..98862ee4 100644 --- a/lib/collection/composer.json +++ b/lib/collection/composer.json @@ -1,7 +1,7 @@ { "name": "ramsey/collection", "type": "library", - "description": "A PHP 7.2+ library for representing and manipulating collections.", + "description": "A PHP library for representing and manipulating collections.", "keywords": [ "array", "collection", @@ -19,25 +19,27 @@ } ], "require": { - "php": "^7.2 || ^8" + "php": "^7.3 || ^8", + "symfony/polyfill-php81": "^1.23" }, "require-dev": { "captainhook/captainhook": "^5.3", "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", "ergebnis/composer-normalize": "^2.6", - "fzaninotto/faker": "^1.5", + "fakerphp/faker": "^1.5", "hamcrest/hamcrest-php": "^2", - "jangregor/phpstan-prophecy": "^0.6", + "jangregor/phpstan-prophecy": "^0.8", "mockery/mockery": "^1.3", + "phpspec/prophecy-phpunit": "^2.0", "phpstan/extension-installer": "^1", "phpstan/phpstan": "^0.12.32", "phpstan/phpstan-mockery": "^0.12.5", "phpstan/phpstan-phpunit": "^0.12.11", - "phpunit/phpunit": "^8.5", + "phpunit/phpunit": "^8.5 || ^9", "psy/psysh": "^0.10.4", "slevomat/coding-standard": "^6.3", "squizlabs/php_codesniffer": "^3.5", - "vimeo/psalm": "^3.12.2" + "vimeo/psalm": "^4.4" }, "config": { "sort-packages": true @@ -50,7 +52,8 @@ "autoload-dev": { "psr-4": { "Ramsey\\Console\\": "resources/console/", - "Ramsey\\Collection\\Test\\": "tests/" + "Ramsey\\Collection\\Test\\": "tests/", + "Ramsey\\Test\\Generics\\": "tests/generics/" }, "files": [ "vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest.php" @@ -58,48 +61,42 @@ }, "scripts": { "post-autoload-dump": "captainhook install --ansi -f -s", - "br:analyze": [ - "@br:analyze:phpstan", - "@br:analyze:psalm" + "dev:analyze": [ + "@dev:analyze:phpstan", + "@dev:analyze:psalm" ], - "br:analyze:phpstan": "phpstan --memory-limit=1G analyse", - "br:analyze:psalm": "psalm --diff --diff-methods --config=psalm.xml", - "br:build:clean": "git clean -fX build/.", - "br:build:clear-cache": "git clean -fX build/cache/.", - "br:lint": "phpcs --cache=build/cache/phpcs.cache", - "br:lint:fix": "./bin/lint-fix.sh", - "br:repl": [ + "dev:analyze:phpstan": "phpstan --memory-limit=1G analyse", + "dev:analyze:psalm": "psalm --diff --config=psalm.xml", + "dev:build:clean": "git clean -fX build/.", + "dev:build:clear-cache": "git clean -fX build/cache/.", + "dev:lint": "phpcs --cache=build/cache/phpcs.cache", + "dev:lint:fix": "./bin/lint-fix.sh", + "dev:repl": [ "echo ; echo 'Type ./bin/repl to start the REPL.'" ], - "br:test": "phpunit", - "br:test:all": [ - "@br:lint", - "@br:analyze", - "@br:test" + "dev:test": "phpunit", + "dev:test:all": [ + "@dev:lint", + "@dev:analyze", + "@dev:test" ], - "br:test:coverage:ci": "phpunit --coverage-clover build/logs/clover.xml", - "br:test:coverage:html": "phpunit --coverage-html build/coverage", - "pre-commit": [ - "@br:lint:fix", - "@br:lint", - "@br:analyze" - ], - "test": "@br:test:all" + "dev:test:coverage:ci": "phpunit --coverage-clover build/logs/clover.xml", + "dev:test:coverage:html": "phpunit --coverage-html build/coverage", + "test": "@dev:test:all" }, "scripts-descriptions": { - "br:analyze": "Performs static analysis on the code base.", - "br:analyze:phpstan": "Runs the PHPStan static analyzer.", - "br:analyze:psalm": "Runs the Psalm static analyzer.", - "br:build:clean": "Removes everything not under version control from the build directory.", - "br:build:clear-cache": "Removes everything not under version control from build/cache/.", - "br:lint": "Checks all source code for coding standards issues.", - "br:lint:fix": "Checks source code for coding standards issues and fixes them, if possible.", - "br:repl": "Note: Use ./bin/repl to run the REPL.", - "br:test": "Runs the full unit test suite.", - "br:test:all": "Runs linting, static analysis, and unit tests.", - "br:test:coverage:ci": "Runs the unit test suite and generates a Clover coverage report.", - "br:test:coverage:html": "Runs the unit tests suite and generates an HTML coverage report.", - "pre-commit": "These commands are run as part of a Git pre-commit hook installed using captainhook/captainhook. Each command should be prepared to accept a list of space-separated staged files.", + "dev:analyze": "Performs static analysis on the code base.", + "dev:analyze:phpstan": "Runs the PHPStan static analyzer.", + "dev:analyze:psalm": "Runs the Psalm static analyzer.", + "dev:build:clean": "Removes everything not under version control from the build directory.", + "dev:build:clear-cache": "Removes everything not under version control from build/cache/.", + "dev:lint": "Checks all source code for coding standards issues.", + "dev:lint:fix": "Checks source code for coding standards issues and fixes them, if possible.", + "dev:repl": "Note: Use ./bin/repl to run the REPL.", + "dev:test": "Runs the full unit test suite.", + "dev:test:all": "Runs linting, static analysis, and unit tests.", + "dev:test:coverage:ci": "Runs the unit test suite and generates a Clover coverage report.", + "dev:test:coverage:html": "Runs the unit tests suite and generates an HTML coverage report.", "test": "Shortcut to run the full test suite." } } diff --git a/lib/collection/src/AbstractArray.php b/lib/collection/src/AbstractArray.php index f8b4be2c..d72dbe69 100644 --- a/lib/collection/src/AbstractArray.php +++ b/lib/collection/src/AbstractArray.php @@ -23,20 +23,23 @@ /** * This class provides a basic implementation of `ArrayInterface`, to minimize * the effort required to implement this interface. + * + * @template T + * @implements ArrayInterface */ abstract class AbstractArray implements ArrayInterface { /** * The items of this array. * - * @var mixed[] + * @var array */ protected $data = []; /** * Constructs a new array object. * - * @param mixed[] $data The initial items to add to this array. + * @param array $data The initial items to add to this array. */ public function __construct(array $data = []) { @@ -52,7 +55,7 @@ public function __construct(array $data = []) * * @link http://php.net/manual/en/iteratoraggregate.getiterator.php IteratorAggregate::getIterator() * - * @return ArrayIterator + * @return Traversable */ public function getIterator(): Traversable { @@ -64,7 +67,7 @@ public function getIterator(): Traversable * * @link http://php.net/manual/en/arrayaccess.offsetexists.php ArrayAccess::offsetExists() * - * @param mixed $offset The offset to check. + * @param array-key $offset The offset to check. */ public function offsetExists($offset): bool { @@ -76,11 +79,14 @@ public function offsetExists($offset): bool * * @link http://php.net/manual/en/arrayaccess.offsetget.php ArrayAccess::offsetGet() * - * @param mixed $offset The offset for which a value should be returned. + * @param array-key $offset The offset for which a value should be returned. * - * @return mixed|null the value stored at the offset, or null if the offset + * @return T|null the value stored at the offset, or null if the offset * does not exist. + * + * @psalm-suppress InvalidAttribute */ + #[\ReturnTypeWillChange] // phpcs:ignore public function offsetGet($offset) { return $this->data[$offset] ?? null; @@ -91,10 +97,11 @@ public function offsetGet($offset) * * @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet() * - * @param mixed|null $offset The offset to set. If `null`, the value may be + * @param array-key|null $offset The offset to set. If `null`, the value may be * set at a numerically-indexed offset. - * @param mixed $value The value to set at the given offset. + * @param T $value The value to set at the given offset. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function offsetSet($offset, $value): void { if ($offset === null) { @@ -109,7 +116,7 @@ public function offsetSet($offset, $value): void * * @link http://php.net/manual/en/arrayaccess.offsetunset.php ArrayAccess::offsetUnset() * - * @param mixed $offset The offset to remove from the array. + * @param array-key $offset The offset to remove from the array. */ public function offsetUnset($offset): void { @@ -119,6 +126,8 @@ public function offsetUnset($offset): void /** * Returns a serialized string representation of this array object. * + * @deprecated The Serializable interface will go away in PHP 9. + * * @link http://php.net/manual/en/serializable.serialize.php Serializable::serialize() * * @return string a PHP serialized string. @@ -128,9 +137,24 @@ public function serialize(): string return serialize($this->data); } + /** + * Returns data suitable for PHP serialization. + * + * @link https://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.serialize + * @link https://www.php.net/serialize + * + * @return array + */ + public function __serialize(): array + { + return $this->data; + } + /** * Converts a serialized string representation into an instance object. * + * @deprecated The Serializable interface will go away in PHP 9. + * * @link http://php.net/manual/en/serializable.unserialize.php Serializable::unserialize() * * @param string $serialized A PHP serialized string to unserialize. @@ -139,7 +163,20 @@ public function serialize(): string */ public function unserialize($serialized): void { - $this->data = unserialize($serialized, ['allowed_classes' => false]); + /** @var array $data */ + $data = unserialize($serialized, ['allowed_classes' => false]); + + $this->data = $data; + } + + /** + * Adds unserialized data to the object. + * + * @param array $data + */ + public function __unserialize(array $data): void + { + $this->data = $data; } /** @@ -152,27 +189,19 @@ public function count(): int return count($this->data); } - /** - * Removes all items from this array. - */ public function clear(): void { $this->data = []; } /** - * Returns a native PHP array representation of this array object. - * - * @return mixed[] + * @inheritDoc */ public function toArray(): array { return $this->data; } - /** - * Returns `true` if this array is empty. - */ public function isEmpty(): bool { return count($this->data) === 0; diff --git a/lib/collection/src/AbstractCollection.php b/lib/collection/src/AbstractCollection.php index 84e8b882..d2cd1151 100644 --- a/lib/collection/src/AbstractCollection.php +++ b/lib/collection/src/AbstractCollection.php @@ -14,11 +14,11 @@ namespace Ramsey\Collection; +use Closure; use Ramsey\Collection\Exception\CollectionMismatchException; use Ramsey\Collection\Exception\InvalidArgumentException; use Ramsey\Collection\Exception\InvalidSortOrderException; use Ramsey\Collection\Exception\OutOfBoundsException; -use Ramsey\Collection\Exception\ValueExtractionException; use Ramsey\Collection\Tool\TypeTrait; use Ramsey\Collection\Tool\ValueExtractorTrait; use Ramsey\Collection\Tool\ValueToStringTrait; @@ -32,6 +32,7 @@ use function current; use function end; use function in_array; +use function is_int; use function reset; use function sprintf; use function unserialize; @@ -40,6 +41,10 @@ /** * This class provides a basic implementation of `CollectionInterface`, to * minimize the effort required to implement this interface + * + * @template T + * @extends AbstractArray + * @implements CollectionInterface */ abstract class AbstractCollection extends AbstractArray implements CollectionInterface { @@ -48,14 +53,7 @@ abstract class AbstractCollection extends AbstractArray implements CollectionInt use ValueExtractorTrait; /** - * Ensures that this collection contains the specified element. - * - * @param mixed $element The element to add to the collection. - * - * @return bool `true` if this collection changed as a result of the call. - * - * @throws InvalidArgumentException when the element does not match the - * specified type for this collection. + * @inheritDoc */ public function add($element): bool { @@ -65,10 +63,7 @@ public function add($element): bool } /** - * Returns `true` if this collection contains the specified element. - * - * @param mixed $element The element to check whether the collection contains. - * @param bool $strict Whether to perform a strict type check on the value. + * @inheritDoc */ public function contains($element, bool $strict = true): bool { @@ -76,14 +71,7 @@ public function contains($element, bool $strict = true): bool } /** - * Sets the given value to the given offset in the array. - * - * @param mixed|null $offset The position to set the value in the array, or - * `null` to append the value to the array. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this collection. + * @inheritDoc */ public function offsetSet($offset, $value): void { @@ -102,12 +90,7 @@ public function offsetSet($offset, $value): void } /** - * Removes a single instance of the specified element from this collection, - * if it is present. - * - * @param mixed $element The element to remove from the collection. - * - * @return bool `true` if an element was removed as a result of this call. + * @inheritDoc */ public function remove($element): bool { @@ -121,31 +104,25 @@ public function remove($element): bool } /** - * Returns the values from given property or method. - * - * @param string $propertyOrMethod The property or method name to filter by. - * - * @return mixed[] - * - * @throws ValueExtractionException if property or method is not defined. + * @inheritDoc */ public function column(string $propertyOrMethod): array { $temp = []; foreach ($this->data as $item) { - $temp[] = $this->extractValue($item, $propertyOrMethod); + /** @var mixed $value */ + $value = $this->extractValue($item, $propertyOrMethod); + + /** @psalm-suppress MixedAssignment */ + $temp[] = $value; } return $temp; } /** - * Returns the first item of the collection. - * - * @return mixed - * - * @throws OutOfBoundsException when the collection is empty. + * @inheritDoc */ public function first() { @@ -155,15 +132,14 @@ public function first() reset($this->data); - return current($this->data); + /** @var T $first */ + $first = current($this->data); + + return $first; } /** - * Returns the last item of the collection. - * - * @return mixed - * - * @throws OutOfBoundsException when the collection is empty. + * @inheritDoc */ public function last() { @@ -171,27 +147,13 @@ public function last() throw new OutOfBoundsException('Can\'t determine last item. Collection is empty'); } + /** @var T $item */ $item = end($this->data); reset($this->data); return $item; } - /** - * Returns a sorted collection. - * - * {@inheritdoc} - * - * @param string $propertyOrMethod The property or method to sort by. - * @param string $order The sort order for the resulting collection (one of - * this interface's `SORT_*` constants). - * - * @return CollectionInterface - * - * @throws InvalidSortOrderException if neither "asc" nor "desc" was given - * as the order. - * @throws ValueExtractionException if property or method is not defined. - */ public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): CollectionInterface { if (!in_array($order, [self::SORT_ASC, self::SORT_DESC], true)) { @@ -200,25 +162,26 @@ public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): $collection = clone $this; - usort($collection->data, function ($a, $b) use ($propertyOrMethod, $order) { - $aValue = $this->extractValue($a, $propertyOrMethod); - $bValue = $this->extractValue($b, $propertyOrMethod); + usort( + $collection->data, + /** + * @param T $a + * @param T $b + */ + function ($a, $b) use ($propertyOrMethod, $order): int { + /** @var mixed $aValue */ + $aValue = $this->extractValue($a, $propertyOrMethod); - return ($aValue <=> $bValue) * ($order === self::SORT_DESC ? -1 : 1); - }); + /** @var mixed $bValue */ + $bValue = $this->extractValue($b, $propertyOrMethod); + + return ($aValue <=> $bValue) * ($order === self::SORT_DESC ? -1 : 1); + } + ); return $collection; } - /** - * Returns a filtered collection. - * - * {@inheritdoc} - * - * @param callable $callback A callable to use for filtering elements. - * - * @return CollectionInterface - */ public function filter(callable $callback): CollectionInterface { $collection = clone $this; @@ -228,84 +191,31 @@ public function filter(callable $callback): CollectionInterface } /** - * Returns a collection of matching items. - * * {@inheritdoc} - * - * @param string $propertyOrMethod The property or method to evaluate. - * @param mixed $value The value to match. - * - * @return CollectionInterface - * - * @throws ValueExtractionException if property or method is not defined. */ public function where(string $propertyOrMethod, $value): CollectionInterface { return $this->filter(function ($item) use ($propertyOrMethod, $value) { + /** @var mixed $accessorValue */ $accessorValue = $this->extractValue($item, $propertyOrMethod); return $accessorValue === $value; }); } - /** - * Applies a callback to each item of the collection. - * - * {@inheritdoc} - * - * @param callable $callback A callable to apply to each item of the - * collection. - * - * @return CollectionInterface - */ public function map(callable $callback): CollectionInterface { - $collection = clone $this; - array_map($callback, $collection->data); - - return $collection; + return new Collection('mixed', array_map($callback, $this->data)); } - /** - * Create a new collection with divergent items between current and given - * collection. - * - * @param CollectionInterface $other The collection to check for divergent - * items. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if the given collection is not of the - * same type. - */ public function diff(CollectionInterface $other): CollectionInterface { - if (!$other instanceof static) { - throw new CollectionMismatchException('Collection must be of type ' . static::class); - } + $this->compareCollectionTypes($other); - // When using generics (Collection.php, Set.php, etc), - // we also need to make sure that the internal types match each other - if ($other->getType() !== $this->getType()) { - throw new CollectionMismatchException('Collection items must be of type ' . $this->getType()); - } + $diffAtoB = array_udiff($this->data, $other->toArray(), $this->getComparator()); + $diffBtoA = array_udiff($other->toArray(), $this->data, $this->getComparator()); - $comparator = function ($a, $b): int { - // If the two values are object, we convert them to unique scalars. - // If the collection contains mixed values (unlikely) where some are objects - // and some are not, we leave them as they are. - // The comparator should still work and the result of $a < $b should - // be consistent but unpredictable since not documented. - if (is_object($a) && is_object($b)) { - $a = spl_object_id($a); - $b = spl_object_id($b); - } - - return $a === $b ? 0 : ($a < $b ? 1 : -1); - }; - - $diffAtoB = array_udiff($this->data, $other->data, $comparator); - $diffBtoA = array_udiff($other->data, $this->data, $comparator); + /** @var array $diff */ $diff = array_merge($diffAtoB, $diffBtoA); $collection = clone $this; @@ -314,45 +224,12 @@ public function diff(CollectionInterface $other): CollectionInterface return $collection; } - /** - * Create a new collection with intersecting item between current and given - * collection. - * - * @param CollectionInterface $other The collection to check for - * intersecting items. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if the given collection is not of the - * same type. - */ public function intersect(CollectionInterface $other): CollectionInterface { - if (!$other instanceof static) { - throw new CollectionMismatchException('Collection must be of type ' . static::class); - } + $this->compareCollectionTypes($other); - // When using generics (Collection.php, Set.php, etc), - // we also need to make sure that the internal types match each other - if ($other->getType() !== $this->getType()) { - throw new CollectionMismatchException('Collection items must be of type ' . $this->getType()); - } - - $comparator = function ($a, $b): int { - // If the two values are object, we convert them to unique scalars. - // If the collection contains mixed values (unlikely) where some are objects - // and some are not, we leave them as they are. - // The comparator should still work and the result of $a < $b should - // be consistent but unpredictable since not documented. - if (is_object($a) && is_object($b)) { - $a = spl_object_id($a); - $b = spl_object_id($b); - } - - return $a === $b ? 0 : ($a < $b ? 1 : -1); - }; - - $intersect = array_uintersect($this->data, $other->data, $comparator); + /** @var array $intersect */ + $intersect = array_uintersect($this->data, $other->toArray(), $this->getComparator()); $collection = clone $this; $collection->data = $intersect; @@ -360,18 +237,9 @@ public function intersect(CollectionInterface $other): CollectionInterface return $collection; } - /** - * Merge current items and items of given collections into a new one. - * - * @param CollectionInterface ...$collections The collections to merge. - * - * @return CollectionInterface - * - * @throws CollectionMismatchException if any of the given collections are not of the same type. - */ public function merge(CollectionInterface ...$collections): CollectionInterface { - $temp = [$this->data]; + $mergedCollection = clone $this; foreach ($collections as $index => $collection) { if (!$collection instanceof static) { @@ -388,15 +256,16 @@ public function merge(CollectionInterface ...$collections): CollectionInterface ); } - $temp[] = $collection->toArray(); + foreach ($collection as $key => $value) { + if (is_int($key)) { + $mergedCollection[] = $value; + } else { + $mergedCollection[$key] = $value; + } + } } - $merge = array_merge(...$temp); - - $collection = clone $this; - $collection->data = $merge; - - return $collection; + return $mergedCollection; } /** @@ -404,6 +273,46 @@ public function merge(CollectionInterface ...$collections): CollectionInterface */ public function unserialize($serialized): void { - $this->data = unserialize($serialized, ['allowed_classes' => [$this->getType()]]); + /** @var array $data */ + $data = unserialize($serialized, ['allowed_classes' => [$this->getType()]]); + + $this->data = $data; + } + + /** + * @param CollectionInterface $other + */ + private function compareCollectionTypes(CollectionInterface $other): void + { + if (!$other instanceof static) { + throw new CollectionMismatchException('Collection must be of type ' . static::class); + } + + // When using generics (Collection.php, Set.php, etc), + // we also need to make sure that the internal types match each other + if ($other->getType() !== $this->getType()) { + throw new CollectionMismatchException('Collection items must be of type ' . $this->getType()); + } + } + + private function getComparator(): Closure + { + return /** + * @param T $a + * @param T $b + */ + function ($a, $b): int { + // If the two values are object, we convert them to unique scalars. + // If the collection contains mixed values (unlikely) where some are objects + // and some are not, we leave them as they are. + // The comparator should still work and the result of $a < $b should + // be consistent but unpredictable since not documented. + if (is_object($a) && is_object($b)) { + $a = spl_object_id($a); + $b = spl_object_id($b); + } + + return $a === $b ? 0 : ($a < $b ? 1 : -1); + }; } } diff --git a/lib/collection/src/AbstractSet.php b/lib/collection/src/AbstractSet.php index 674fda03..1126ccb0 100644 --- a/lib/collection/src/AbstractSet.php +++ b/lib/collection/src/AbstractSet.php @@ -14,25 +14,18 @@ namespace Ramsey\Collection; -use Ramsey\Collection\Exception\InvalidArgumentException; - /** * This class contains the basic implementation of a collection that does not * allow duplicated values (a set), to minimize the effort required to implement * this specific type of collection. + * + * @template T + * @extends AbstractCollection */ abstract class AbstractSet extends AbstractCollection { /** - * Adds the specified element to this set, if it is not already present. - * - * @param mixed $element The element to add to the set. - * - * @return bool `true` if this set did not already contain the specified - * element. - * - * @throws InvalidArgumentException when the element does not match the - * specified type for this set. + * @inheritDoc */ public function add($element): bool { @@ -44,14 +37,7 @@ public function add($element): bool } /** - * Sets the given value to the given offset in this set, if it is not - * already present. - * - * @param mixed|null $offset The offset is ignored and is treated as `null`. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this set. + * @inheritDoc */ public function offsetSet($offset, $value): void { diff --git a/lib/collection/src/ArrayInterface.php b/lib/collection/src/ArrayInterface.php index 81835cc8..27af6102 100644 --- a/lib/collection/src/ArrayInterface.php +++ b/lib/collection/src/ArrayInterface.php @@ -21,6 +21,10 @@ /** * `ArrayInterface` provides traversable array functionality to data types. + * + * @template T + * @extends ArrayAccess + * @extends IteratorAggregate */ interface ArrayInterface extends ArrayAccess, @@ -36,7 +40,7 @@ public function clear(): void; /** * Returns a native PHP array representation of this array object. * - * @return mixed[] + * @return array */ public function toArray(): array; diff --git a/lib/collection/src/Collection.php b/lib/collection/src/Collection.php index e4db68df..1299c12c 100644 --- a/lib/collection/src/Collection.php +++ b/lib/collection/src/Collection.php @@ -69,6 +69,9 @@ * // the collection is a collection of My\Foo objects * } * ``` + * + * @template T + * @extends AbstractCollection */ class Collection extends AbstractCollection { @@ -88,7 +91,7 @@ class Collection extends AbstractCollection * * @param string $collectionType The type (FQCN) associated with this * collection. - * @param mixed[] $data The initial items to store in the collection. + * @param array $data The initial items to store in the collection. */ public function __construct(string $collectionType, array $data = []) { @@ -96,9 +99,6 @@ public function __construct(string $collectionType, array $data = []) parent::__construct($data); } - /** - * Returns the type associated with this collection. - */ public function getType(): string { return $this->collectionType; diff --git a/lib/collection/src/CollectionInterface.php b/lib/collection/src/CollectionInterface.php index c865fa9f..aa86feb0 100644 --- a/lib/collection/src/CollectionInterface.php +++ b/lib/collection/src/CollectionInterface.php @@ -19,6 +19,9 @@ * * Some collections allow duplicate elements and others do not. Some are ordered * and others unordered. + * + * @template T + * @extends ArrayInterface */ interface CollectionInterface extends ArrayInterface { @@ -52,18 +55,20 @@ interface CollectionInterface extends ArrayInterface * (rather than returning `false`). This preserves the invariant that a * collection always contains the specified element after this call returns. * - * @param mixed $element The element to add to the collection. + * @param T $element The element to add to the collection. * * @return bool `true` if this collection changed as a result of the call. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function add($element): bool; /** * Returns `true` if this collection contains the specified element. * - * @param mixed $element The element to check whether the collection contains. + * @param T $element The element to check whether the collection contains. * @param bool $strict Whether to perform a strict type check on the value. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function contains($element, bool $strict = true): bool; /** @@ -75,10 +80,11 @@ public function getType(): string; * Removes a single instance of the specified element from this collection, * if it is present. * - * @param mixed $element The element to remove from the collection. + * @param T $element The element to remove from the collection. * * @return bool `true` if an element was removed as a result of this call. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function remove($element): bool; /** @@ -86,21 +92,21 @@ public function remove($element): bool; * * @param string $propertyOrMethod The property or method name to filter by. * - * @return mixed[] + * @return list */ public function column(string $propertyOrMethod): array; /** * Returns the first item of the collection. * - * @return mixed + * @return T */ public function first(); /** * Returns the last item of the collection. * - * @return mixed + * @return T */ public function last(); @@ -114,7 +120,7 @@ public function last(); * @param string $order The sort order for the resulting collection (one of * this interface's `SORT_*` constants). * - * @return CollectionInterface + * @return CollectionInterface */ public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): self; @@ -128,9 +134,9 @@ public function sort(string $propertyOrMethod, string $order = self::SORT_ASC): * See the {@link http://php.net/manual/en/function.array-filter.php PHP array_filter() documentation} * for examples of how the `$callback` parameter works. * - * @param callable $callback A callable to use for filtering elements. + * @param callable(T):bool $callback A callable to use for filtering elements. * - * @return CollectionInterface + * @return CollectionInterface */ public function filter(callable $callback): self; @@ -141,25 +147,28 @@ public function filter(callable $callback): self; * a new one. * * @param string $propertyOrMethod The property or method to evaluate. - * @param mixed $value The value to match. + * @param mixed $value The value to match. * - * @return CollectionInterface + * @return CollectionInterface */ public function where(string $propertyOrMethod, $value): self; /** * Apply a given callback method on each item of the collection. * - * This will always leave the original collection untouched and will return - * a new one. + * This will always leave the original collection untouched. The new + * collection is created by mapping the callback to each item of the + * original collection. * * See the {@link http://php.net/manual/en/function.array-map.php PHP array_map() documentation} * for examples of how the `$callback` parameter works. * - * @param callable $callback A callable to apply to each item of the - * collection. + * @param callable(T):TCallbackReturn $callback A callable to apply to each + * item of the collection. + * + * @return CollectionInterface * - * @return CollectionInterface + * @template TCallbackReturn */ public function map(callable $callback): self; @@ -167,10 +176,10 @@ public function map(callable $callback): self; * Create a new collection with divergent items between current and given * collection. * - * @param CollectionInterface $other The collection to check for divergent + * @param CollectionInterface $other The collection to check for divergent * items. * - * @return CollectionInterface + * @return CollectionInterface */ public function diff(CollectionInterface $other): self; @@ -178,19 +187,19 @@ public function diff(CollectionInterface $other): self; * Create a new collection with intersecting item between current and given * collection. * - * @param CollectionInterface $other The collection to check for + * @param CollectionInterface $other The collection to check for * intersecting items. * - * @return CollectionInterface + * @return CollectionInterface */ public function intersect(CollectionInterface $other): self; /** * Merge current items and items of given collections into a new one. * - * @param CollectionInterface ...$collections The collections to merge. + * @param CollectionInterface ...$collections The collections to merge. * - * @return CollectionInterface + * @return CollectionInterface */ public function merge(CollectionInterface ...$collections): self; } diff --git a/lib/collection/src/DoubleEndedQueue.php b/lib/collection/src/DoubleEndedQueue.php index 4eb4dbea..c9c59502 100644 --- a/lib/collection/src/DoubleEndedQueue.php +++ b/lib/collection/src/DoubleEndedQueue.php @@ -20,6 +20,10 @@ /** * This class provides a basic implementation of `DoubleEndedQueueInterface`, to * minimize the effort required to implement this interface. + * + * @template T + * @extends Queue + * @implements DoubleEndedQueueInterface */ class DoubleEndedQueue extends Queue implements DoubleEndedQueueInterface { @@ -31,19 +35,7 @@ class DoubleEndedQueue extends Queue implements DoubleEndedQueueInterface private $tail = -1; /** - * Sets the given value to the given offset in the queue. - * - * Since arbitrary offsets may not be manipulated in a queue, this method - * serves only to fulfill the `ArrayAccess` interface requirements. It is - * invoked by other operations when adding values to the queue. - * - * @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet() - * - * @param mixed|null $offset The offset is ignored and is treated as `null`. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this queue. + * @inheritDoc */ public function offsetSet($offset, $value): void { @@ -60,16 +52,7 @@ public function offsetSet($offset, $value): void } /** - * Ensures that the specified element is inserted at the front of this queue. - * - * @see self::offerFirst() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if this queue changed as a result of the call. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this queue. + * @inheritDoc */ public function addFirst($element): bool { @@ -88,16 +71,7 @@ public function addFirst($element): bool } /** - * Ensures that the specified element in inserted at the end of this queue. - * - * @see Queue::add() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if this queue changed as a result of the call. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this queue. + * @inheritDoc */ public function addLast($element): bool { @@ -105,13 +79,7 @@ public function addLast($element): bool } /** - * Inserts the specified element at the front this queue. - * - * @see self::addFirst() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if the element was added to this queue, else `false`. + * @inheritDoc */ public function offerFirst($element): bool { @@ -123,14 +91,7 @@ public function offerFirst($element): bool } /** - * Inserts the specified element at the end this queue. - * - * @see self::addLast() - * @see Queue::offer() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if the element was added to this queue, else `false`. + * @inheritDoc */ public function offerLast($element): bool { @@ -138,17 +99,7 @@ public function offerLast($element): bool } /** - * Retrieves and removes the head of this queue. - * - * This method differs from `pollFirst()` only in that it throws an - * exception if this queue is empty. - * - * @see self::pollFirst() - * @see Queue::remove() - * - * @return mixed the head of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function removeFirst() { @@ -156,38 +107,21 @@ public function removeFirst() } /** - * Retrieves and removes the tail of this queue. - * - * This method differs from `pollLast()` only in that it throws an exception - * if this queue is empty. - * - * @see self::pollLast() - * - * @return mixed the tail of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function removeLast() { - if ($this->count() === 0) { + $tail = $this->pollLast(); + + if ($tail === null) { throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.'); } - $tail = $this[$this->tail]; - - unset($this[$this->tail]); - $this->tail--; - return $tail; } /** - * Retrieves and removes the head of this queue, or returns `null` if this - * queue is empty. - * - * @see self::removeFirst() - * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ public function pollFirst() { @@ -195,12 +129,7 @@ public function pollFirst() } /** - * Retrieves and removes the tail of this queue, or returns `null` if this - * queue is empty. - * - * @see self::removeLast() - * - * @return mixed|null the tail of this queue, or `null` if this queue is empty. + * @inheritDoc */ public function pollLast() { @@ -217,17 +146,7 @@ public function pollLast() } /** - * Retrieves, but does not remove, the head of this queue. - * - * This method differs from `peekFirst()` only in that it throws an - * exception if this queue is empty. - * - * @see self::peekFirst() - * @see Queue::element() - * - * @return mixed the head of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function firstElement() { @@ -235,16 +154,7 @@ public function firstElement() } /** - * Retrieves, but does not remove, the tail of this queue. - * - * This method differs from `peekLast()` only in that it throws an exception - * if this queue is empty. - * - * @see self::peekLast() - * - * @return mixed the tail of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function lastElement() { @@ -256,13 +166,7 @@ public function lastElement() } /** - * Retrieves, but does not remove, the head of this queue, or returns `null` - * if this queue is empty. - * - * @see self::firstElement() - * @see Queue::peek() - * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ public function peekFirst() { @@ -270,12 +174,7 @@ public function peekFirst() } /** - * Retrieves, but does not remove, the tail of this queue, or returns `null` - * if this queue is empty. - * - * @see self::lastElement() - * - * @return mixed|null the tail of this queue, or `null` if this queue is empty + * @inheritDoc */ public function peekLast() { diff --git a/lib/collection/src/DoubleEndedQueueInterface.php b/lib/collection/src/DoubleEndedQueueInterface.php index 6b23cf55..d7df5346 100644 --- a/lib/collection/src/DoubleEndedQueueInterface.php +++ b/lib/collection/src/DoubleEndedQueueInterface.php @@ -158,6 +158,9 @@ * ability to insert nulls. This is so because `null` is used as a special * return value by various methods to indicated that the double-ended queue is * empty. + * + * @template T + * @extends QueueInterface */ interface DoubleEndedQueueInterface extends QueueInterface { @@ -168,7 +171,7 @@ interface DoubleEndedQueueInterface extends QueueInterface * When using a capacity-restricted double-ended queue, it is generally * preferable to use the `offerFirst()` method. * - * @param mixed $element The element to add to the front of this queue. + * @param T $element The element to add to the front of this queue. * * @return bool `true` if this queue changed as a result of the call. * @@ -177,6 +180,7 @@ interface DoubleEndedQueueInterface extends QueueInterface * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function addFirst($element): bool; /** @@ -188,7 +192,7 @@ public function addFirst($element): bool; * * This method is equivalent to `add()`. * - * @param mixed $element The element to add to the end of this queue. + * @param T $element The element to add to the end of this queue. * * @return bool `true` if this queue changed as a result of the call. * @@ -197,6 +201,7 @@ public function addFirst($element): bool; * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function addLast($element): bool; /** @@ -207,10 +212,11 @@ public function addLast($element): bool; * preferable to `addFirst()`, which can fail to insert an element only by * throwing an exception. * - * @param mixed $element The element to add to the front of this queue. + * @param T $element The element to add to the front of this queue. * * @return bool `true` if the element was added to this queue, else `false`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function offerFirst($element): bool; /** @@ -221,10 +227,11 @@ public function offerFirst($element): bool; * preferable to `addLast()` which can fail to insert an element only by * throwing an exception. * - * @param mixed $element The element to add to the end of this queue. + * @param T $element The element to add to the end of this queue. * * @return bool `true` if the element was added to this queue, else `false`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function offerLast($element): bool; /** @@ -233,7 +240,7 @@ public function offerLast($element): bool; * This method differs from `pollFirst()` only in that it throws an * exception if this queue is empty. * - * @return mixed the first element in this queue. + * @return T the first element in this queue. * * @throws NoSuchElementException if this queue is empty. */ @@ -245,7 +252,7 @@ public function removeFirst(); * This method differs from `pollLast()` only in that it throws an exception * if this queue is empty. * - * @return mixed the last element in this queue. + * @return T the last element in this queue. * * @throws NoSuchElementException if this queue is empty. */ @@ -255,7 +262,7 @@ public function removeLast(); * Retrieves and removes the head of this queue, or returns `null` if this * queue is empty. * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ public function pollFirst(); @@ -263,7 +270,7 @@ public function pollFirst(); * Retrieves and removes the tail of this queue, or returns `null` if this * queue is empty. * - * @return mixed|null the tail of this queue, or `null` if this queue is empty. + * @return T|null the tail of this queue, or `null` if this queue is empty. */ public function pollLast(); @@ -273,7 +280,7 @@ public function pollLast(); * This method differs from `peekFirst()` only in that it throws an * exception if this queue is empty. * - * @return mixed the head of this queue. + * @return T the head of this queue. * * @throws NoSuchElementException if this queue is empty. */ @@ -285,7 +292,7 @@ public function firstElement(); * This method differs from `peekLast()` only in that it throws an exception * if this queue is empty. * - * @return mixed the tail of this queue. + * @return T the tail of this queue. * * @throws NoSuchElementException if this queue is empty. */ @@ -295,7 +302,7 @@ public function lastElement(); * Retrieves, but does not remove, the head of this queue, or returns `null` * if this queue is empty. * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ public function peekFirst(); @@ -303,7 +310,7 @@ public function peekFirst(); * Retrieves, but does not remove, the tail of this queue, or returns `null` * if this queue is empty. * - * @return mixed|null the tail of this queue, or `null` if this queue is empty. + * @return T|null the tail of this queue, or `null` if this queue is empty. */ public function peekLast(); } diff --git a/lib/collection/src/GenericArray.php b/lib/collection/src/GenericArray.php index 2f9ab767..2b079aa5 100644 --- a/lib/collection/src/GenericArray.php +++ b/lib/collection/src/GenericArray.php @@ -16,6 +16,8 @@ /** * `GenericArray` represents a standard array object. + * + * @extends AbstractArray */ class GenericArray extends AbstractArray { diff --git a/lib/collection/src/Map/AbstractMap.php b/lib/collection/src/Map/AbstractMap.php index 6b2e97a0..ae9f2fe6 100644 --- a/lib/collection/src/Map/AbstractMap.php +++ b/lib/collection/src/Map/AbstractMap.php @@ -24,23 +24,22 @@ /** * This class provides a basic implementation of `MapInterface`, to minimize the * effort required to implement this interface. + * + * @template T + * @extends AbstractArray + * @implements MapInterface */ abstract class AbstractMap extends AbstractArray implements MapInterface { /** - * Sets the given value to the given offset in the map. - * - * @param mixed $offset The offset to set. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException if the offset provided is `null`. + * @inheritDoc */ public function offsetSet($offset, $value): void { if ($offset === null) { throw new InvalidArgumentException( 'Map elements are key/value pairs; a key must be provided for ' - . 'value ' . $value + . 'value ' . var_export($value, true) ); } @@ -48,9 +47,7 @@ public function offsetSet($offset, $value): void } /** - * Returns `true` if this map contains a mapping for the specified key. - * - * @param mixed $key The key to check in the map. + * @inheritDoc */ public function containsKey($key): bool { @@ -58,11 +55,7 @@ public function containsKey($key): bool } /** - * Returns `true` if this map maps one or more keys to the specified value. - * - * This performs a strict type check on the value. - * - * @param mixed $value The value to check in the map. + * @inheritDoc */ public function containsValue($value): bool { @@ -70,9 +63,7 @@ public function containsValue($value): bool } /** - * Return an array of the keys contained in this map. - * - * @return mixed[] + * @inheritDoc */ public function keys(): array { @@ -80,14 +71,7 @@ public function keys(): array } /** - * Returns the value to which the specified key is mapped, `null` if this - * map contains no mapping for the key, or (optionally) `$defaultValue` if - * this map contains no mapping for the key. - * - * @param mixed $key The key to return from the map. - * @param mixed $defaultValue The default value to use if `$key` is not found. - * - * @return mixed|null the value or `null` if the key could not be found. + * @inheritDoc */ public function get($key, $defaultValue = null) { @@ -99,16 +83,7 @@ public function get($key, $defaultValue = null) } /** - * Associates the specified value with the specified key in this map. - * - * If the map previously contained a mapping for the key, the old value is - * replaced by the specified value. - * - * @param mixed $key The key to put or replace in the map. - * @param mixed $value The value to store at `$key`. - * - * @return mixed|null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ public function put($key, $value) { @@ -119,17 +94,7 @@ public function put($key, $value) } /** - * Associates the specified value with the specified key in this map only if - * it is not already set. - * - * If there is already a value associated with `$key`, this returns that - * value without replacing it. - * - * @param mixed $key The key to put in the map. - * @param mixed $value The value to store at `$key`. - * - * @return mixed|null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ public function putIfAbsent($key, $value) { @@ -143,12 +108,7 @@ public function putIfAbsent($key, $value) } /** - * Removes the mapping for a key from this map if it is present. - * - * @param mixed $key The key to remove from the map. - * - * @return mixed|null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ public function remove($key) { @@ -159,15 +119,7 @@ public function remove($key) } /** - * Removes the entry for the specified key only if it is currently mapped to - * the specified value. - * - * This performs a strict type check on the value. - * - * @param mixed $key The key to remove from the map. - * @param mixed $value The value to match. - * - * @return bool true if the value was removed. + * @inheritDoc */ public function removeIf($key, $value): bool { @@ -181,14 +133,7 @@ public function removeIf($key, $value): bool } /** - * Replaces the entry for the specified key only if it is currently mapped - * to some value. - * - * @param mixed $key The key to replace. - * @param mixed $value The value to set at `$key`. - * - * @return mixed|null the previous value associated with key, or `null` if - * there was no mapping for `$key`. + * @inheritDoc */ public function replace($key, $value) { @@ -202,16 +147,7 @@ public function replace($key, $value) } /** - * Replaces the entry for the specified key only if currently mapped to the - * specified value. - * - * This performs a strict type check on the value. - * - * @param mixed $key The key to remove from the map. - * @param mixed $oldValue The value to match. - * @param mixed $newValue The value to use as a replacement. - * - * @return bool true if the value was replaced. + * @inheritDoc */ public function replaceIf($key, $oldValue, $newValue): bool { diff --git a/lib/collection/src/Map/AbstractTypedMap.php b/lib/collection/src/Map/AbstractTypedMap.php index 80cec2e2..551d2e6c 100644 --- a/lib/collection/src/Map/AbstractTypedMap.php +++ b/lib/collection/src/Map/AbstractTypedMap.php @@ -21,6 +21,11 @@ /** * This class provides a basic implementation of `TypedMapInterface`, to * minimize the effort required to implement this interface. + * + * @template K + * @template T + * @extends AbstractMap + * @implements TypedMapInterface */ abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface { @@ -28,16 +33,22 @@ abstract class AbstractTypedMap extends AbstractMap implements TypedMapInterface use ValueToStringTrait; /** - * Sets the given value to the given offset in the map. + * @param K|null $offset + * @param T $value * - * @param mixed $offset The offset to set. - * @param mixed $value The value to set at the given offset. + * @inheritDoc * - * @throws InvalidArgumentException if the offset or value do not match the - * expected types. + * @psalm-suppress MoreSpecificImplementedParamType */ public function offsetSet($offset, $value): void { + if ($offset === null) { + throw new InvalidArgumentException( + 'Map elements are key/value pairs; a key must be provided for ' + . 'value ' . var_export($value, true) + ); + } + if ($this->checkType($this->getKeyType(), $offset) === false) { throw new InvalidArgumentException( 'Key must be of type ' . $this->getKeyType() . '; key is ' @@ -52,6 +63,7 @@ public function offsetSet($offset, $value): void ); } + /** @psalm-suppress MixedArgumentTypeCoercion */ parent::offsetSet($offset, $value); } } diff --git a/lib/collection/src/Map/AssociativeArrayMap.php b/lib/collection/src/Map/AssociativeArrayMap.php index f97e2172..79a314d9 100644 --- a/lib/collection/src/Map/AssociativeArrayMap.php +++ b/lib/collection/src/Map/AssociativeArrayMap.php @@ -16,6 +16,9 @@ /** * `AssociativeArrayMap` represents a standard associative array object. + * + * @template T + * @extends AbstractMap */ class AssociativeArrayMap extends AbstractMap { diff --git a/lib/collection/src/Map/MapInterface.php b/lib/collection/src/Map/MapInterface.php index 500bdb2d..6ed0b296 100644 --- a/lib/collection/src/Map/MapInterface.php +++ b/lib/collection/src/Map/MapInterface.php @@ -20,13 +20,16 @@ * An object that maps keys to values. * * A map cannot contain duplicate keys; each key can map to at most one value. + * + * @template T + * @extends ArrayInterface */ interface MapInterface extends ArrayInterface { /** * Returns `true` if this map contains a mapping for the specified key. * - * @param mixed $key The key to check in the map. + * @param array-key $key The key to check in the map. */ public function containsKey($key): bool; @@ -35,14 +38,15 @@ public function containsKey($key): bool; * * This performs a strict type check on the value. * - * @param mixed $value The value to check in the map. + * @param T $value The value to check in the map. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function containsValue($value): bool; /** * Return an array of the keys contained in this map. * - * @return mixed[] + * @return list */ public function keys(): array; @@ -51,11 +55,12 @@ public function keys(): array; * map contains no mapping for the key, or (optionally) `$defaultValue` if * this map contains no mapping for the key. * - * @param mixed $key The key to return from the map. - * @param mixed $defaultValue The default value to use if `$key` is not found. + * @param array-key $key The key to return from the map. + * @param T|null $defaultValue The default value to use if `$key` is not found. * - * @return mixed|null the value or `null` if the key could not be found. + * @return T|null the value or `null` if the key could not be found. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function get($key, $defaultValue = null); /** @@ -64,12 +69,13 @@ public function get($key, $defaultValue = null); * If the map previously contained a mapping for the key, the old value is * replaced by the specified value. * - * @param mixed $key The key to put or replace in the map. - * @param mixed $value The value to store at `$key`. + * @param array-key $key The key to put or replace in the map. + * @param T $value The value to store at `$key`. * - * @return mixed|null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function put($key, $value); /** @@ -79,22 +85,24 @@ public function put($key, $value); * If there is already a value associated with `$key`, this returns that * value without replacing it. * - * @param mixed $key The key to put in the map. - * @param mixed $value The value to store at `$key`. + * @param array-key $key The key to put in the map. + * @param T $value The value to store at `$key`. * - * @return mixed|null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function putIfAbsent($key, $value); /** * Removes the mapping for a key from this map if it is present. * - * @param mixed $key The key to remove from the map. + * @param array-key $key The key to remove from the map. * - * @return mixed|null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function remove($key); /** @@ -103,23 +111,25 @@ public function remove($key); * * This performs a strict type check on the value. * - * @param mixed $key The key to remove from the map. - * @param mixed $value The value to match. + * @param array-key $key The key to remove from the map. + * @param T $value The value to match. * * @return bool true if the value was removed. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function removeIf($key, $value): bool; /** * Replaces the entry for the specified key only if it is currently mapped * to some value. * - * @param mixed $key The key to replace. - * @param mixed $value The value to set at `$key`. + * @param array-key $key The key to replace. + * @param T $value The value to set at `$key`. * - * @return mixed|null the previous value associated with key, or `null` if + * @return T|null the previous value associated with key, or `null` if * there was no mapping for `$key`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function replace($key, $value); /** @@ -128,11 +138,12 @@ public function replace($key, $value); * * This performs a strict type check on the value. * - * @param mixed $key The key to remove from the map. - * @param mixed $oldValue The value to match. - * @param mixed $newValue The value to use as a replacement. + * @param array-key $key The key to remove from the map. + * @param T $oldValue The value to match. + * @param T $newValue The value to use as a replacement. * * @return bool true if the value was replaced. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function replaceIf($key, $oldValue, $newValue): bool; } diff --git a/lib/collection/src/Map/NamedParameterMap.php b/lib/collection/src/Map/NamedParameterMap.php index 7adfa0af..9926ddd8 100644 --- a/lib/collection/src/Map/NamedParameterMap.php +++ b/lib/collection/src/Map/NamedParameterMap.php @@ -25,6 +25,8 @@ /** * `NamedParameterMap` represents a mapping of values to a set of named keys * that may optionally be typed + * + * @extends AbstractMap */ class NamedParameterMap extends AbstractMap { @@ -34,15 +36,15 @@ class NamedParameterMap extends AbstractMap /** * Named parameters defined for this map. * - * @var array + * @var array */ protected $namedParameters; /** * Constructs a new `NamedParameterMap`. * - * @param array $namedParameters The named parameters defined for this map. - * @param mixed[] $data An initial set of data to set on this map. + * @param array $namedParameters The named parameters defined for this map. + * @param array $data An initial set of data to set on this map. */ public function __construct(array $namedParameters, array $data = []) { @@ -53,7 +55,7 @@ public function __construct(array $namedParameters, array $data = []) /** * Returns named parameters set for this `NamedParameterMap`. * - * @return array + * @return array */ public function getNamedParameters(): array { @@ -61,17 +63,17 @@ public function getNamedParameters(): array } /** - * Sets the given value to the given offset in the map. - * - * @param mixed $offset The offset to set. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException if the offset provided is not a - * defined named parameter, or if the value is not of the type defined - * for the given named parameter. + * @inheritDoc */ public function offsetSet($offset, $value): void { + if ($offset === null) { + throw new InvalidArgumentException( + 'Map elements are key/value pairs; a key must be provided for ' + . 'value ' . var_export($value, true) + ); + } + if (!array_key_exists($offset, $this->namedParameters)) { throw new InvalidArgumentException( 'Attempting to set value for unconfigured parameter \'' @@ -94,9 +96,9 @@ public function offsetSet($offset, $value): void * Given an array of named parameters, constructs a proper mapping of * named parameters to types. * - * @param array $namedParameters The named parameters to filter. + * @param array $namedParameters The named parameters to filter. * - * @return array + * @return array */ protected function filterNamedParameters(array $namedParameters): array { @@ -105,11 +107,11 @@ protected function filterNamedParameters(array $namedParameters): array foreach ($namedParameters as $key => $value) { if (is_int($key)) { - $names[] = (string) $value; + $names[] = $value; $types[] = 'mixed'; } else { $names[] = $key; - $types[] = (string) $value; + $types[] = $value; } } diff --git a/lib/collection/src/Map/TypedMap.php b/lib/collection/src/Map/TypedMap.php index 84d075f8..2e796377 100644 --- a/lib/collection/src/Map/TypedMap.php +++ b/lib/collection/src/Map/TypedMap.php @@ -79,6 +79,10 @@ * } * } * ``` + * + * @template K + * @template T + * @extends AbstractTypedMap */ class TypedMap extends AbstractTypedMap { @@ -97,7 +101,7 @@ class TypedMap extends AbstractTypedMap /** * The data type of values stored in this collection. * - * A map values's type is immutable once it is set. For this reason, this + * A map value's type is immutable once it is set. For this reason, this * property is set private. * * @var string data type of the map value. @@ -110,26 +114,22 @@ class TypedMap extends AbstractTypedMap * * @param string $keyType The data type of the map's keys. * @param string $valueType The data type of the map's values. - * @param mixed[] $data The initial data to set for this map. + * @param array $data The initial data to set for this map. */ public function __construct(string $keyType, string $valueType, array $data = []) { $this->keyType = $keyType; $this->valueType = $valueType; + + /** @psalm-suppress MixedArgumentTypeCoercion */ parent::__construct($data); } - /** - * Return the type used on the key. - */ public function getKeyType(): string { return $this->keyType; } - /** - * Return the type forced on the values. - */ public function getValueType(): string { return $this->valueType; diff --git a/lib/collection/src/Map/TypedMapInterface.php b/lib/collection/src/Map/TypedMapInterface.php index 54c78369..0308109c 100644 --- a/lib/collection/src/Map/TypedMapInterface.php +++ b/lib/collection/src/Map/TypedMapInterface.php @@ -17,6 +17,9 @@ /** * A `TypedMapInterface` represents a map of elements where key and value are * typed. + * + * @template T + * @extends MapInterface */ interface TypedMapInterface extends MapInterface { diff --git a/lib/collection/src/Queue.php b/lib/collection/src/Queue.php index 4f53ff5e..93e032b4 100644 --- a/lib/collection/src/Queue.php +++ b/lib/collection/src/Queue.php @@ -22,6 +22,10 @@ /** * This class provides a basic implementation of `QueueInterface`, to minimize * the effort required to implement this interface. + * + * @template T + * @extends AbstractArray + * @implements QueueInterface */ class Queue extends AbstractArray implements QueueInterface { @@ -50,7 +54,7 @@ class Queue extends AbstractArray implements QueueInterface * specified data. * * @param string $queueType The type (FQCN) associated with this queue. - * @param mixed[] $data The initial items to store in the collection. + * @param array $data The initial items to store in the collection. */ public function __construct(string $queueType, array $data = []) { @@ -59,19 +63,11 @@ public function __construct(string $queueType, array $data = []) } /** - * Sets the given value to the given offset in the queue. + * {@inheritDoc} * * Since arbitrary offsets may not be manipulated in a queue, this method * serves only to fulfill the `ArrayAccess` interface requirements. It is * invoked by other operations when adding values to the queue. - * - * @link http://php.net/manual/en/arrayaccess.offsetset.php ArrayAccess::offsetSet() - * - * @param mixed|null $offset The offset is ignored and is treated as `null`. - * @param mixed $value The value to set at the given offset. - * - * @throws InvalidArgumentException when the value does not match the - * specified type for this queue. */ public function offsetSet($offset, $value): void { @@ -86,19 +82,7 @@ public function offsetSet($offset, $value): void } /** - * Ensures that this queue contains the specified element. - * - * This method differs from `offer()` only in that it throws an exception if - * it cannot add the element to the queue. - * - * @see self::offer() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if this queue changed as a result of the call. - * - * @throws InvalidArgumentException when the element does not match the - * specified type for this queue. + * @inheritDoc */ public function add($element): bool { @@ -108,39 +92,23 @@ public function add($element): bool } /** - * Retrieves, but does not remove, the head of this queue. - * - * This method differs from `peek()` only in that it throws an exception if - * this queue is empty. - * - * @see self::peek() - * - * @return mixed the head of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function element() { - if ($this->count() === 0) { + $element = $this->peek(); + + if ($element === null) { throw new NoSuchElementException( 'Can\'t return element from Queue. Queue is empty.' ); } - return $this[$this->index]; + return $element; } /** - * Inserts the specified element into this queue. - * - * This method differs from `add()` only in that it does not throw an - * exception if it cannot add the element to the queue. - * - * @see self::add() - * - * @param mixed $element The element to add to this queue. - * - * @return bool `true` if the element was added to this queue, else `false`. + * @inheritDoc */ public function offer($element): bool { @@ -152,12 +120,7 @@ public function offer($element): bool } /** - * Retrieves, but does not remove, the head of this queue, or returns `null` - * if this queue is empty. - * - * @see self::element() - * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ public function peek() { @@ -169,12 +132,7 @@ public function peek() } /** - * Retrieves and removes the head of this queue, or returns `null` - * if this queue is empty. - * - * @see self::remove() - * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @inheritDoc */ public function poll() { @@ -191,34 +149,19 @@ public function poll() } /** - * Retrieves and removes the head of this queue. - * - * This method differs from `poll()` only in that it throws an exception if - * this queue is empty. - * - * @see self::poll() - * - * @return mixed the head of this queue. - * - * @throws NoSuchElementException if this queue is empty. + * @inheritDoc */ public function remove() { - if ($this->count() === 0) { + $head = $this->poll(); + + if ($head === null) { throw new NoSuchElementException('Can\'t return element from Queue. Queue is empty.'); } - $head = $this[$this->index]; - - unset($this[$this->index]); - $this->index++; - return $head; } - /** - * Returns the type associated with this queue. - */ public function getType(): string { return $this->queueType; diff --git a/lib/collection/src/QueueInterface.php b/lib/collection/src/QueueInterface.php index 6c7f2ac2..8c7383df 100644 --- a/lib/collection/src/QueueInterface.php +++ b/lib/collection/src/QueueInterface.php @@ -92,6 +92,9 @@ * Even in the implementations that permit it, `null` should not be inserted * into a queue, as `null` is also used as a special return value by the * `poll()` method to indicate that the queue contains no elements. + * + * @template T + * @extends ArrayInterface */ interface QueueInterface extends ArrayInterface { @@ -116,7 +119,7 @@ interface QueueInterface extends ArrayInterface * * @see self::offer() * - * @param mixed $element The element to add to this queue. + * @param T $element The element to add to this queue. * * @return bool `true` if this queue changed as a result of the call. * @@ -125,6 +128,7 @@ interface QueueInterface extends ArrayInterface * Implementations should use a more-specific exception that extends * `\RuntimeException`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function add($element): bool; /** @@ -135,7 +139,7 @@ public function add($element): bool; * * @see self::peek() * - * @return mixed the head of this queue. + * @return T the head of this queue. * * @throws NoSuchElementException if this queue is empty. */ @@ -151,10 +155,11 @@ public function element(); * * @see self::add() * - * @param mixed $element The element to add to this queue. + * @param T $element The element to add to this queue. * * @return bool `true` if the element was added to this queue, else `false`. */ + // phpcs:ignore SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint public function offer($element): bool; /** @@ -163,7 +168,7 @@ public function offer($element): bool; * * @see self::element() * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ public function peek(); @@ -173,7 +178,7 @@ public function peek(); * * @see self::remove() * - * @return mixed|null the head of this queue, or `null` if this queue is empty. + * @return T|null the head of this queue, or `null` if this queue is empty. */ public function poll(); @@ -185,7 +190,7 @@ public function poll(); * * @see self::poll() * - * @return mixed the head of this queue. + * @return T the head of this queue. * * @throws NoSuchElementException if this queue is empty. */ diff --git a/lib/collection/src/Set.php b/lib/collection/src/Set.php index 42fb66c3..6932f247 100644 --- a/lib/collection/src/Set.php +++ b/lib/collection/src/Set.php @@ -34,6 +34,9 @@ * $bar = new \My\Foo(); * $set->add($bar); // returns TRUE, $bar !== $foo * ``` + * + * @template T + * @extends AbstractSet */ class Set extends AbstractSet { @@ -51,7 +54,7 @@ class Set extends AbstractSet * specified data. * * @param string $setType The type (FQCN) associated with this set. - * @param mixed[] $data The initial items to store in the set. + * @param array $data The initial items to store in the set. */ public function __construct(string $setType, array $data = []) { @@ -59,9 +62,6 @@ public function __construct(string $setType, array $data = []) parent::__construct($data); } - /** - * Returns the type associated with this set. - */ public function getType(): string { return $this->setType; diff --git a/lib/collection/src/Tool/ValueExtractorTrait.php b/lib/collection/src/Tool/ValueExtractorTrait.php index 7bc4878d..f9be1be2 100644 --- a/lib/collection/src/Tool/ValueExtractorTrait.php +++ b/lib/collection/src/Tool/ValueExtractorTrait.php @@ -29,7 +29,7 @@ trait ValueExtractorTrait /** * Extracts the value of the given property or method from the object. * - * @param object $object The object to extract the value from. + * @param mixed $object The object to extract the value from. * @param string $propertyOrMethod The property or method for which the * value should be extracted. * @@ -37,8 +37,12 @@ trait ValueExtractorTrait * * @throws ValueExtractionException if the method or property is not defined. */ - protected function extractValue(object $object, string $propertyOrMethod) + protected function extractValue($object, string $propertyOrMethod) { + if (!is_object($object)) { + throw new ValueExtractionException('Unable to extract a value from a non-object'); + } + if (property_exists($object, $propertyOrMethod)) { return $object->$propertyOrMethod; } diff --git a/lib/collection/src/Tool/ValueToStringTrait.php b/lib/collection/src/Tool/ValueToStringTrait.php index 34a9a0a6..721ade00 100644 --- a/lib/collection/src/Tool/ValueToStringTrait.php +++ b/lib/collection/src/Tool/ValueToStringTrait.php @@ -71,7 +71,12 @@ protected function toolValueToString($value): string return '(' . get_resource_type($value) . ' resource #' . (int) $value . ')'; } - // after this line $value is an object since is not null, scalar, array or resource + // If we don't know what it is, use var_export(). + if (!is_object($value)) { + return '(' . var_export($value, true) . ')'; + } + + // From here, $value should be an object. // __toString() is implemented if (is_callable([$value, '__toString'])) { diff --git a/lib/comment.inc.php b/lib/comment.inc.php index 7ac49fbe..639271b2 100755 --- a/lib/comment.inc.php +++ b/lib/comment.inc.php @@ -34,12 +34,19 @@ function showComment($_detail_id) global $dbs; require SIMBIO.'simbio_GUI/paging/simbio_paging.inc.php'; $_list_comment = ''; + if (!is_null(config('3rd_party_comment'))) + { + // execute registered hook for 3rd party comment management + \SLiMS\Plugins::getInstance()->execute('comment_init', [&$_list_comment]); + return $_list_comment; + } $_recs_each_page = 3; $_pages_each_set = 10; $_all_recs = 0; + $_detail_id = (int)$_detail_id; if (ISSET($_GET['page']) && $_GET['page']>1) { - $page = $_GET['page']; + $page = (int)$_GET['page']; } else { $page = 1; } @@ -60,7 +67,7 @@ function showComment($_detail_id) while ($_data = $commlist->fetch_assoc()) { $_list_comment .= '
'; $_list_comment .= '
'.$_data['member_name']. __(' at ') . $_data['input_date']. __(' write'). '
'; - $_list_comment .= '
'. $_data['comment'] . '
'; + $_list_comment .= '
'. $_data['comment'] . '
'; $_list_comment .= '
'; } $_list_comment .= '
'.simbio_paging::paging($_all_recs, $_recs_each_page, $int_pages_each_set = 10, '', '_self').'
'; @@ -69,13 +76,15 @@ function showComment($_detail_id) if (ISSET($_SESSION['mid'])) { // Comment form $_forms = '
'; - $_forms .= simbio_form_element::textField('textarea','comment','','placeholder="Add your comment" class="comment-input form-control"'). '
'; + $_forms .= simbio_form_element::textField('textarea','comment','','placeholder="Add your comment" class="comment-input form-control ckeditor"'). '
'; $_forms .= ''; $_forms .= \Volnix\CSRF\CSRF::getHiddenInputString(); $_forms .= '
'; - return $_list_comment.$_forms; + // ckeditor for rich feature + $js = ''; + $js .= ""; + return $_list_comment.$_forms.$js; } else { return $_list_comment; } - } diff --git a/lib/content.inc.php b/lib/content.inc.php index 45ddeef5..e85c666c 100755 --- a/lib/content.inc.php +++ b/lib/content.inc.php @@ -1,136 +1,136 @@ - 1) { - $offset = ($page*$max_each_page)-$max_each_page; - } - - // language - $_lang = strtolower($sysconf['default_lang']); - - // query content - $_sql_content = "SELECT SQL_CALC_FOUND_ROWS * FROM content WHERE is_news=1"; - if ($search_query) { - $search_query = $obj_db->escape_string(trim($search_query)); - $_sql_content .= " AND MATCH(`content_title`, `content_desc`) AGAINST('$search_query' IN BOOLEAN MODE)"; - } - $_sql_content .= " ORDER BY `last_update` DESC"; - $_sql_content .= " LIMIT $max_each_page OFFSET $offset"; - - $_content_q = $obj_db->query($_sql_content); - // echo $_sql_content; - - // get total rows - $_total_rows = $obj_db->query('SELECT FOUND_ROWS()'); - $_total_rows_d = $_total_rows->fetch_row(); - $total = $_total_rows_d[0]; - - // get content data - while ($_content_d = $_content_q->fetch_assoc()) { - $contents[] = $_content_d; - } - - return $contents; - } - - public function get($obj_db, $str_path = '') - { - global $sysconf; - $_path = strtolower(trim($str_path)); - if (!$_path) { - return; - } - - if (preg_match('@^admin.+@i', $_path)) { - $_unauthorized = !isset($_SESSION['uid']) AND !isset($_SESSION['uname']) AND !isset($_SESSION['realname']); - if ($_unauthorized) { - return; - } - } - - // language - $_lang = strtolower($sysconf['default_lang']); - $_path_lang = $_path.'_'.$_lang; - - // check for language - $_sql_check = sprintf('SELECT COUNT(*) FROM content WHERE content_path=\'%s\'', $obj_db->escape_string($_path_lang)); - $_check_q = $obj_db->query($_sql_check); - $_check_d = $_check_q->fetch_row(); - if ($_check_d[0] > 0) { - $_path = $_path_lang; - } - - // query content - $_sql_content = sprintf('SELECT * FROM content WHERE content_path=\'%s\'', $obj_db->escape_string($_path)); - $_content_q = $obj_db->query($_sql_content); - // get content data - $_content_d = $_content_q->fetch_assoc(); - if (!isset($_content_d['content_title']) OR !isset($_content_d['content_path'])) { - return false; - } else { - $_content['Title'] = $_content_d['content_title']; - $_content['Path'] = $_content_d['content_path']; - $_content['Content'] = $_content_d['content_desc']; - // strip html - if ($this->strip_html) { - $_content['Content'] = strip_tags($_content['Content'], $this->allowed_tags); - } - - return $_content; - } - } -} + 1) { + $offset = ($page*$max_each_page)-$max_each_page; + } + + // language + $_lang = strtolower($sysconf['default_lang']); + + // query content + $_sql_content = "SELECT SQL_CALC_FOUND_ROWS * FROM content WHERE is_news=1"; + if ($search_query) { + $search_query = $obj_db->escape_string(trim($search_query)); + $_sql_content .= " AND MATCH(`content_title`, `content_desc`) AGAINST('$search_query' IN BOOLEAN MODE)"; + } + $_sql_content .= " ORDER BY `last_update` DESC"; + $_sql_content .= " LIMIT $max_each_page OFFSET $offset"; + + $_content_q = $obj_db->query($_sql_content); + // echo $_sql_content; + + // get total rows + $_total_rows = $obj_db->query('SELECT FOUND_ROWS()'); + $_total_rows_d = $_total_rows->fetch_row(); + $total = $_total_rows_d[0]; + + // get content data + while ($_content_d = $_content_q->fetch_assoc()) { + $contents[] = $_content_d; + } + + return $contents; + } + + public function get($obj_db, $str_path = '') + { + global $sysconf; + $_path = strtolower(trim($str_path)); + if (!$_path) { + return; + } + + if (preg_match('@^admin.+@i', $_path)) { + $_unauthorized = !isset($_SESSION['uid']) AND !isset($_SESSION['uname']) AND !isset($_SESSION['realname']); + if ($_unauthorized) { + return; + } + } + + // language + $_lang = strtolower($sysconf['default_lang']); + $_path_lang = $_path.'_'.$_lang; + + // check for language + $_sql_check = sprintf('SELECT COUNT(*) FROM content WHERE content_path=\'%s\'', $obj_db->escape_string($_path_lang)); + $_check_q = $obj_db->query($_sql_check); + $_check_d = $_check_q->fetch_row(); + if ($_check_d[0] > 0) { + $_path = $_path_lang; + } + + // query content + $_sql_content = sprintf('SELECT * FROM content WHERE content_path=\'%s\'', $obj_db->escape_string($_path)); + $_content_q = $obj_db->query($_sql_content); + // get content data + $_content_d = $_content_q->fetch_assoc(); + if (!isset($_content_d['content_title']) OR !isset($_content_d['content_path'])) { + return false; + } else { + $_content['Title'] = $_content_d['content_title']; + $_content['Path'] = $_content_d['content_path']; + $_content['Content'] = $_content_d['content_desc']; + // strip html + if ($this->strip_html) { + $_content['Content'] = strip_tags($_content['Content'], $this->allowed_tags); + } + + return $_content; + } + } +} diff --git a/lib/contents/default.inc.php b/lib/contents/default.inc.php old mode 100755 new mode 100644 index 8c93bd0f..ae3205c5 --- a/lib/contents/default.inc.php +++ b/lib/contents/default.inc.php @@ -1,299 +1,109 @@ getMessage()); -} - -if (isset($sysconf['enable_xml_detail']) && !$sysconf['enable_xml_detail']) { - $biblio_list->xml_detail = false; -} -if (isset($sysconf['enable_mark']) && !$sysconf['enable_mark']) { - $biblio_list->enable_mark = false; -} - -// search result info -$search_result_info = ''; + * @Created by : Waris Agung Widodo (ido.alit@gmail.com) + * @Date : 01/01/2022 12:14 + * @File name : default.inc.php + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +use SLiMS\SearchEngine\Contract; +use SLiMS\SearchEngine\Criteria; +use SLiMS\SearchEngine\DefaultEngine; // if we are in searching mode -if (isset($_GET['search']) && !empty($_GET['search'])) { - // default vars - $is_adv = false; - $keywords = ''; - $criteria = ''; - // simple search - if (isset($_GET['keywords'])) { - $keywords = trim(strip_tags(urldecode($_GET['keywords']))); - } - if ($keywords && !preg_match('@[a-z0-9_.]+=[^=]+\s+@i', $keywords.' ')) { - $criteria = 'title='.$keywords.' OR author='.$keywords.' OR subject='.$keywords; - $biblio_list->setSQLcriteria($criteria); - } else { - $biblio_list->setSQLcriteria($keywords); - } - // advanced search - $is_adv = isset($_GET['title']) || isset($_GET['author']) || isset($_GET['isbn']) - || isset($_GET['subject']) || isset($_GET['location']) - || isset($_GET['gmd']) || isset($_GET['colltype']) || isset($_GET['publisher']) || isset($_GET['callnumber']); - if ($is_adv) { - $title = ''; - if (isset($_GET['title'])) { - $title = trim(strip_tags(urldecode($_GET['title']))); - } - $author = ''; - if (isset($_GET['author'])) { - $author = trim(strip_tags(urldecode($_GET['author']))); - } - $subject = ''; - if (isset($_GET['subject'])) { - $subject = trim(strip_tags(urldecode($_GET['subject']))); - } - $isbn = ''; - if (isset($_GET['isbn'])) { - $isbn = trim(strip_tags(urldecode($_GET['isbn']))); - } - $gmd = ''; - if (isset($_GET['gmd'])) { - $gmd = trim(strip_tags(urldecode($_GET['gmd']))); - } - $colltype = ''; - if (isset($_GET['colltype'])) { - $colltype = trim(strip_tags(urldecode($_GET['colltype']))); - } - $location = ''; - if (isset($_GET['location'])) { - $location = trim(strip_tags(urldecode($_GET['location']))); - } - $publisher = ''; - if (isset($_GET['publisher'])) { - $publisher = trim(strip_tags(urldecode($_GET['publisher']))); - } - $callnumber = ''; - if (isset($_GET['callnumber'])) { - $callnumber = trim(strip_tags(urldecode($_GET['callnumber']))); - } - // don't do search if all search field is empty - if ($title || $author || $subject || $isbn || $gmd || $colltype || $location || $publisher || $callnumber !== '') { - $criteria = ''; - if ($title) { $criteria .= ' title='.$title; } - if ($author) { $criteria .= ' author='.$author; } - if ($subject) { $criteria .= ' subject='.$subject; } - if ($isbn) { $criteria .= ' isbn='.$isbn; } - if ($gmd) { $criteria .= ' gmd="'.$gmd.'"'; } - if ($colltype) { $criteria .= ' colltype="'.$colltype.'"'; } - if ($location) { $criteria .= ' location="'.$location.'"'; } - if ($publisher) { $criteria .= ' publisher="'.$publisher.'"'; } - if ($callnumber !== '') { $criteria .= ' callnumber="'.$callnumber.'"'; } - $criteria = trim($criteria); - $biblio_list->setSQLcriteria($criteria); - } - } - - // searched words - $searched_words = implode(' ', $biblio_list->words); - if ($biblio_list->words) { - $searched_words_js_array = '['; - foreach($biblio_list->words as $word) { - $searched_words_js_array .= "'$word',"; - } - $searched_words_js_array = substr_replace($searched_words_js_array, '', -1); - $searched_words_js_array .= ']'; - } - - // search result info construction - $keywords_info = ''.((strlen($keywords)>30)?substr($keywords, 0, 30).'...':$keywords).''; - $search_result_info .= '
'; - if ($is_adv) { - $search_result_info .= __('Found {biblio_list->num_rows} from your keywords').': '.$keywords_info.' '; - if ($title) { $search_result_info .= __('Title').' : '.$title.', '; } - if ($author) { $search_result_info .= __('Author').' : '.$author.', '; } - if ($subject) { $search_result_info .= __('Subject').' : '.$subject.', '; } - if ($isbn) { $search_result_info .= __('ISBN/ISSN').' : '.$isbn.', '; } - if ($gmd) { $search_result_info .= __('GMD').' : '.$gmd.', '; } - if ($colltype) { $search_result_info .= __('Collection Type').' : '.$colltype.', '; } - if ($location) { $search_result_info .= __('Location').' : '.$location.', '; } - if ($publisher) { $search_result_info .= __('Publisher').' : '.$publisher.', '; } - if ($callnumber !== '') { $search_result_info .= __('Call Number').' : '.$callnumber.', '; } - // strip last comma - $search_result_info = substr_replace($search_result_info, '', -2); - } else { - $search_result_info .= __('Found {biblio_list->num_rows} from your keywords').': '.$keywords_info.''; - } - $search_result_info .= '
'; - - // show promoted titles - if (isset($sysconf['enable_promote_titles']) && $sysconf['enable_promote_titles']) { - $biblio_list->only_promoted = true; - } - - if (!isset($_GET['resultXML']) && !isset($_GET['JSONLD']) && !isset($_GET['rss'])) { - // show the list - echo $biblio_list->getDocumentList(); - echo '
'."\n"; - } - - // set result number info - $search_result_info = str_replace('{biblio_list->num_rows}', $biblio_list->num_rows, $search_result_info); - - // count total pages - $total_pages = ceil($biblio_list->num_rows/$sysconf['opac_result_num']); - - // page number info - if (isset($_GET['page']) AND $_GET['page'] > 1) { - $page = intval($_GET['page']); - $msg = str_replace('{page}', $page, __('You currently on page {page} of {total_pages} page(s)')); //mfc - $msg = str_replace('{total_pages}', $total_pages, $msg); - $search_result_info .= '
'.$msg.'
'; - } else { - $page = 1; - } - - // query time - if (!isset($_SERVER['QUERY_STRING'])) { - $_SERVER['QUERY_STRING'] = ''; - } - $search_result_info .= '
'.__('Query took').' '.$biblio_list->query_time.' '.__('second(s) to complete').'
'; - if ($biblio_list->num_rows < 1 && $keywords != '') { - // word suggestion with enchant - if (function_exists('enchant_broker_init') && $sysconf['spellchecker_enabled']) { - $enc = enchant_broker_init(); - if (enchant_broker_dict_exists($enc,$sysconf['default_lang'])) { - $dict = enchant_broker_request_dict($enc,$sysconf['default_lang']); - } else { - $dict = enchant_broker_request_dict($enc,'en_US'); - } - $search_result_info .= '
'.__('Did you mean:').' '; - $word = strtok($keywords, " \t\n"); - $keywords_suggest = array(); - while ($word !== false) { - // check if we are inside quote - if (stripos($word, '"', 0) === true) { - $search_result_info .= preg_replace('@[a-z]@i', '', $word); - $word = str_replace('"', '', $word); - } - $wordcorrect = enchant_dict_check($dict, $word); - if (!$wordcorrect) { - $closest = null; - $wordsuggest = enchant_dict_suggest($dict, $word); - $shortest = -1; - // loop through words to find the closest with levenshtein - foreach ($wordsuggest as $wordsg) { - $lev = levenshtein($word, $wordsg); - if ($lev == 0) { - $closest = $wordsg; - $shortest = 0; - break; - } - - if ($lev <= $shortest || $shortest < 0) { - // set the closest match, and shortest distance - $closest = $wordsg; - $shortest = $lev; - } - } - - $keywords_suggest[] = ''.$closest.''; - $keywords_suggest_plain[] = $closest; +if (isset($_GET['search'])) { + // required library + require SIMBIO . 'simbio_GUI/paging/simbio_paging.inc.php'; + require LIB . 'biblio_list_model.inc.php'; + + // initialize variable + $keywords = ''; + $search_result_info = ''; + + // get engine name from setting + $search_engine = config('search_engine', DefaultEngine::class); + + // starting engine + $engine = new $search_engine; + + // make sure the engine running is the correct engine + if ($engine instanceof Contract) { + // opac limit result + $engine->setLimit(config('opac_result_num', 10)); + + // initialize criteria + $criteria = new Criteria; + $searched_fields = array_intersect($engine->searchable_fields, array_keys($_GET)); + if (!empty($searched_fields)) { + // get criteria from advanced search + foreach ($searched_fields as $field) { + $value = trim(strip_tags(urldecode($_GET[$field]))); + if ($value !== '' && $value !== '0') $criteria->and($field, $value); + } + $keywords = $criteria->getQueries(); } else { - $keywords_suggest[] = ''.$word.''; - $keywords_suggest_plain[] = $word; - } - $word = strtok(" \t\n"); - } - $keywords_suggest_plain_str = implode(' ', $keywords_suggest_plain); - $search_result_info .= ''; - $search_result_info .= implode(' ', $keywords_suggest); - $search_result_info .= '?
'; - enchant_broker_free_dict($dict); - } - } - - if (isset($biblio_list) && isset($sysconf['enable_xml_result']) && $sysconf['enable_xml_result']) { - $search_result_info .= '
'; - $search_result_info .= 'XML Result'; - $search_result_info .= 'JSON Result'; - $search_result_info .= '
'; - } -} - -if (isset($_GET['JSONLD']) && $sysconf['jsonld_result']) { - // get document list but don't output the result - $biblio_list->getDocumentList(false); - if ($biblio_list->num_rows > 0) { - // send http header - header('Content-Type: application/ld+json'); - header('Content-disposition: attachment; filename=biblio-opac.json'); - echo $biblio_list->JSONLDresult(); - } - exit(); -} -// check if we are on xml resultset mode -if ( (isset($_GET['rss']) || isset($_GET['resultXML'])) && $sysconf['enable_xml_result']) { - // get document list but don't output the result - $biblio_list->getDocumentList(false); - if ($biblio_list->num_rows > 0) { - // send http header - header('Content-Type: text/xml'); - echo ''."\n"; - if (isset($_GET['rss'])) { - echo $biblio_list->RSSresult(); - } else { - echo $biblio_list->XMLresult(); + // get criteria from simple search + $keywords = trim(strip_tags(urldecode($_GET['keywords'] ?? ''))); + if ($keywords !== '') $criteria->keywords = $keywords; + } + + // get records base on criteria + $engine->setCriteria($criteria); + $engine->getDocuments(); + + // create output + // check if we are on json-ld result set mode + if (isset($_GET['JSONLD']) && config('jsonld_result')) { + // send http header + header('Content-Type: application/ld+json'); + header('Content-disposition: attachment; filename=biblio-opac.json'); + echo $engine->toJSON(); + exit(); + } else + // check if we are on xml result set mode + if ((isset($_GET['rss']) || isset($_GET['resultXML'])) && config('enable_xml_result')) { + // send http header + header('Content-Type: text/xml'); + echo '' . "\n"; + if (isset($_GET['rss'])) { + echo $engine->toRSS(); + } else { + echo $engine->toXML(); + } + exit(); + } else { + // default to HTML mode + // generate search result info + $keywords_info = '' . ((strlen($keywords) > 30) ? substr($keywords, 0, 30) . '...' : $keywords) . ''; + $search_result_info .= '
'; + $search_result_info .= __('Found {biblio_list->num_rows} from your keywords') . ': ' . $keywords_info . ''; + $search_result_info .= '
'; + $search_result_info = str_replace('{biblio_list->num_rows}', $engine->getNumRows(), $search_result_info); + $search_result_info .= '
' . __('Query took') . ' ' . $engine->query_time . ' ' . __('second(s) to complete') . '
'; + $search_result_info .= '
'; + $search_result_info .= 'XML Result'; + $search_result_info .= 'JSON Result'; + $search_result_info .= '
'; + + // pagination + $paging = simbio_paging::paging($engine->getNumRows(), $engine->getLimit(), '5'); + if ($paging) echo '
' . $paging . '
'; + echo '
' . $engine->toHTML() . '
'; + if ($paging) echo '
' . $paging . '
'; + } } - } - exit(); -} +} \ No newline at end of file diff --git a/lib/contents/error.inc.php b/lib/contents/error.inc.php index f5cf7c52..1afb3894 100755 --- a/lib/contents/error.inc.php +++ b/lib/contents/error.inc.php @@ -30,6 +30,7 @@ $errmsg = NULL; if (isset($_GET['errnum'])) { if ($_GET['errnum'] === '601') { + $errnum = FALSE; $errmsg = ''; } else { $errnum = FALSE; diff --git a/lib/contents/fstream.inc.php b/lib/contents/fstream.inc.php index b2046f3e..eb5733cc 100755 --- a/lib/contents/fstream.inc.php +++ b/lib/contents/fstream.inc.php @@ -18,6 +18,8 @@ * */ +use Ramsey\Uuid\Uuid; + // be sure that this file not accessed directly if (!defined('INDEX_AUTH')) { die("can not access this file directly"); @@ -25,6 +27,11 @@ die("can not access this file directly"); } +if (isset($_POST['init'])) { + echo base64_encode($_SESSION[$_POST['init']].$_POST['init']) ?? ''; + exit; +} + /* File Viewer */ // get file ID @@ -66,6 +73,9 @@ if ($file_d['mime_type'] == 'application/pdf') { if ($sysconf['pdf']['viewer'] == 'pdfjs') { $file_loc_url = SWB . 'index.php?p=fstream-pdf&fid=' . $fileID . '&bid=' . $biblioID; + $uuid = Uuid::uuid4()->toString(); + $_SESSION[$uuid] = base64_encode($file_d['file_key']??''); + $loader_init = $uuid; \SLiMS\Plugins::getInstance()->execute('fstream_pdf_before_download', ['data' => array('fileID' => $fileID, 'memberID' => $memberID, 'userID' => $userID, 'biblioID' => $biblioID, 'file_d' => $file_d)]); if (utility::isMobileBrowser()) { diff --git a/lib/contents/login.inc.php b/lib/contents/login.inc.php index 6dfd6b90..572b8c81 100755 --- a/lib/contents/login.inc.php +++ b/lib/contents/login.inc.php @@ -140,7 +140,7 @@ // message $msg = ''; simbio_security::destroySessionCookie($msg, COOKIES_NAME, SWB.'admin', false); } diff --git a/lib/contents/member.inc.php b/lib/contents/member.inc.php index ae381a27..83507db1 100644 --- a/lib/contents/member.inc.php +++ b/lib/contents/member.inc.php @@ -119,7 +119,7 @@ if ($logon->valid($dbs)) { // write log utility::writeLogs($dbs, 'member', $username, 'Login', sprintf(__('Login success for member %s from address %s'),$username,$_SERVER['REMOTE_ADDR'])); - if (isset($_GET['destination'])) { + if (isset($_GET['destination']) && filter_var($_GET['destination'], FILTER_VALIDATE_URL)) { header("location:" . $_GET['destination']); } else { header('Location: index.php?p=member'); @@ -209,7 +209,12 @@ if ($is_member_login) : - $member_image = $_SESSION['m_image'] && file_exists(IMGBS . 'persons/' . $_SESSION['m_image']) ? $_SESSION['m_image'] : 'person.png'; + if (filter_var($_SESSION['m_image'], FILTER_VALIDATE_URL)) { + $member_image_url = $_SESSION['m_image']; + } else { + $member_image = $_SESSION['m_image'] && file_exists(IMGBS . 'persons/' . $_SESSION['m_image']) ? $_SESSION['m_image'] : 'person.png'; + $member_image_url = './images/persons/' . $member_image; + } // require file require SIMBIO . 'simbio_GUI/table/simbio_table.inc.php'; @@ -706,7 +711,7 @@ function _isAlreadyReserved($dbs, $biblio_id)
- member photo + member photo
@@ -902,7 +907,7 @@ class="fas fa-sign-out-alt mr-2"> ?>
-
+
diff --git a/lib/contents/show_detail.inc.php b/lib/contents/show_detail.inc.php index 0a2477d5..cc3a9c65 100755 --- a/lib/contents/show_detail.inc.php +++ b/lib/contents/show_detail.inc.php @@ -60,6 +60,15 @@ header('Content-Type: application/ld+json'); echo $output; exit(); +} else if (isset($_GET['MARC']) AND !empty($_GET['MARC'])) { + // filter the ID + $detail_id = intval($_GET['id']); + include MDLBS . 'bibliography/File/MARC.php'; + $biblio = new Biblio($dbs, null); + header('Content-type: application/marc'); + header('Content-disposition: attachment; filename=biblio-detail-' . $detail_id . '.mrc'); + echo $biblio->marc_export($detail_id); + exit; } else { // filter the ID $detail_id = intval($_GET['id']); @@ -77,7 +86,7 @@ exit(); } require SIMBIO.'simbio_DB/simbio_dbop.inc.php'; - $data['comment'] = trim(strip_tags($_POST['comment'])); + $data['comment'] = trim(strip_tags($_POST['comment'], ['p','em','ol','ul','li','strong'])); $data['biblio_id'] = $detail_id; $data['member_id'] = $_SESSION['mid']; @@ -89,8 +98,10 @@ $sql_op = new simbio_dbop($dbs); $insert = $sql_op->insert('comment', $data); if ($insert) { - utility::jsAlert(__('Thank you for your comment.')); - } else { utility::jsAlert(__('FAILED to strore you comment. Please Contact System Administrator')."\nDEBUG : ".$sql_op->error); } + utility::jsToastr(__('Success'), __('Thank you for your comment.'), 'success'); + } else { + utility::jsToastr(__('Error'), __('FAILED to store you comment. Please Contact System Administrator') . (ENVIRONMENT === 'development' ? $sql_op->error : ''), 'error'); + } } if (isset($_GET['keywords'])) { diff --git a/lib/contents/visitor.inc.php b/lib/contents/visitor.inc.php index 04153b9f..a30a5825 100755 --- a/lib/contents/visitor.inc.php +++ b/lib/contents/visitor.inc.php @@ -116,6 +116,8 @@ function setCounter($str_member_ID) { $_checkin_date = date('Y-m-d H:i:s'); $_checkin_sql = "INSERT INTO visitor_count (member_id, member_name, institution, checkin_date) VALUES ('$member_id', '$member_name', '$_institution', '$_checkin_date')"; + SLiMS\Plugins::getInstance()->execute('MEMBER_ON_VISIT', ['data' => $_d]); + // limitation if ($sysconf['enable_visitor_limitation']) { $already_checkin = checkVisit($member_id, true); @@ -138,6 +140,9 @@ function setCounter($str_member_ID) { return INSTITUTION_EMPTY; } else { $_checkin_sql = "INSERT INTO visitor_count (member_name, institution, checkin_date) VALUES ('$member_name', '$_institution', '$_checkin_date')"; + + SLiMS\Plugins::getInstance()->execute('NON_MEMBER_ON_VISIT', ['data' => ['member_name' => $member_name, 'institution' => $_institution]]); + // limitation if ($sysconf['enable_visitor_limitation']) { $already_checkin = checkVisit($member_name, false); @@ -158,17 +163,20 @@ function setCounter($str_member_ID) { $memberID = trim($_POST['memberID']); $counter = setCounter($memberID); if ($counter === true) { - echo $member_name . __(', thank you for inserting your data to our visitor log'); + $message = $member_name . __(', thank you for inserting your data to our visitor log'); if ($expire) { - echo '
'.__('Your membership already EXPIRED, please renew/extend your membership immediately').'
'; + $message = '
'.__('Your membership already EXPIRED, please renew/extend your membership immediately').'
'; } } else if ($counter === ALREADY_CHECKIN) { - echo __('Welcome back').' '.$member_name.'.'; + $message = __('Welcome back').' '.$member_name.'.'; } else if ($counter === INSTITUTION_EMPTY) { - echo __('Sorry, Please fill institution field if you are not library member'); + $message = __('Sorry, Please fill institution field if you are not library member'); } else { - echo __('Error inserting counter data to database!'); + $message = __('Error inserting counter data to database!'); } + + header('Content-Type: application/json'); + echo json_encode(['message' => $message, 'image' => $photo]); exit(); } @@ -190,6 +198,7 @@ function setCounter($str_member_ID) { $('#memberID').focus(); var visitorCounterForm = $('#visitorCounterForm'); var defaultMsg = $('#counterInfo').html(); + var defaultImg = 'photo.png'; // register event visitorCounterForm.on('submit', function(e) { e.preventDefault(); @@ -212,15 +221,16 @@ function setCounter($str_member_ID) { data: formData, cache: false, success: function(respond) { - $('#counterInfo').html(respond); - $('#text_voice').val(success_text + respond); + $('#counterInfo').html(respond.message); + $('#text_voice').val(success_text + respond.message); // reset counter setTimeout(function() { $('#speak').trigger('click'); - $('#visitorCounterPhoto').attr('src', './images/persons/photo.png'); + $('#visitorCounterPhoto').attr('src', `./images/persons/${respond.image}`); $('#counterInfo').html(defaultMsg); visitorCounterForm.enableForm().find('input[type=text]').val(''); $('#memberID').focus(); + setTimeout(() => { $('#visitorCounterPhoto').attr('src', `./images/persons/${defaultImg}`); }, 8000); }, 1000); }, complete: function() { @@ -251,8 +261,8 @@ function setCounter($str_member_ID) { message['volume'] = 1; message['rate'] = 1; message['pitch'] = 1; - message['lang'] = ''; - message['voice'] = voices[1]; + message['lang'] = ''; + message['voice'] = null; speechSynthesis.cancel(); speechSynthesis.speak(message); }); diff --git a/lib/detail.inc.php b/lib/detail.inc.php index 68c9d353..80bd9526 100755 --- a/lib/detail.inc.php +++ b/lib/detail.inc.php @@ -131,11 +131,18 @@ public function getAttachments() { return false; } foreach ($this->record_detail['attachments'] as $attachment_d) { - - if (!is_null($attachment_d['access_limit']) && !utility::isMemberLogin()) { + // Restricted attachment check + if (!is_null($attachment_d['access_limit'])) { + // need member login access + if (!utility::isMemberLogin()) { $_output .= '
  • '.__('Please login to see this attachment').'
  • '; continue; - } + // member type access check + } else if (utility::isMemberLogin() && !in_array($_SESSION['m_member_type_id'], unserialize($attachment_d['access_limit']))) { + $_output .= '
  • '. __('You have no authorization to download this file.') . '
  • '; + continue; + } + } if ($attachment_d['mime_type'] == 'application/pdf') { $_output .= '
  • '.$attachment_d['file_title'].''; @@ -245,7 +252,7 @@ public function getItemCopy() { } else if ($copy_d['no_loan']) { $_output .= ''.__('Available but not for loan').' - '.$copy_d['item_status_name'].''; } else { - $_output .= ''.__('Available').(trim($copy_d['item_status_name'])?' - '.$copy_d['item_status_name']:'').''; + $_output .= ''.__('Available').(trim($copy_d['item_status_name']??'')?' - '.$copy_d['item_status_name']:'').''; } $loan_stat_q->free_result(); $_output .= ''; @@ -385,7 +392,7 @@ protected function htmlOutput() foreach ($this->record_detail as $idx => $data) { if ($idx == 'notes') { - $data = nl2br($data); + $data = nl2br($data??''); } else { if (is_string($data)) { $data = trim(strip_tags($data)); @@ -536,7 +543,7 @@ public function MODSoutput() */ // $xml->startElement('name'); $xml->writeAttribute('type', $sysconf['authority_type'][$_auth_d['authority_type']]); $xml->writeAttribute('authority', $_auth_d['auth_list']); - $xml->startElement('name'); $xml->writeAttribute('type', $_auth_d['authority_type']); $xml->writeAttribute('authority', $_auth_d['auth_list']); + $xml->startElement('name'); $xml->writeAttribute('type', $_auth_d['authority_type']); $xml->writeAttribute('authority', $_auth_d['auth_list']??''); $xml->startElement('namePart'); $this->xmlWrite($xml, $_auth_d['author_name']); $xml->endElement(); $xml->startElement('role'); $xml->startElement('roleTerm'); $xml->writeAttribute('type', 'text'); @@ -631,7 +638,7 @@ public function MODSoutput() $_xml_output .= '<'.$_subject_type.'>'; $_xml_output .= ''."\n"; */ - $xml->startElement('subject'); $xml->writeAttribute('authority', $_topic_d['auth_list']); + $xml->startElement('subject'); $xml->writeAttribute('authority', $_topic_d['auth_list']??''); $xml->startElement($_subject_type); $this->xmlWrite($xml, $_topic_d['topic']); $xml->endElement(); $xml->endElement(); } @@ -1042,7 +1049,7 @@ private function xmlWrite(&$xmlwriter, $data, $mode = 'Text') { if ($mode == 'CData') { $xmlwriter->writeCData($data); } else { - $xmlwriter->text($data); + $xmlwriter->text($data??''); } } } diff --git a/lib/ezyang/htmlpurifier/CREDITS b/lib/ezyang/htmlpurifier/CREDITS new file mode 100644 index 00000000..7921b45a --- /dev/null +++ b/lib/ezyang/htmlpurifier/CREDITS @@ -0,0 +1,9 @@ + +CREDITS + +Almost everything written by Edward Z. Yang (Ambush Commander). Lots of thanks +to the DevNetwork Community for their help (see docs/ref-devnetwork.html for +more details), Feyd especially (namely IPv6 and optimization). Thanks to RSnake +for letting me package his fantastic XSS cheatsheet for a smoketest. + + vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/LICENSE b/lib/ezyang/htmlpurifier/LICENSE new file mode 100644 index 00000000..8c88a20d --- /dev/null +++ b/lib/ezyang/htmlpurifier/LICENSE @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/README.md b/lib/ezyang/htmlpurifier/README.md new file mode 100644 index 00000000..e6b7199c --- /dev/null +++ b/lib/ezyang/htmlpurifier/README.md @@ -0,0 +1,29 @@ +HTML Purifier [![Build Status](https://github.com/ezyang/htmlpurifier/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/ezyang/htmlpurifier/actions/workflows/ci.yml) +============= + +HTML Purifier is an HTML filtering solution that uses a unique combination +of robust whitelists and aggressive parsing to ensure that not only are +XSS attacks thwarted, but the resulting HTML is standards compliant. + +HTML Purifier is oriented towards richly formatted documents from +untrusted sources that require CSS and a full tag-set. This library can +be configured to accept a more restrictive set of tags, but it won't be +as efficient as more bare-bones parsers. It will, however, do the job +right, which may be more important. + +Places to go: + +* See INSTALL for a quick installation guide +* See docs/ for developer-oriented documentation, code examples and + an in-depth installation guide. +* See WYSIWYG for information on editors like TinyMCE and FCKeditor + +HTML Purifier can be found on the web at: [http://htmlpurifier.org/](http://htmlpurifier.org/) + +## Installation + +Package available on [Composer](https://packagist.org/packages/ezyang/htmlpurifier). + +If you're using Composer to manage dependencies, you can use + + $ composer require ezyang/htmlpurifier diff --git a/lib/ezyang/htmlpurifier/VERSION b/lib/ezyang/htmlpurifier/VERSION new file mode 100644 index 00000000..09ce0ce7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/VERSION @@ -0,0 +1 @@ +4.14.0 \ No newline at end of file diff --git a/lib/ezyang/htmlpurifier/composer.json b/lib/ezyang/htmlpurifier/composer.json new file mode 100644 index 00000000..5f62d889 --- /dev/null +++ b/lib/ezyang/htmlpurifier/composer.json @@ -0,0 +1,25 @@ +{ + "name": "ezyang/htmlpurifier", + "description": "Standards compliant HTML filter written in PHP", + "type": "library", + "keywords": ["html"], + "homepage": "http://htmlpurifier.org/", + "license": "LGPL-2.1-or-later", + "authors": [ + { + "name": "Edward Z. Yang", + "email": "admin@htmlpurifier.org", + "homepage": "http://ezyang.com" + } + ], + "require": { + "php": ">=5.2" + }, + "autoload": { + "psr-0": { "HTMLPurifier": "library/" }, + "files": ["library/HTMLPurifier.composer.php"], + "exclude-from-classmap": [ + "/library/HTMLPurifier/Language/" + ] + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier.auto.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier.auto.php new file mode 100644 index 00000000..1960c399 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier.auto.php @@ -0,0 +1,11 @@ +purify($html, $config); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier.includes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier.includes.php new file mode 100644 index 00000000..ee81cac6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier.includes.php @@ -0,0 +1,234 @@ + $attributes) { + $allowed_elements[$element] = true; + foreach ($attributes as $attribute => $x) { + $allowed_attributes["$element.$attribute"] = true; + } + } + $config->set('HTML.AllowedElements', $allowed_elements); + $config->set('HTML.AllowedAttributes', $allowed_attributes); + if ($allowed_protocols !== null) { + $config->set('URI.AllowedSchemes', $allowed_protocols); + } + $purifier = new HTMLPurifier($config); + return $purifier->purify($string); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier.path.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier.path.php new file mode 100644 index 00000000..39b1b653 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier.path.php @@ -0,0 +1,11 @@ +config = HTMLPurifier_Config::create($config); + $this->strategy = new HTMLPurifier_Strategy_Core(); + } + + /** + * Adds a filter to process the output. First come first serve + * + * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object + */ + public function addFilter($filter) + { + trigger_error( + 'HTMLPurifier->addFilter() is deprecated, use configuration directives' . + ' in the Filter namespace or Filter.Custom', + E_USER_WARNING + ); + $this->filters[] = $filter; + } + + /** + * Filters an HTML snippet/document to be XSS-free and standards-compliant. + * + * @param string $html String of HTML to purify + * @param HTMLPurifier_Config $config Config object for this operation, + * if omitted, defaults to the config object specified during this + * object's construction. The parameter can also be any type + * that HTMLPurifier_Config::create() supports. + * + * @return string Purified HTML + */ + public function purify($html, $config = null) + { + // :TODO: make the config merge in, instead of replace + $config = $config ? HTMLPurifier_Config::create($config) : $this->config; + + // implementation is partially environment dependant, partially + // configuration dependant + $lexer = HTMLPurifier_Lexer::create($config); + + $context = new HTMLPurifier_Context(); + + // setup HTML generator + $this->generator = new HTMLPurifier_Generator($config, $context); + $context->register('Generator', $this->generator); + + // set up global context variables + if ($config->get('Core.CollectErrors')) { + // may get moved out if other facilities use it + $language_factory = HTMLPurifier_LanguageFactory::instance(); + $language = $language_factory->create($config, $context); + $context->register('Locale', $language); + + $error_collector = new HTMLPurifier_ErrorCollector($context); + $context->register('ErrorCollector', $error_collector); + } + + // setup id_accumulator context, necessary due to the fact that + // AttrValidator can be called from many places + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + + $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context); + + // setup filters + $filter_flags = $config->getBatch('Filter'); + $custom_filters = $filter_flags['Custom']; + unset($filter_flags['Custom']); + $filters = array(); + foreach ($filter_flags as $filter => $flag) { + if (!$flag) { + continue; + } + if (strpos($filter, '.') !== false) { + continue; + } + $class = "HTMLPurifier_Filter_$filter"; + $filters[] = new $class; + } + foreach ($custom_filters as $filter) { + // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat + $filters[] = $filter; + } + $filters = array_merge($filters, $this->filters); + // maybe prepare(), but later + + for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) { + $html = $filters[$i]->preFilter($html, $config, $context); + } + + // purified HTML + $html = + $this->generator->generateFromTokens( + // list of tokens + $this->strategy->execute( + // list of un-purified tokens + $lexer->tokenizeHTML( + // un-purified HTML + $html, + $config, + $context + ), + $config, + $context + ) + ); + + for ($i = $filter_size - 1; $i >= 0; $i--) { + $html = $filters[$i]->postFilter($html, $config, $context); + } + + $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context); + $this->context =& $context; + return $html; + } + + /** + * Filters an array of HTML snippets + * + * @param string[] $array_of_html Array of html snippets + * @param HTMLPurifier_Config $config Optional config object for this operation. + * See HTMLPurifier::purify() for more details. + * + * @return string[] Array of purified HTML + */ + public function purifyArray($array_of_html, $config = null) + { + $context_array = array(); + $array = array(); + foreach($array_of_html as $key=>$value){ + if (is_array($value)) { + $array[$key] = $this->purifyArray($value, $config); + } else { + $array[$key] = $this->purify($value, $config); + } + $context_array[$key] = $this->context; + } + $this->context = $context_array; + return $array; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + */ + public static function instance($prototype = null) + { + if (!self::$instance || $prototype) { + if ($prototype instanceof HTMLPurifier) { + self::$instance = $prototype; + } elseif ($prototype) { + self::$instance = new HTMLPurifier($prototype); + } else { + self::$instance = new HTMLPurifier(); + } + } + return self::$instance; + } + + /** + * Singleton for enforcing just one HTML Purifier in your system + * + * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype + * HTMLPurifier instance to overload singleton with, + * or HTMLPurifier_Config instance to configure the + * generated version with. + * + * @return HTMLPurifier + * @note Backwards compatibility, see instance() + */ + public static function getInstance($prototype = null) + { + return HTMLPurifier::instance($prototype); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier.safe-includes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier.safe-includes.php new file mode 100644 index 00000000..a3261f8a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier.safe-includes.php @@ -0,0 +1,228 @@ +getHTMLDefinition(); + $parent = new HTMLPurifier_Token_Start($definition->info_parent); + $stack = array($parent->toNode()); + foreach ($tokens as $token) { + $token->skip = null; // [MUT] + $token->carryover = null; // [MUT] + if ($token instanceof HTMLPurifier_Token_End) { + $token->start = null; // [MUT] + $r = array_pop($stack); + //assert($r->name === $token->name); + //assert(empty($token->attr)); + $r->endCol = $token->col; + $r->endLine = $token->line; + $r->endArmor = $token->armor; + continue; + } + $node = $token->toNode(); + $stack[count($stack)-1]->children[] = $node; + if ($token instanceof HTMLPurifier_Token_Start) { + $stack[] = $node; + } + } + //assert(count($stack) == 1); + return $stack[0]; + } + + public static function flatten($node, $config, $context) { + $level = 0; + $nodes = array($level => new HTMLPurifier_Queue(array($node))); + $closingTokens = array(); + $tokens = array(); + do { + while (!$nodes[$level]->isEmpty()) { + $node = $nodes[$level]->shift(); // FIFO + list($start, $end) = $node->toTokenPair(); + if ($level > 0) { + $tokens[] = $start; + } + if ($end !== NULL) { + $closingTokens[$level][] = $end; + } + if ($node instanceof HTMLPurifier_Node_Element) { + $level++; + $nodes[$level] = new HTMLPurifier_Queue(); + foreach ($node->children as $childNode) { + $nodes[$level]->push($childNode); + } + } + } + $level--; + if ($level && isset($closingTokens[$level])) { + while ($token = array_pop($closingTokens[$level])) { + $tokens[] = $token; + } + } + } while ($level > 0); + return $tokens; + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrCollections.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrCollections.php new file mode 100644 index 00000000..c7b17cf1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrCollections.php @@ -0,0 +1,148 @@ +doConstruct($attr_types, $modules); + } + + public function doConstruct($attr_types, $modules) + { + // load extensions from the modules + foreach ($modules as $module) { + foreach ($module->attr_collections as $coll_i => $coll) { + if (!isset($this->info[$coll_i])) { + $this->info[$coll_i] = array(); + } + foreach ($coll as $attr_i => $attr) { + if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) { + // merge in includes + $this->info[$coll_i][$attr_i] = array_merge( + $this->info[$coll_i][$attr_i], + $attr + ); + continue; + } + $this->info[$coll_i][$attr_i] = $attr; + } + } + } + // perform internal expansions and inclusions + foreach ($this->info as $name => $attr) { + // merge attribute collections that include others + $this->performInclusions($this->info[$name]); + // replace string identifiers with actual attribute objects + $this->expandIdentifiers($this->info[$name], $attr_types); + } + } + + /** + * Takes a reference to an attribute associative array and performs + * all inclusions specified by the zero index. + * @param array &$attr Reference to attribute array + */ + public function performInclusions(&$attr) + { + if (!isset($attr[0])) { + return; + } + $merge = $attr[0]; + $seen = array(); // recursion guard + // loop through all the inclusions + for ($i = 0; isset($merge[$i]); $i++) { + if (isset($seen[$merge[$i]])) { + continue; + } + $seen[$merge[$i]] = true; + // foreach attribute of the inclusion, copy it over + if (!isset($this->info[$merge[$i]])) { + continue; + } + foreach ($this->info[$merge[$i]] as $key => $value) { + if (isset($attr[$key])) { + continue; + } // also catches more inclusions + $attr[$key] = $value; + } + if (isset($this->info[$merge[$i]][0])) { + // recursion + $merge = array_merge($merge, $this->info[$merge[$i]][0]); + } + } + unset($attr[0]); + } + + /** + * Expands all string identifiers in an attribute array by replacing + * them with the appropriate values inside HTMLPurifier_AttrTypes + * @param array &$attr Reference to attribute array + * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance + */ + public function expandIdentifiers(&$attr, $attr_types) + { + // because foreach will process new elements we add, make sure we + // skip duplicates + $processed = array(); + + foreach ($attr as $def_i => $def) { + // skip inclusions + if ($def_i === 0) { + continue; + } + + if (isset($processed[$def_i])) { + continue; + } + + // determine whether or not attribute is required + if ($required = (strpos($def_i, '*') !== false)) { + // rename the definition + unset($attr[$def_i]); + $def_i = trim($def_i, '*'); + $attr[$def_i] = $def; + } + + $processed[$def_i] = true; + + // if we've already got a literal object, move on + if (is_object($def)) { + // preserve previous required + $attr[$def_i]->required = ($required || $attr[$def_i]->required); + continue; + } + + if ($def === false) { + unset($attr[$def_i]); + continue; + } + + if ($t = $attr_types->get($def)) { + $attr[$def_i] = $t; + $attr[$def_i]->required = $required; + } else { + unset($attr[$def_i]); + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef.php new file mode 100644 index 00000000..739646fa --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef.php @@ -0,0 +1,144 @@ + by removing + * leading and trailing whitespace, ignoring line feeds, and replacing + * carriage returns and tabs with spaces. While most useful for HTML + * attributes specified as CDATA, it can also be applied to most CSS + * values. + * + * @note This method is not entirely standards compliant, as trim() removes + * more types of whitespace than specified in the spec. In practice, + * this is rarely a problem, as those extra characters usually have + * already been removed by HTMLPurifier_Encoder. + * + * @warning This processing is inconsistent with XML's whitespace handling + * as specified by section 3.3.3 and referenced XHTML 1.0 section + * 4.7. However, note that we are NOT necessarily + * parsing XML, thus, this behavior may still be correct. We + * assume that newlines have been normalized. + */ + public function parseCDATA($string) + { + $string = trim($string); + $string = str_replace(array("\n", "\t", "\r"), ' ', $string); + return $string; + } + + /** + * Factory method for creating this class from a string. + * @param string $string String construction info + * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string + */ + public function make($string) + { + // default implementation, return a flyweight of this object. + // If $string has an effect on the returned object (i.e. you + // need to overload this method), it is best + // to clone or instantiate new copies. (Instantiation is safer.) + return $this; + } + + /** + * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work + * properly. THIS IS A HACK! + * @param string $string a CSS colour definition + * @return string + */ + protected function mungeRgb($string) + { + $p = '\s*(\d+(\.\d+)?([%]?))\s*'; + + if (preg_match('/(rgba|hsla)\(/', $string)) { + return preg_replace('/(rgba|hsla)\('.$p.','.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8,\11)', $string); + } + + return preg_replace('/(rgb|hsl)\('.$p.','.$p.','.$p.'\)/', '\1(\2,\5,\8)', $string); + } + + /** + * Parses a possibly escaped CSS string and returns the "pure" + * version of it. + */ + protected function expandCSSEscape($string) + { + // flexibly parse it + $ret = ''; + for ($i = 0, $c = strlen($string); $i < $c; $i++) { + if ($string[$i] === '\\') { + $i++; + if ($i >= $c) { + $ret .= '\\'; + break; + } + if (ctype_xdigit($string[$i])) { + $code = $string[$i]; + for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) { + if (!ctype_xdigit($string[$i])) { + break; + } + $code .= $string[$i]; + } + // We have to be extremely careful when adding + // new characters, to make sure we're not breaking + // the encoding. + $char = HTMLPurifier_Encoder::unichr(hexdec($code)); + if (HTMLPurifier_Encoder::cleanUTF8($char) === '') { + continue; + } + $ret .= $char; + if ($i < $c && trim($string[$i]) !== '') { + $i--; + } + continue; + } + if ($string[$i] === "\n") { + continue; + } + } + $ret .= $string[$i]; + } + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS.php new file mode 100644 index 00000000..ad2cb90a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS.php @@ -0,0 +1,136 @@ +parseCDATA($css); + + $definition = $config->getCSSDefinition(); + $allow_duplicates = $config->get("CSS.AllowDuplicates"); + + + // According to the CSS2.1 spec, the places where a + // non-delimiting semicolon can appear are in strings + // escape sequences. So here is some dumb hack to + // handle quotes. + $len = strlen($css); + $accum = ""; + $declarations = array(); + $quoted = false; + for ($i = 0; $i < $len; $i++) { + $c = strcspn($css, ";'\"", $i); + $accum .= substr($css, $i, $c); + $i += $c; + if ($i == $len) break; + $d = $css[$i]; + if ($quoted) { + $accum .= $d; + if ($d == $quoted) { + $quoted = false; + } + } else { + if ($d == ";") { + $declarations[] = $accum; + $accum = ""; + } else { + $accum .= $d; + $quoted = $d; + } + } + } + if ($accum != "") $declarations[] = $accum; + + $propvalues = array(); + $new_declarations = ''; + + /** + * Name of the current CSS property being validated. + */ + $property = false; + $context->register('CurrentCSSProperty', $property); + + foreach ($declarations as $declaration) { + if (!$declaration) { + continue; + } + if (!strpos($declaration, ':')) { + continue; + } + list($property, $value) = explode(':', $declaration, 2); + $property = trim($property); + $value = trim($value); + $ok = false; + do { + if (isset($definition->info[$property])) { + $ok = true; + break; + } + if (ctype_lower($property)) { + break; + } + $property = strtolower($property); + if (isset($definition->info[$property])) { + $ok = true; + break; + } + } while (0); + if (!$ok) { + continue; + } + // inefficient call, since the validator will do this again + if (strtolower(trim($value)) !== 'inherit') { + // inherit works for everything (but only on the base property) + $result = $definition->info[$property]->validate( + $value, + $config, + $context + ); + } else { + $result = 'inherit'; + } + if ($result === false) { + continue; + } + if ($allow_duplicates) { + $new_declarations .= "$property:$result;"; + } else { + $propvalues[$property] = $result; + } + } + + $context->destroy('CurrentCSSProperty'); + + // procedure does not write the new CSS simultaneously, so it's + // slightly inefficient, but it's the only way of getting rid of + // duplicates. Perhaps config to optimize it, but not now. + + foreach ($propvalues as $prop => $value) { + $new_declarations .= "$prop:$value;"; + } + + return $new_declarations ? $new_declarations : false; + + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php new file mode 100644 index 00000000..af2b83df --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php @@ -0,0 +1,34 @@ + 1.0) { + $result = '1'; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Background.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Background.php new file mode 100644 index 00000000..28c49883 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Background.php @@ -0,0 +1,113 @@ +getCSSDefinition(); + $this->info['background-color'] = $def->info['background-color']; + $this->info['background-image'] = $def->info['background-image']; + $this->info['background-repeat'] = $def->info['background-repeat']; + $this->info['background-attachment'] = $def->info['background-attachment']; + $this->info['background-position'] = $def->info['background-position']; + $this->info['background-size'] = $def->info['background-size']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // munge rgb() decl if necessary + $string = $this->mungeRgb($string); + + // assumes URI doesn't have spaces in it + $bits = explode(' ', $string); // bits to process + + $caught = array(); + $caught['color'] = false; + $caught['image'] = false; + $caught['repeat'] = false; + $caught['attachment'] = false; + $caught['position'] = false; + $caught['size'] = false; + + $i = 0; // number of catches + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($key != 'position') { + if ($status !== false) { + continue; + } + $r = $this->info['background-' . $key]->validate($bit, $config, $context); + } else { + $r = $bit; + } + if ($r === false) { + continue; + } + if ($key == 'position') { + if ($caught[$key] === false) { + $caught[$key] = ''; + } + $caught[$key] .= $r . ' '; + } else { + $caught[$key] = $r; + } + $i++; + break; + } + } + + if (!$i) { + return false; + } + if ($caught['position'] !== false) { + $caught['position'] = $this->info['background-position']-> + validate($caught['position'], $config, $context); + } + + $ret = array(); + foreach ($caught as $value) { + if ($value === false) { + continue; + } + $ret[] = $value; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php new file mode 100644 index 00000000..4580ef5a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php @@ -0,0 +1,157 @@ + | | left | center | right + ] + [ + | | top | center | bottom + ]? + ] | + [ // this signifies that the vertical and horizontal adjectives + // can be arbitrarily ordered, however, there can only be two, + // one of each, or none at all + [ + left | center | right + ] || + [ + top | center | bottom + ] + ] + top, left = 0% + center, (none) = 50% + bottom, right = 100% +*/ + +/* QuirksMode says: + keyword + length/percentage must be ordered correctly, as per W3C + + Internet Explorer and Opera, however, support arbitrary ordering. We + should fix it up. + + Minor issue though, not strictly necessary. +*/ + +// control freaks may appreciate the ability to convert these to +// percentages or something, but it's not necessary + +/** + * Validates the value of background-position. + */ +class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef +{ + + /** + * @type HTMLPurifier_AttrDef_CSS_Length + */ + protected $length; + + /** + * @type HTMLPurifier_AttrDef_CSS_Percentage + */ + protected $percentage; + + public function __construct() + { + $this->length = new HTMLPurifier_AttrDef_CSS_Length(); + $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $bits = explode(' ', $string); + + $keywords = array(); + $keywords['h'] = false; // left, right + $keywords['v'] = false; // top, bottom + $keywords['ch'] = false; // center (first word) + $keywords['cv'] = false; // center (second word) + $measures = array(); + + $i = 0; + + $lookup = array( + 'top' => 'v', + 'bottom' => 'v', + 'left' => 'h', + 'right' => 'h', + 'center' => 'c' + ); + + foreach ($bits as $bit) { + if ($bit === '') { + continue; + } + + // test for keyword + $lbit = ctype_lower($bit) ? $bit : strtolower($bit); + if (isset($lookup[$lbit])) { + $status = $lookup[$lbit]; + if ($status == 'c') { + if ($i == 0) { + $status = 'ch'; + } else { + $status = 'cv'; + } + } + $keywords[$status] = $lbit; + $i++; + } + + // test for length + $r = $this->length->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + + // test for percentage + $r = $this->percentage->validate($bit, $config, $context); + if ($r !== false) { + $measures[] = $r; + $i++; + } + } + + if (!$i) { + return false; + } // no valid values were caught + + $ret = array(); + + // first keyword + if ($keywords['h']) { + $ret[] = $keywords['h']; + } elseif ($keywords['ch']) { + $ret[] = $keywords['ch']; + $keywords['cv'] = false; // prevent re-use: center = center center + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if ($keywords['v']) { + $ret[] = $keywords['v']; + } elseif ($keywords['cv']) { + $ret[] = $keywords['cv']; + } elseif (count($measures)) { + $ret[] = array_shift($measures); + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Border.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Border.php new file mode 100644 index 00000000..16243ba1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Border.php @@ -0,0 +1,56 @@ +getCSSDefinition(); + $this->info['border-width'] = $def->info['border-width']; + $this->info['border-style'] = $def->info['border-style']; + $this->info['border-top-color'] = $def->info['border-top-color']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + $string = $this->mungeRgb($string); + $bits = explode(' ', $string); + $done = array(); // segments we've finished + $ret = ''; // return value + foreach ($bits as $bit) { + foreach ($this->info as $propname => $validator) { + if (isset($done[$propname])) { + continue; + } + $r = $validator->validate($bit, $config, $context); + if ($r !== false) { + $ret .= $r . ' '; + $done[$propname] = true; + break; + } + } + } + return rtrim($ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Color.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Color.php new file mode 100644 index 00000000..d7287a00 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Color.php @@ -0,0 +1,161 @@ +alpha = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param string $color + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($color, $config, $context) + { + static $colors = null; + if ($colors === null) { + $colors = $config->get('Core.ColorKeywords'); + } + + $color = trim($color); + if ($color === '') { + return false; + } + + $lower = strtolower($color); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + + if (preg_match('#(rgb|rgba|hsl|hsla)\(#', $color, $matches) === 1) { + $length = strlen($color); + if (strpos($color, ')') !== $length - 1) { + return false; + } + + // get used function : rgb, rgba, hsl or hsla + $function = $matches[1]; + + $parameters_size = 3; + $alpha_channel = false; + if (substr($function, -1) === 'a') { + $parameters_size = 4; + $alpha_channel = true; + } + + /* + * Allowed types for values : + * parameter_position => [type => max_value] + */ + $allowed_types = array( + 1 => array('percentage' => 100, 'integer' => 255), + 2 => array('percentage' => 100, 'integer' => 255), + 3 => array('percentage' => 100, 'integer' => 255), + ); + $allow_different_types = false; + + if (strpos($function, 'hsl') !== false) { + $allowed_types = array( + 1 => array('integer' => 360), + 2 => array('percentage' => 100), + 3 => array('percentage' => 100), + ); + $allow_different_types = true; + } + + $values = trim(str_replace($function, '', $color), ' ()'); + + $parts = explode(',', $values); + if (count($parts) !== $parameters_size) { + return false; + } + + $type = false; + $new_parts = array(); + $i = 0; + + foreach ($parts as $part) { + $i++; + $part = trim($part); + + if ($part === '') { + return false; + } + + // different check for alpha channel + if ($alpha_channel === true && $i === count($parts)) { + $result = $this->alpha->validate($part, $config, $context); + + if ($result === false) { + return false; + } + + $new_parts[] = (string)$result; + continue; + } + + if (substr($part, -1) === '%') { + $current_type = 'percentage'; + } else { + $current_type = 'integer'; + } + + if (!array_key_exists($current_type, $allowed_types[$i])) { + return false; + } + + if (!$type) { + $type = $current_type; + } + + if ($allow_different_types === false && $type != $current_type) { + return false; + } + + $max_value = $allowed_types[$i][$current_type]; + + if ($current_type == 'integer') { + // Return value between range 0 -> $max_value + $new_parts[] = (int)max(min($part, $max_value), 0); + } elseif ($current_type == 'percentage') { + $new_parts[] = (float)max(min(rtrim($part, '%'), $max_value), 0) . '%'; + } + } + + $new_values = implode(',', $new_parts); + + $color = $function . '(' . $new_values . ')'; + } else { + // hexadecimal handling + if ($color[0] === '#') { + $hex = substr($color, 1); + } else { + $hex = $color; + $color = '#' . $color; + } + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + } + return $color; + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Composite.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Composite.php new file mode 100644 index 00000000..9c175055 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Composite.php @@ -0,0 +1,48 @@ +defs = $defs; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + foreach ($this->defs as $i => $def) { + $result = $this->defs[$i]->validate($string, $config, $context); + if ($result !== false) { + return $result; + } + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php new file mode 100644 index 00000000..9d77cc9a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php @@ -0,0 +1,44 @@ +def = $def; + $this->element = $element; + } + + /** + * Checks if CurrentToken is set and equal to $this->element + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if ($token && $token->name == $this->element) { + return false; + } + return $this->def->validate($string, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Filter.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Filter.php new file mode 100644 index 00000000..bde4c330 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Filter.php @@ -0,0 +1,77 @@ +intValidator = new HTMLPurifier_AttrDef_Integer(); + } + + /** + * @param string $value + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($value, $config, $context) + { + $value = $this->parseCDATA($value); + if ($value === 'none') { + return $value; + } + // if we looped this we could support multiple filters + $function_length = strcspn($value, '('); + $function = trim(substr($value, 0, $function_length)); + if ($function !== 'alpha' && + $function !== 'Alpha' && + $function !== 'progid:DXImageTransform.Microsoft.Alpha' + ) { + return false; + } + $cursor = $function_length + 1; + $parameters_length = strcspn($value, ')', $cursor); + $parameters = substr($value, $cursor, $parameters_length); + $params = explode(',', $parameters); + $ret_params = array(); + $lookup = array(); + foreach ($params as $param) { + list($key, $value) = explode('=', $param); + $key = trim($key); + $value = trim($value); + if (isset($lookup[$key])) { + continue; + } + if ($key !== 'opacity') { + continue; + } + $value = $this->intValidator->validate($value, $config, $context); + if ($value === false) { + continue; + } + $int = (int)$value; + if ($int > 100) { + $value = '100'; + } + if ($int < 0) { + $value = '0'; + } + $ret_params[] = "$key=$value"; + $lookup[$key] = true; + } + $ret_parameters = implode(',', $ret_params); + $ret_function = "$function($ret_parameters)"; + return $ret_function; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Font.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Font.php new file mode 100644 index 00000000..579b97ef --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Font.php @@ -0,0 +1,176 @@ +getCSSDefinition(); + $this->info['font-style'] = $def->info['font-style']; + $this->info['font-variant'] = $def->info['font-variant']; + $this->info['font-weight'] = $def->info['font-weight']; + $this->info['font-size'] = $def->info['font-size']; + $this->info['line-height'] = $def->info['line-height']; + $this->info['font-family'] = $def->info['font-family']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $system_fonts = array( + 'caption' => true, + 'icon' => true, + 'menu' => true, + 'message-box' => true, + 'small-caption' => true, + 'status-bar' => true + ); + + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // check if it's one of the keywords + $lowercase_string = strtolower($string); + if (isset($system_fonts[$lowercase_string])) { + return $lowercase_string; + } + + $bits = explode(' ', $string); // bits to process + $stage = 0; // this indicates what we're looking for + $caught = array(); // which stage 0 properties have we caught? + $stage_1 = array('font-style', 'font-variant', 'font-weight'); + $final = ''; // output + + for ($i = 0, $size = count($bits); $i < $size; $i++) { + if ($bits[$i] === '') { + continue; + } + switch ($stage) { + case 0: // attempting to catch font-style, font-variant or font-weight + foreach ($stage_1 as $validator_name) { + if (isset($caught[$validator_name])) { + continue; + } + $r = $this->info[$validator_name]->validate( + $bits[$i], + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + $caught[$validator_name] = true; + break; + } + } + // all three caught, continue on + if (count($caught) >= 3) { + $stage = 1; + } + if ($r !== false) { + break; + } + case 1: // attempting to catch font-size and perhaps line-height + $found_slash = false; + if (strpos($bits[$i], '/') !== false) { + list($font_size, $line_height) = + explode('/', $bits[$i]); + if ($line_height === '') { + // ooh, there's a space after the slash! + $line_height = false; + $found_slash = true; + } + } else { + $font_size = $bits[$i]; + $line_height = false; + } + $r = $this->info['font-size']->validate( + $font_size, + $config, + $context + ); + if ($r !== false) { + $final .= $r; + // attempt to catch line-height + if ($line_height === false) { + // we need to scroll forward + for ($j = $i + 1; $j < $size; $j++) { + if ($bits[$j] === '') { + continue; + } + if ($bits[$j] === '/') { + if ($found_slash) { + return false; + } else { + $found_slash = true; + continue; + } + } + $line_height = $bits[$j]; + break; + } + } else { + // slash already found + $found_slash = true; + $j = $i; + } + if ($found_slash) { + $i = $j; + $r = $this->info['line-height']->validate( + $line_height, + $config, + $context + ); + if ($r !== false) { + $final .= '/' . $r; + } + } + $final .= ' '; + $stage = 2; + break; + } + return false; + case 2: // attempting to catch font-family + $font_family = + implode(' ', array_slice($bits, $i, $size - $i)); + $r = $this->info['font-family']->validate( + $font_family, + $config, + $context + ); + if ($r !== false) { + $final .= $r . ' '; + // processing completed successfully + return rtrim($final); + } + return false; + } + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/FontFamily.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/FontFamily.php new file mode 100644 index 00000000..74e24c88 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/FontFamily.php @@ -0,0 +1,219 @@ +mask = '_- '; + for ($c = 'a'; $c <= 'z'; $c++) { + $this->mask .= $c; + } + for ($c = 'A'; $c <= 'Z'; $c++) { + $this->mask .= $c; + } + for ($c = '0'; $c <= '9'; $c++) { + $this->mask .= $c; + } // cast-y, but should be fine + // special bytes used by UTF-8 + for ($i = 0x80; $i <= 0xFF; $i++) { + // We don't bother excluding invalid bytes in this range, + // because the our restriction of well-formed UTF-8 will + // prevent these from ever occurring. + $this->mask .= chr($i); + } + + /* + PHP's internal strcspn implementation is + O(length of string * length of mask), making it inefficient + for large masks. However, it's still faster than + preg_match 8) + for (p = s1;;) { + spanp = s2; + do { + if (*spanp == c || p == s1_end) { + return p - s1; + } + } while (spanp++ < (s2_end - 1)); + c = *++p; + } + */ + // possible optimization: invert the mask. + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + static $generic_names = array( + 'serif' => true, + 'sans-serif' => true, + 'monospace' => true, + 'fantasy' => true, + 'cursive' => true + ); + $allowed_fonts = $config->get('CSS.AllowedFonts'); + + // assume that no font names contain commas in them + $fonts = explode(',', $string); + $final = ''; + foreach ($fonts as $font) { + $font = trim($font); + if ($font === '') { + continue; + } + // match a generic name + if (isset($generic_names[$font])) { + if ($allowed_fonts === null || isset($allowed_fonts[$font])) { + $final .= $font . ', '; + } + continue; + } + // match a quoted name + if ($font[0] === '"' || $font[0] === "'") { + $length = strlen($font); + if ($length <= 2) { + continue; + } + $quote = $font[0]; + if ($font[$length - 1] !== $quote) { + continue; + } + $font = substr($font, 1, $length - 2); + } + + $font = $this->expandCSSEscape($font); + + // $font is a pure representation of the font name + + if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) { + continue; + } + + if (ctype_alnum($font) && $font !== '') { + // very simple font, allow it in unharmed + $final .= $font . ', '; + continue; + } + + // bugger out on whitespace. form feed (0C) really + // shouldn't show up regardless + $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font); + + // Here, there are various classes of characters which need + // to be treated differently: + // - Alphanumeric characters are essentially safe. We + // handled these above. + // - Spaces require quoting, though most parsers will do + // the right thing if there aren't any characters that + // can be misinterpreted + // - Dashes rarely occur, but they fairly unproblematic + // for parsing/rendering purposes. + // The above characters cover the majority of Western font + // names. + // - Arbitrary Unicode characters not in ASCII. Because + // most parsers give little thought to Unicode, treatment + // of these codepoints is basically uniform, even for + // punctuation-like codepoints. These characters can + // show up in non-Western pages and are supported by most + // major browsers, for example: "MS 明朝" is a + // legitimate font-name + // . See + // the CSS3 spec for more examples: + // + // You can see live samples of these on the Internet: + // + // However, most of these fonts have ASCII equivalents: + // for example, 'MS Mincho', and it's considered + // professional to use ASCII font names instead of + // Unicode font names. Thanks Takeshi Terada for + // providing this information. + // The following characters, to my knowledge, have not been + // used to name font names. + // - Single quote. While theoretically you might find a + // font name that has a single quote in its name (serving + // as an apostrophe, e.g. Dave's Scribble), I haven't + // been able to find any actual examples of this. + // Internet Explorer's cssText translation (which I + // believe is invoked by innerHTML) normalizes any + // quoting to single quotes, and fails to escape single + // quotes. (Note that this is not IE's behavior for all + // CSS properties, just some sort of special casing for + // font-family). So a single quote *cannot* be used + // safely in the font-family context if there will be an + // innerHTML/cssText translation. Note that Firefox 3.x + // does this too. + // - Double quote. In IE, these get normalized to + // single-quotes, no matter what the encoding. (Fun + // fact, in IE8, the 'content' CSS property gained + // support, where they special cased to preserve encoded + // double quotes, but still translate unadorned double + // quotes into single quotes.) So, because their + // fixpoint behavior is identical to single quotes, they + // cannot be allowed either. Firefox 3.x displays + // single-quote style behavior. + // - Backslashes are reduced by one (so \\ -> \) every + // iteration, so they cannot be used safely. This shows + // up in IE7, IE8 and FF3 + // - Semicolons, commas and backticks are handled properly. + // - The rest of the ASCII punctuation is handled properly. + // We haven't checked what browsers do to unadorned + // versions, but this is not important as long as the + // browser doesn't /remove/ surrounding quotes (as IE does + // for HTML). + // + // With these results in hand, we conclude that there are + // various levels of safety: + // - Paranoid: alphanumeric, spaces and dashes(?) + // - International: Paranoid + non-ASCII Unicode + // - Edgy: Everything except quotes, backslashes + // - NoJS: Standards compliance, e.g. sod IE. Note that + // with some judicious character escaping (since certain + // types of escaping doesn't work) this is theoretically + // OK as long as innerHTML/cssText is not called. + // We believe that international is a reasonable default + // (that we will implement now), and once we do more + // extensive research, we may feel comfortable with dropping + // it down to edgy. + + // Edgy: alphanumeric, spaces, dashes, underscores and Unicode. Use of + // str(c)spn assumes that the string was already well formed + // Unicode (which of course it is). + if (strspn($font, $this->mask) !== strlen($font)) { + continue; + } + + // Historical: + // In the absence of innerHTML/cssText, these ugly + // transforms don't pose a security risk (as \\ and \" + // might--these escapes are not supported by most browsers). + // We could try to be clever and use single-quote wrapping + // when there is a double quote present, but I have choosen + // not to implement that. (NOTE: you can reduce the amount + // of escapes by one depending on what quoting style you use) + // $font = str_replace('\\', '\\5C ', $font); + // $font = str_replace('"', '\\22 ', $font); + // $font = str_replace("'", '\\27 ', $font); + + // font possibly with spaces, requires quoting + $final .= "'$font', "; + } + $final = rtrim($final, ', '); + if ($final === '') { + return false; + } + return $final; + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Ident.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Ident.php new file mode 100644 index 00000000..973002c1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Ident.php @@ -0,0 +1,32 @@ +def = $def; + $this->allow = $allow; + } + + /** + * Intercepts and removes !important if necessary + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // test for ! and important tokens + $string = trim($string); + $is_important = false; + // :TODO: optimization: test directly for !important and ! important + if (strlen($string) >= 9 && substr($string, -9) === 'important') { + $temp = rtrim(substr($string, 0, -9)); + // use a temp, because we might want to restore important + if (strlen($temp) >= 1 && substr($temp, -1) === '!') { + $string = rtrim(substr($temp, 0, -1)); + $is_important = true; + } + } + $string = $this->def->validate($string, $config, $context); + if ($this->allow && $is_important) { + $string .= ' !important'; + } + return $string; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Length.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Length.php new file mode 100644 index 00000000..f12453a0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Length.php @@ -0,0 +1,77 @@ +min = $min !== null ? HTMLPurifier_Length::make($min) : null; + $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + // Optimizations + if ($string === '') { + return false; + } + if ($string === '0') { + return '0'; + } + if (strlen($string) === 1) { + return false; + } + + $length = HTMLPurifier_Length::make($string); + if (!$length->isValid()) { + return false; + } + + if ($this->min) { + $c = $length->compareTo($this->min); + if ($c === false) { + return false; + } + if ($c < 0) { + return false; + } + } + if ($this->max) { + $c = $length->compareTo($this->max); + if ($c === false) { + return false; + } + if ($c > 0) { + return false; + } + } + return $length->toString(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ListStyle.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ListStyle.php new file mode 100644 index 00000000..e74d4265 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ListStyle.php @@ -0,0 +1,112 @@ +getCSSDefinition(); + $this->info['list-style-type'] = $def->info['list-style-type']; + $this->info['list-style-position'] = $def->info['list-style-position']; + $this->info['list-style-image'] = $def->info['list-style-image']; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + // regular pre-processing + $string = $this->parseCDATA($string); + if ($string === '') { + return false; + } + + // assumes URI doesn't have spaces in it + $bits = explode(' ', strtolower($string)); // bits to process + + $caught = array(); + $caught['type'] = false; + $caught['position'] = false; + $caught['image'] = false; + + $i = 0; // number of catches + $none = false; + + foreach ($bits as $bit) { + if ($i >= 3) { + return; + } // optimization bit + if ($bit === '') { + continue; + } + foreach ($caught as $key => $status) { + if ($status !== false) { + continue; + } + $r = $this->info['list-style-' . $key]->validate($bit, $config, $context); + if ($r === false) { + continue; + } + if ($r === 'none') { + if ($none) { + continue; + } else { + $none = true; + } + if ($key == 'image') { + continue; + } + } + $caught[$key] = $r; + $i++; + break; + } + } + + if (!$i) { + return false; + } + + $ret = array(); + + // construct type + if ($caught['type']) { + $ret[] = $caught['type']; + } + + // construct image + if ($caught['image']) { + $ret[] = $caught['image']; + } + + // construct position + if ($caught['position']) { + $ret[] = $caught['position']; + } + + if (empty($ret)) { + return false; + } + return implode(' ', $ret); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Multiple.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Multiple.php new file mode 100644 index 00000000..e707f871 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Multiple.php @@ -0,0 +1,71 @@ +single = $single; + $this->max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->mungeRgb($this->parseCDATA($string)); + if ($string === '') { + return false; + } + $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n + $length = count($parts); + $final = ''; + for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) { + if (ctype_space($parts[$i])) { + continue; + } + $result = $this->single->validate($parts[$i], $config, $context); + if ($result !== false) { + $final .= $result . ' '; + $num++; + } + } + if ($final === '') { + return false; + } + return rtrim($final); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Number.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Number.php new file mode 100644 index 00000000..ef49d20f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Number.php @@ -0,0 +1,90 @@ +non_negative = $non_negative; + } + + /** + * @param string $number + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string|bool + * @warning Some contexts do not pass $config, $context. These + * variables should not be used without checking HTMLPurifier_Length + */ + public function validate($number, $config, $context) + { + $number = $this->parseCDATA($number); + + if ($number === '') { + return false; + } + if ($number === '0') { + return '0'; + } + + $sign = ''; + switch ($number[0]) { + case '-': + if ($this->non_negative) { + return false; + } + $sign = '-'; + case '+': + $number = substr($number, 1); + } + + if (ctype_digit($number)) { + $number = ltrim($number, '0'); + return $number ? $sign . $number : '0'; + } + + // Period is the only non-numeric character allowed + if (strpos($number, '.') === false) { + return false; + } + + list($left, $right) = explode('.', $number, 2); + + if ($left === '' && $right === '') { + return false; + } + if ($left !== '' && !ctype_digit($left)) { + return false; + } + + // Remove leading zeros until positive number or a zero stays left + if (ltrim($left, '0') != '') { + $left = ltrim($left, '0'); + } else { + $left = '0'; + } + + $right = rtrim($right, '0'); + + if ($right === '') { + return $left ? $sign . $left : '0'; + } elseif (!ctype_digit($right)) { + return false; + } + return $sign . $left . '.' . $right; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Percentage.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Percentage.php new file mode 100644 index 00000000..f0f25c50 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Percentage.php @@ -0,0 +1,54 @@ +number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = $this->parseCDATA($string); + + if ($string === '') { + return false; + } + $length = strlen($string); + if ($length === 1) { + return false; + } + if ($string[$length - 1] !== '%') { + return false; + } + + $number = substr($string, 0, $length - 1); + $number = $this->number_def->validate($number, $config, $context); + + if ($number === false) { + return false; + } + return "$number%"; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php new file mode 100644 index 00000000..5fd4b7f7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php @@ -0,0 +1,46 @@ + true, + 'overline' => true, + 'underline' => true, + ); + + $string = strtolower($this->parseCDATA($string)); + + if ($string === 'none') { + return $string; + } + + $parts = explode(' ', $string); + $final = ''; + foreach ($parts as $part) { + if (isset($allowed_values[$part])) { + $final .= $part . ' '; + } + } + $final = rtrim($final); + if ($final === '') { + return false; + } + return $final; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/URI.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/URI.php new file mode 100644 index 00000000..6617acac --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/URI.php @@ -0,0 +1,77 @@ +parseCDATA($uri_string); + if (strpos($uri_string, 'url(') !== 0) { + return false; + } + $uri_string = substr($uri_string, 4); + if (strlen($uri_string) == 0) { + return false; + } + $new_length = strlen($uri_string) - 1; + if ($uri_string[$new_length] != ')') { + return false; + } + $uri = trim(substr($uri_string, 0, $new_length)); + + if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) { + $quote = $uri[0]; + $new_length = strlen($uri) - 1; + if ($uri[$new_length] !== $quote) { + return false; + } + $uri = substr($uri, 1, $new_length - 1); + } + + $uri = $this->expandCSSEscape($uri); + + $result = parent::validate($uri, $config, $context); + + if ($result === false) { + return false; + } + + // extra sanity check; should have been done by URI + $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result); + + // suspicious characters are ()'; we're going to percent encode + // them for safety. + $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result); + + // there's an extra bug where ampersands lose their escaping on + // an innerHTML cycle, so a very unlucky query parameter could + // then change the meaning of the URL. Unfortunately, there's + // not much we can do about that... + return "url(\"$result\")"; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Clone.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Clone.php new file mode 100644 index 00000000..6698a00c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Clone.php @@ -0,0 +1,44 @@ +clone = $clone; + } + + /** + * @param string $v + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($v, $config, $context) + { + return $this->clone->validate($v, $config, $context); + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + return clone $this->clone; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Enum.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Enum.php new file mode 100644 index 00000000..8abda7f6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Enum.php @@ -0,0 +1,73 @@ +valid_values = array_flip($valid_values); + $this->case_sensitive = $case_sensitive; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if (!$this->case_sensitive) { + // we may want to do full case-insensitive libraries + $string = ctype_lower($string) ? $string : strtolower($string); + } + $result = isset($this->valid_values[$string]); + + return $result ? $string : false; + } + + /** + * @param string $string In form of comma-delimited list of case-insensitive + * valid values. Example: "foo,bar,baz". Prepend "s:" to make + * case sensitive + * @return HTMLPurifier_AttrDef_Enum + */ + public function make($string) + { + if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') { + $string = substr($string, 2); + $sensitive = true; + } else { + $sensitive = false; + } + $values = explode(',', $string); + return new HTMLPurifier_AttrDef_Enum($values, $sensitive); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Bool.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Bool.php new file mode 100644 index 00000000..be3bbc8d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Bool.php @@ -0,0 +1,48 @@ +name = $name; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + return $this->name; + } + + /** + * @param string $string Name of attribute + * @return HTMLPurifier_AttrDef_HTML_Bool + */ + public function make($string) + { + return new HTMLPurifier_AttrDef_HTML_Bool($string); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Class.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Class.php new file mode 100644 index 00000000..d5013488 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Class.php @@ -0,0 +1,48 @@ +getDefinition('HTML')->doctype->name; + if ($name == "XHTML 1.1" || $name == "XHTML 2.0") { + return parent::split($string, $config, $context); + } else { + return preg_split('/\s+/', $string); + } + } + + /** + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + $allowed = $config->get('Attr.AllowedClasses'); + $forbidden = $config->get('Attr.ForbiddenClasses'); + $ret = array(); + foreach ($tokens as $token) { + if (($allowed === null || isset($allowed[$token])) && + !isset($forbidden[$token]) && + // We need this O(n) check because of PHP's array + // implementation that casts -0 to 0. + !in_array($token, $ret, true) + ) { + $ret[] = $token; + } + } + return $ret; + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Color.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Color.php new file mode 100644 index 00000000..946ebb78 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Color.php @@ -0,0 +1,51 @@ +get('Core.ColorKeywords'); + } + + $string = trim($string); + + if (empty($string)) { + return false; + } + $lower = strtolower($string); + if (isset($colors[$lower])) { + return $colors[$lower]; + } + if ($string[0] === '#') { + $hex = substr($string, 1); + } else { + $hex = $string; + } + + $length = strlen($hex); + if ($length !== 3 && $length !== 6) { + return false; + } + if (!ctype_xdigit($hex)) { + return false; + } + if ($length === 3) { + $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; + } + return "#$hex"; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php new file mode 100644 index 00000000..d79ba12b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php @@ -0,0 +1,38 @@ +valid_values === false) { + $this->valid_values = $config->get('Attr.AllowedFrameTargets'); + } + return parent::validate($string, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/ID.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/ID.php new file mode 100644 index 00000000..4ba45610 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/ID.php @@ -0,0 +1,113 @@ +selector = $selector; + } + + /** + * @param string $id + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($id, $config, $context) + { + if (!$this->selector && !$config->get('Attr.EnableID')) { + return false; + } + + $id = trim($id); // trim it first + + if ($id === '') { + return false; + } + + $prefix = $config->get('Attr.IDPrefix'); + if ($prefix !== '') { + $prefix .= $config->get('Attr.IDPrefixLocal'); + // prevent re-appending the prefix + if (strpos($id, $prefix) !== 0) { + $id = $prefix . $id; + } + } elseif ($config->get('Attr.IDPrefixLocal') !== '') { + trigger_error( + '%Attr.IDPrefixLocal cannot be used unless ' . + '%Attr.IDPrefix is set', + E_USER_WARNING + ); + } + + if (!$this->selector) { + $id_accumulator =& $context->get('IDAccumulator'); + if (isset($id_accumulator->ids[$id])) { + return false; + } + } + + // we purposely avoid using regex, hopefully this is faster + + if ($config->get('Attr.ID.HTML5') === true) { + if (preg_match('/[\t\n\x0b\x0c ]/', $id)) { + return false; + } + } else { + if (ctype_alpha($id)) { + // OK + } else { + if (!ctype_alpha(@$id[0])) { + return false; + } + // primitive style of regexps, I suppose + $trim = trim( + $id, + 'A..Za..z0..9:-._' + ); + if ($trim !== '') { + return false; + } + } + } + + $regexp = $config->get('Attr.IDBlacklistRegexp'); + if ($regexp && preg_match($regexp, $id)) { + return false; + } + + if (!$this->selector) { + $id_accumulator->add($id); + } + + // if no change was made to the ID, return the result + // else, return the new id if stripping whitespace made it + // valid, or return false. + return $id; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Length.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Length.php new file mode 100644 index 00000000..1c4006fb --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Length.php @@ -0,0 +1,56 @@ + 100) { + return '100%'; + } + return ((string)$points) . '%'; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php new file mode 100644 index 00000000..63fa04c1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php @@ -0,0 +1,72 @@ + 'AllowedRel', + 'rev' => 'AllowedRev' + ); + if (!isset($configLookup[$name])) { + trigger_error( + 'Unrecognized attribute name for link ' . + 'relationship.', + E_USER_ERROR + ); + return; + } + $this->name = $configLookup[$name]; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $allowed = $config->get('Attr.' . $this->name); + if (empty($allowed)) { + return false; + } + + $string = $this->parseCDATA($string); + $parts = explode(' ', $string); + + // lookup to prevent duplicates + $ret_lookup = array(); + foreach ($parts as $part) { + $part = strtolower(trim($part)); + if (!isset($allowed[$part])) { + continue; + } + $ret_lookup[$part] = true; + } + + if (empty($ret_lookup)) { + return false; + } + $string = implode(' ', array_keys($ret_lookup)); + return $string; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/MultiLength.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/MultiLength.php new file mode 100644 index 00000000..bbb20f2f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/MultiLength.php @@ -0,0 +1,60 @@ +split($string, $config, $context); + $tokens = $this->filter($tokens, $config, $context); + if (empty($tokens)) { + return false; + } + return implode(' ', $tokens); + } + + /** + * Splits a space separated list of tokens into its constituent parts. + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function split($string, $config, $context) + { + // OPTIMIZABLE! + // do the preg_match, capture all subpatterns for reformulation + + // we don't support U+00A1 and up codepoints or + // escaping because I don't know how to do that with regexps + // and plus it would complicate optimization efforts (you never + // see that anyway). + $pattern = '/(?:(?<=\s)|\A)' . // look behind for space or string start + '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)' . + '(?:(?=\s)|\z)/'; // look ahead for space or string end + preg_match_all($pattern, $string, $matches); + return $matches[1]; + } + + /** + * Template method for removing certain tokens based on arbitrary criteria. + * @note If we wanted to be really functional, we'd do an array_filter + * with a callback. But... we're not. + * @param array $tokens + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + protected function filter($tokens, $config, $context) + { + return $tokens; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Pixels.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Pixels.php new file mode 100644 index 00000000..a1d019e0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Pixels.php @@ -0,0 +1,76 @@ +max = $max; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $string = trim($string); + if ($string === '0') { + return $string; + } + if ($string === '') { + return false; + } + $length = strlen($string); + if (substr($string, $length - 2) == 'px') { + $string = substr($string, 0, $length - 2); + } + if (!is_numeric($string)) { + return false; + } + $int = (int)$string; + + if ($int < 0) { + return '0'; + } + + // upper-bound value, extremely high values can + // crash operating systems, see + // WARNING, above link WILL crash you if you're using Windows + + if ($this->max !== null && $int > $this->max) { + return (string)$this->max; + } + return (string)$int; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef + */ + public function make($string) + { + if ($string === '') { + $max = null; + } else { + $max = (int)$string; + } + $class = get_class($this); + return new $class($max); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Integer.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Integer.php new file mode 100644 index 00000000..400e707d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Integer.php @@ -0,0 +1,91 @@ +negative = $negative; + $this->zero = $zero; + $this->positive = $positive; + } + + /** + * @param string $integer + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($integer, $config, $context) + { + $integer = $this->parseCDATA($integer); + if ($integer === '') { + return false; + } + + // we could possibly simply typecast it to integer, but there are + // certain fringe cases that must not return an integer. + + // clip leading sign + if ($this->negative && $integer[0] === '-') { + $digits = substr($integer, 1); + if ($digits === '0') { + $integer = '0'; + } // rm minus sign for zero + } elseif ($this->positive && $integer[0] === '+') { + $digits = $integer = substr($integer, 1); // rm unnecessary plus + } else { + $digits = $integer; + } + + // test if it's numeric + if (!ctype_digit($digits)) { + return false; + } + + // perform scope tests + if (!$this->zero && $integer == 0) { + return false; + } + if (!$this->positive && $integer > 0) { + return false; + } + if (!$this->negative && $integer < 0) { + return false; + } + + return $integer; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Lang.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Lang.php new file mode 100644 index 00000000..2a55cea6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Lang.php @@ -0,0 +1,86 @@ + 8 || !ctype_alnum($subtags[1])) { + return $new_string; + } + if (!ctype_lower($subtags[1])) { + $subtags[1] = strtolower($subtags[1]); + } + + $new_string .= '-' . $subtags[1]; + if ($num_subtags == 2) { + return $new_string; + } + + // process all other subtags, index 2 and up + for ($i = 2; $i < $num_subtags; $i++) { + $length = strlen($subtags[$i]); + if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) { + return $new_string; + } + if (!ctype_lower($subtags[$i])) { + $subtags[$i] = strtolower($subtags[$i]); + } + $new_string .= '-' . $subtags[$i]; + } + return $new_string; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Switch.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Switch.php new file mode 100644 index 00000000..c7eb3199 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Switch.php @@ -0,0 +1,53 @@ +tag = $tag; + $this->withTag = $with_tag; + $this->withoutTag = $without_tag; + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $token = $context->get('CurrentToken', true); + if (!$token || $token->name !== $this->tag) { + return $this->withoutTag->validate($string, $config, $context); + } else { + return $this->withTag->validate($string, $config, $context); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Text.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Text.php new file mode 100644 index 00000000..4553a4ea --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Text.php @@ -0,0 +1,21 @@ +parseCDATA($string); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI.php new file mode 100644 index 00000000..c1cd8977 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI.php @@ -0,0 +1,111 @@ +parser = new HTMLPurifier_URIParser(); + $this->embedsResource = (bool)$embeds_resource; + } + + /** + * @param string $string + * @return HTMLPurifier_AttrDef_URI + */ + public function make($string) + { + $embeds = ($string === 'embedded'); + return new HTMLPurifier_AttrDef_URI($embeds); + } + + /** + * @param string $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($uri, $config, $context) + { + if ($config->get('URI.Disable')) { + return false; + } + + $uri = $this->parseCDATA($uri); + + // parse the URI + $uri = $this->parser->parse($uri); + if ($uri === false) { + return false; + } + + // add embedded flag to context for validators + $context->register('EmbeddedURI', $this->embedsResource); + + $ok = false; + do { + + // generic validation + $result = $uri->validate($config, $context); + if (!$result) { + break; + } + + // chained filtering + $uri_def = $config->getDefinition('URI'); + $result = $uri_def->filter($uri, $config, $context); + if (!$result) { + break; + } + + // scheme-specific validation + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + break; + } + if ($this->embedsResource && !$scheme_obj->browsable) { + break; + } + $result = $scheme_obj->validate($uri, $config, $context); + if (!$result) { + break; + } + + // Post chained filtering + $result = $uri_def->postFilter($uri, $config, $context); + if (!$result) { + break; + } + + // survived gauntlet + $ok = true; + + } while (false); + + $context->destroy('EmbeddedURI'); + if (!$ok) { + return false; + } + // back to string + return $uri->toString(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email.php new file mode 100644 index 00000000..daf32b76 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email.php @@ -0,0 +1,20 @@ +" + // that needs more percent encoding to be done + if ($string == '') { + return false; + } + $string = trim($string); + $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string); + return $result ? $string : false; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Host.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Host.php new file mode 100644 index 00000000..1beeaa5d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Host.php @@ -0,0 +1,142 @@ +ipv4 = new HTMLPurifier_AttrDef_URI_IPv4(); + $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6(); + } + + /** + * @param string $string + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool|string + */ + public function validate($string, $config, $context) + { + $length = strlen($string); + // empty hostname is OK; it's usually semantically equivalent: + // the default host as defined by a URI scheme is used: + // + // If the URI scheme defines a default for host, then that + // default applies when the host subcomponent is undefined + // or when the registered name is empty (zero length). + if ($string === '') { + return ''; + } + if ($length > 1 && $string[0] === '[' && $string[$length - 1] === ']') { + //IPv6 + $ip = substr($string, 1, $length - 2); + $valid = $this->ipv6->validate($ip, $config, $context); + if ($valid === false) { + return false; + } + return '[' . $valid . ']'; + } + + // need to do checks on unusual encodings too + $ipv4 = $this->ipv4->validate($string, $config, $context); + if ($ipv4 !== false) { + return $ipv4; + } + + // A regular domain name. + + // This doesn't match I18N domain names, but we don't have proper IRI support, + // so force users to insert Punycode. + + // There is not a good sense in which underscores should be + // allowed, since it's technically not! (And if you go as + // far to allow everything as specified by the DNS spec... + // well, that's literally everything, modulo some space limits + // for the components and the overall name (which, by the way, + // we are NOT checking!). So we (arbitrarily) decide this: + // let's allow underscores wherever we would have allowed + // hyphens, if they are enabled. This is a pretty good match + // for browser behavior, for example, a large number of browsers + // cannot handle foo_.example.com, but foo_bar.example.com is + // fairly well supported. + $underscore = $config->get('Core.AllowHostnameUnderscore') ? '_' : ''; + + // Based off of RFC 1738, but amended so that + // as per RFC 3696, the top label need only not be all numeric. + // The productions describing this are: + $a = '[a-z]'; // alpha + $an = '[a-z0-9]'; // alphanum + $and = "[a-z0-9-$underscore]"; // alphanum | "-" + // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum + $domainlabel = "$an(?:$and*$an)?"; + // AMENDED as per RFC 3696 + // toplabel = alphanum | alphanum *( alphanum | "-" ) alphanum + // side condition: not all numeric + $toplabel = "$an(?:$and*$an)?"; + // hostname = *( domainlabel "." ) toplabel [ "." ] + if (preg_match("/^(?:$domainlabel\.)*($toplabel)\.?$/i", $string, $matches)) { + if (!ctype_digit($matches[1])) { + return $string; + } + } + + // PHP 5.3 and later support this functionality natively + if (function_exists('idn_to_ascii')) { + if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) { + $string = idn_to_ascii($string, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46); + } else { + $string = idn_to_ascii($string); + } + + // If we have Net_IDNA2 support, we can support IRIs by + // punycoding them. (This is the most portable thing to do, + // since otherwise we have to assume browsers support + } elseif ($config->get('Core.EnableIDNA')) { + $idna = new Net_IDNA2(array('encoding' => 'utf8', 'overlong' => false, 'strict' => true)); + // we need to encode each period separately + $parts = explode('.', $string); + try { + $new_parts = array(); + foreach ($parts as $part) { + $encodable = false; + for ($i = 0, $c = strlen($part); $i < $c; $i++) { + if (ord($part[$i]) > 0x7a) { + $encodable = true; + break; + } + } + if (!$encodable) { + $new_parts[] = $part; + } else { + $new_parts[] = $idna->encode($part); + } + } + $string = implode('.', $new_parts); + } catch (Exception $e) { + // XXX error reporting + } + } + // Try again + if (preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string)) { + return $string; + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv4.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv4.php new file mode 100644 index 00000000..30ac16c9 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv4.php @@ -0,0 +1,45 @@ +ip4) { + $this->_loadRegex(); + } + + if (preg_match('#^' . $this->ip4 . '$#s', $aIP)) { + return $aIP; + } + return false; + } + + /** + * Lazy load function to prevent regex from being stuffed in + * cache. + */ + protected function _loadRegex() + { + $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255 + $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})"; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv6.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv6.php new file mode 100644 index 00000000..f243793e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv6.php @@ -0,0 +1,89 @@ +ip4) { + $this->_loadRegex(); + } + + $original = $aIP; + + $hex = '[0-9a-fA-F]'; + $blk = '(?:' . $hex . '{1,4})'; + $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128 + + // prefix check + if (strpos($aIP, '/') !== false) { + if (preg_match('#' . $pre . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + unset($find); + } else { + return false; + } + } + + // IPv4-compatiblity check + if (preg_match('#(?<=:' . ')' . $this->ip4 . '$#s', $aIP, $find)) { + $aIP = substr($aIP, 0, 0 - strlen($find[0])); + $ip = explode('.', $find[0]); + $ip = array_map('dechex', $ip); + $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3]; + unset($find, $ip); + } + + // compression check + $aIP = explode('::', $aIP); + $c = count($aIP); + if ($c > 2) { + return false; + } elseif ($c == 2) { + list($first, $second) = $aIP; + $first = explode(':', $first); + $second = explode(':', $second); + + if (count($first) + count($second) > 8) { + return false; + } + + while (count($first) < 8) { + array_push($first, '0'); + } + + array_splice($first, 8 - count($second), 8, $second); + $aIP = $first; + unset($first, $second); + } else { + $aIP = explode(':', $aIP[0]); + } + $c = count($aIP); + + if ($c != 8) { + return false; + } + + // All the pieces should be 16-bit hex strings. Are they? + foreach ($aIP as $piece) { + if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece))) { + return false; + } + } + return $original; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform.php new file mode 100644 index 00000000..b428331f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform.php @@ -0,0 +1,60 @@ +confiscateAttr($attr, 'background'); + // some validation should happen here + + $this->prependCSS($attr, "background-image:url($background);"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BdoDir.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BdoDir.php new file mode 100644 index 00000000..d66c04a5 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BdoDir.php @@ -0,0 +1,27 @@ +get('Attr.DefaultTextDir'); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BgColor.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BgColor.php new file mode 100644 index 00000000..0f51fd2c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BgColor.php @@ -0,0 +1,28 @@ +confiscateAttr($attr, 'bgcolor'); + // some validation should happen here + + $this->prependCSS($attr, "background-color:$bgcolor;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BoolToCSS.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BoolToCSS.php new file mode 100644 index 00000000..f25cd019 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/BoolToCSS.php @@ -0,0 +1,47 @@ +attr = $attr; + $this->css = $css; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + unset($attr[$this->attr]); + $this->prependCSS($attr, $this->css); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Border.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Border.php new file mode 100644 index 00000000..057dc017 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Border.php @@ -0,0 +1,26 @@ +confiscateAttr($attr, 'border'); + // some validation should happen here + $this->prependCSS($attr, "border:{$border_width}px solid;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/EnumToCSS.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/EnumToCSS.php new file mode 100644 index 00000000..7ccd0e3f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/EnumToCSS.php @@ -0,0 +1,68 @@ +attr = $attr; + $this->enumToCSS = $enum_to_css; + $this->caseSensitive = (bool)$case_sensitive; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $value = trim($attr[$this->attr]); + unset($attr[$this->attr]); + + if (!$this->caseSensitive) { + $value = strtolower($value); + } + + if (!isset($this->enumToCSS[$value])) { + return $attr; + } + $this->prependCSS($attr, $this->enumToCSS[$value]); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgRequired.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgRequired.php new file mode 100644 index 00000000..235ebb34 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgRequired.php @@ -0,0 +1,47 @@ +get('Core.RemoveInvalidImg')) { + return $attr; + } + $attr['src'] = $config->get('Attr.DefaultInvalidImage'); + $src = false; + } + + if (!isset($attr['alt'])) { + if ($src) { + $alt = $config->get('Attr.DefaultImageAlt'); + if ($alt === null) { + $attr['alt'] = basename($attr['src']); + } else { + $attr['alt'] = $alt; + } + } else { + $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt'); + } + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgSpace.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgSpace.php new file mode 100644 index 00000000..350b3358 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ImgSpace.php @@ -0,0 +1,61 @@ + array('left', 'right'), + 'vspace' => array('top', 'bottom') + ); + + /** + * @param string $attr + */ + public function __construct($attr) + { + $this->attr = $attr; + if (!isset($this->css[$attr])) { + trigger_error(htmlspecialchars($attr) . ' is not valid space attribute'); + } + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->attr])) { + return $attr; + } + + $width = $this->confiscateAttr($attr, $this->attr); + // some validation could happen here + + if (!isset($this->css[$this->attr])) { + return $attr; + } + + $style = ''; + foreach ($this->css[$this->attr] as $suffix) { + $property = "margin-$suffix"; + $style .= "$property:{$width}px;"; + } + $this->prependCSS($attr, $style); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Input.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Input.php new file mode 100644 index 00000000..3ab47ed8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Input.php @@ -0,0 +1,56 @@ +pixels = new HTMLPurifier_AttrDef_HTML_Pixels(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $t = 'text'; + } else { + $t = strtolower($attr['type']); + } + if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') { + unset($attr['checked']); + } + if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') { + unset($attr['maxlength']); + } + if (isset($attr['size']) && $t !== 'text' && $t !== 'password') { + $result = $this->pixels->validate($attr['size'], $config, $context); + if ($result === false) { + unset($attr['size']); + } else { + $attr['size'] = $result; + } + } + if (isset($attr['src']) && $t !== 'image') { + unset($attr['src']); + } + if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) { + $attr['value'] = ''; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Lang.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Lang.php new file mode 100644 index 00000000..5b0aff0e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Lang.php @@ -0,0 +1,31 @@ +name = $name; + $this->cssName = $css_name ? $css_name : $name; + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr[$this->name])) { + return $attr; + } + $length = $this->confiscateAttr($attr, $this->name); + if (ctype_digit($length)) { + $length .= 'px'; + } + $this->prependCSS($attr, $this->cssName . ":$length;"); + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Name.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Name.php new file mode 100644 index 00000000..63cce683 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Name.php @@ -0,0 +1,33 @@ +get('HTML.Attr.Name.UseCDATA')) { + return $attr; + } + if (!isset($attr['name'])) { + return $attr; + } + $id = $this->confiscateAttr($attr, 'name'); + if (isset($attr['id'])) { + return $attr; + } + $attr['id'] = $id; + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/NameSync.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/NameSync.php new file mode 100644 index 00000000..36079b78 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/NameSync.php @@ -0,0 +1,41 @@ +idDef = new HTMLPurifier_AttrDef_HTML_ID(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['name'])) { + return $attr; + } + $name = $attr['name']; + if (isset($attr['id']) && $attr['id'] === $name) { + return $attr; + } + $result = $this->idDef->validate($name, $config, $context); + if ($result === false) { + unset($attr['name']); + } else { + $attr['name'] = $result; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Nofollow.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Nofollow.php new file mode 100644 index 00000000..1057ebee --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/Nofollow.php @@ -0,0 +1,52 @@ +parser = new HTMLPurifier_URIParser(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['href'])) { + return $attr; + } + + // XXX Kind of inefficient + $url = $this->parser->parse($attr['href']); + $scheme = $url->getSchemeObj($config, $context); + + if ($scheme->browsable && !$url->isLocal($config, $context)) { + if (isset($attr['rel'])) { + $rels = explode(' ', $attr['rel']); + if (!in_array('nofollow', $rels)) { + $rels[] = 'nofollow'; + } + $attr['rel'] = implode(' ', $rels); + } else { + $attr['rel'] = 'nofollow'; + } + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/SafeEmbed.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/SafeEmbed.php new file mode 100644 index 00000000..231c81a3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/SafeEmbed.php @@ -0,0 +1,25 @@ +uri = new HTMLPurifier_AttrDef_URI(true); // embedded + $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent')); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // If we add support for other objects, we'll need to alter the + // transforms. + switch ($attr['name']) { + // application/x-shockwave-flash + // Keep this synchronized with Injector/SafeObject.php + case 'allowScriptAccess': + $attr['value'] = 'never'; + break; + case 'allowNetworking': + $attr['value'] = 'internal'; + break; + case 'allowFullScreen': + if ($config->get('HTML.FlashAllowFullScreen')) { + $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false'; + } else { + $attr['value'] = 'false'; + } + break; + case 'wmode': + $attr['value'] = $this->wmode->validate($attr['value'], $config, $context); + break; + case 'movie': + case 'src': + $attr['name'] = "movie"; + $attr['value'] = $this->uri->validate($attr['value'], $config, $context); + break; + case 'flashvars': + // we're going to allow arbitrary inputs to the SWF, on + // the reasoning that it could only hack the SWF, not us. + break; + // add other cases to support other param name/value pairs + default: + $attr['name'] = $attr['value'] = null; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ScriptRequired.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ScriptRequired.php new file mode 100644 index 00000000..b7057bbf --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/ScriptRequired.php @@ -0,0 +1,23 @@ + + */ +class HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['type'])) { + $attr['type'] = 'text/javascript'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetBlank.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetBlank.php new file mode 100644 index 00000000..dd63ea89 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetBlank.php @@ -0,0 +1,45 @@ +parser = new HTMLPurifier_URIParser(); + } + + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + if (!isset($attr['href'])) { + return $attr; + } + + // XXX Kind of inefficient + $url = $this->parser->parse($attr['href']); + $scheme = $url->getSchemeObj($config, $context); + + if ($scheme->browsable && !$url->isBenign($config, $context)) { + $attr['target'] = '_blank'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetNoopener.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetNoopener.php new file mode 100644 index 00000000..1db3c6c0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetNoopener.php @@ -0,0 +1,37 @@ + + */ +class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform +{ + /** + * @param array $attr + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function transform($attr, $config, $context) + { + // Calculated from Firefox + if (!isset($attr['cols'])) { + $attr['cols'] = '22'; + } + if (!isset($attr['rows'])) { + $attr['rows'] = '3'; + } + return $attr; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTypes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTypes.php new file mode 100644 index 00000000..3b70520b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrTypes.php @@ -0,0 +1,96 @@ +info['Enum'] = new HTMLPurifier_AttrDef_Enum(); + $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool(); + + $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID(); + $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length(); + $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength(); + $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens(); + $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels(); + $this->info['Text'] = new HTMLPurifier_AttrDef_Text(); + $this->info['URI'] = new HTMLPurifier_AttrDef_URI(); + $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang(); + $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color(); + $this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right'); + $this->info['LAlign'] = self::makeEnum('top,bottom,left,right'); + $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget(); + + // unimplemented aliases + $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text(); + $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text(); + $this->info['Character'] = new HTMLPurifier_AttrDef_Text(); + + // "proprietary" types + $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class(); + + // number is really a positive integer (one or more digits) + // FIXME: ^^ not always, see start and value of list items + $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true); + } + + private static function makeEnum($in) + { + return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in))); + } + + /** + * Retrieves a type + * @param string $type String type name + * @return HTMLPurifier_AttrDef Object AttrDef for type + */ + public function get($type) + { + // determine if there is any extra info tacked on + if (strpos($type, '#') !== false) { + list($type, $string) = explode('#', $type, 2); + } else { + $string = ''; + } + + if (!isset($this->info[$type])) { + trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR); + return; + } + return $this->info[$type]->make($string); + } + + /** + * Sets a new implementation for a type + * @param string $type String type name + * @param HTMLPurifier_AttrDef $impl Object AttrDef for type + */ + public function set($type, $impl) + { + $this->info[$type] = $impl; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrValidator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrValidator.php new file mode 100644 index 00000000..f97dc93e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/AttrValidator.php @@ -0,0 +1,178 @@ +getHTMLDefinition(); + $e =& $context->get('ErrorCollector', true); + + // initialize IDAccumulator if necessary + $ok =& $context->get('IDAccumulator', true); + if (!$ok) { + $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context); + $context->register('IDAccumulator', $id_accumulator); + } + + // initialize CurrentToken if necessary + $current_token =& $context->get('CurrentToken', true); + if (!$current_token) { + $context->register('CurrentToken', $token); + } + + if (!$token instanceof HTMLPurifier_Token_Start && + !$token instanceof HTMLPurifier_Token_Empty + ) { + return; + } + + // create alias to global definition array, see also $defs + // DEFINITION CALL + $d_defs = $definition->info_global_attr; + + // don't update token until the very end, to ensure an atomic update + $attr = $token->attr; + + // do global transformations (pre) + // nothing currently utilizes this + foreach ($definition->info_attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // do local transformations only applicable to this element (pre) + // ex.

    to

    + foreach ($definition->info[$token->name]->attr_transform_pre as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // create alias to this element's attribute definition array, see + // also $d_defs (global attribute definition array) + // DEFINITION CALL + $defs = $definition->info[$token->name]->attr; + + $attr_key = false; + $context->register('CurrentAttr', $attr_key); + + // iterate through all the attribute keypairs + // Watch out for name collisions: $key has previously been used + foreach ($attr as $attr_key => $value) { + + // call the definition + if (isset($defs[$attr_key])) { + // there is a local definition defined + if ($defs[$attr_key] === false) { + // We've explicitly been told not to allow this element. + // This is usually when there's a global definition + // that must be overridden. + // Theoretically speaking, we could have a + // AttrDef_DenyAll, but this is faster! + $result = false; + } else { + // validate according to the element's definition + $result = $defs[$attr_key]->validate( + $value, + $config, + $context + ); + } + } elseif (isset($d_defs[$attr_key])) { + // there is a global definition defined, validate according + // to the global definition + $result = $d_defs[$attr_key]->validate( + $value, + $config, + $context + ); + } else { + // system never heard of the attribute? DELETE! + $result = false; + } + + // put the results into effect + if ($result === false || $result === null) { + // this is a generic error message that should replaced + // with more specific ones when possible + if ($e) { + $e->send(E_ERROR, 'AttrValidator: Attribute removed'); + } + + // remove the attribute + unset($attr[$attr_key]); + } elseif (is_string($result)) { + // generally, if a substitution is happening, there + // was some sort of implicit correction going on. We'll + // delegate it to the attribute classes to say exactly what. + + // simple substitution + $attr[$attr_key] = $result; + } else { + // nothing happens + } + + // we'd also want slightly more complicated substitution + // involving an array as the return value, + // although we're not sure how colliding attributes would + // resolve (certain ones would be completely overriden, + // others would prepend themselves). + } + + $context->destroy('CurrentAttr'); + + // post transforms + + // global (error reporting untested) + foreach ($definition->info_attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + // local (error reporting untested) + foreach ($definition->info[$token->name]->attr_transform_post as $transform) { + $attr = $transform->transform($o = $attr, $config, $context); + if ($e) { + if ($attr != $o) { + $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr); + } + } + } + + $token->attr = $attr; + + // destroy CurrentToken if we made it ourselves + if (!$current_token) { + $context->destroy('CurrentToken'); + } + + } + + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Bootstrap.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Bootstrap.php new file mode 100644 index 00000000..707122bb --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Bootstrap.php @@ -0,0 +1,124 @@ + +if (!defined('PHP_EOL')) { + switch (strtoupper(substr(PHP_OS, 0, 3))) { + case 'WIN': + define('PHP_EOL', "\r\n"); + break; + case 'DAR': + define('PHP_EOL', "\r"); + break; + default: + define('PHP_EOL', "\n"); + } +} + +/** + * Bootstrap class that contains meta-functionality for HTML Purifier such as + * the autoload function. + * + * @note + * This class may be used without any other files from HTML Purifier. + */ +class HTMLPurifier_Bootstrap +{ + + /** + * Autoload function for HTML Purifier + * @param string $class Class to load + * @return bool + */ + public static function autoload($class) + { + $file = HTMLPurifier_Bootstrap::getPath($class); + if (!$file) { + return false; + } + // Technically speaking, it should be ok and more efficient to + // just do 'require', but Antonio Parraga reports that with + // Zend extensions such as Zend debugger and APC, this invariant + // may be broken. Since we have efficient alternatives, pay + // the cost here and avoid the bug. + require_once HTMLPURIFIER_PREFIX . '/' . $file; + return true; + } + + /** + * Returns the path for a specific class. + * @param string $class Class path to get + * @return string + */ + public static function getPath($class) + { + if (strncmp('HTMLPurifier', $class, 12) !== 0) { + return false; + } + // Custom implementations + if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) { + $code = str_replace('_', '-', substr($class, 22)); + $file = 'HTMLPurifier/Language/classes/' . $code . '.php'; + } else { + $file = str_replace('_', '/', $class) . '.php'; + } + if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) { + return false; + } + return $file; + } + + /** + * "Pre-registers" our autoloader on the SPL stack. + */ + public static function registerAutoload() + { + $autoload = array('HTMLPurifier_Bootstrap', 'autoload'); + if (($funcs = spl_autoload_functions()) === false) { + spl_autoload_register($autoload); + } elseif (function_exists('spl_autoload_unregister')) { + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + // prepend flag exists, no need for shenanigans + spl_autoload_register($autoload, true, true); + } else { + $buggy = version_compare(PHP_VERSION, '5.2.11', '<'); + $compat = version_compare(PHP_VERSION, '5.1.2', '<=') && + version_compare(PHP_VERSION, '5.1.0', '>='); + foreach ($funcs as $func) { + if ($buggy && is_array($func)) { + // :TRICKY: There are some compatibility issues and some + // places where we need to error out + $reflector = new ReflectionMethod($func[0], $func[1]); + if (!$reflector->isStatic()) { + throw new Exception( + 'HTML Purifier autoloader registrar is not compatible + with non-static object methods due to PHP Bug #44144; + Please do not use HTMLPurifier.autoload.php (or any + file that includes this file); instead, place the code: + spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\')) + after your own autoloaders.' + ); + } + // Suprisingly, spl_autoload_register supports the + // Class::staticMethod callback format, although call_user_func doesn't + if ($compat) { + $func = implode('::', $func); + } + } + spl_autoload_unregister($func); + } + spl_autoload_register($autoload); + foreach ($funcs as $func) { + spl_autoload_register($func); + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/CSSDefinition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/CSSDefinition.php new file mode 100644 index 00000000..3f08b81c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/CSSDefinition.php @@ -0,0 +1,549 @@ +info['text-align'] = new HTMLPurifier_AttrDef_Enum( + array('left', 'right', 'center', 'justify'), + false + ); + + $border_style = + $this->info['border-bottom-style'] = + $this->info['border-right-style'] = + $this->info['border-left-style'] = + $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum( + array( + 'none', + 'hidden', + 'dotted', + 'dashed', + 'solid', + 'double', + 'groove', + 'ridge', + 'inset', + 'outset' + ), + false + ); + + $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style); + + $this->info['clear'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right', 'both'), + false + ); + $this->info['float'] = new HTMLPurifier_AttrDef_Enum( + array('none', 'left', 'right'), + false + ); + $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'italic', 'oblique'), + false + ); + $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum( + array('normal', 'small-caps'), + false + ); + + $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('none')), + new HTMLPurifier_AttrDef_CSS_URI() + ) + ); + + $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum( + array('inside', 'outside'), + false + ); + $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum( + array( + 'disc', + 'circle', + 'square', + 'decimal', + 'lower-roman', + 'upper-roman', + 'lower-alpha', + 'upper-alpha', + 'none' + ), + false + ); + $this->info['list-style-image'] = $uri_or_none; + + $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config); + + $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum( + array('capitalize', 'uppercase', 'lowercase', 'none'), + false + ); + $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + $this->info['background-image'] = $uri_or_none; + $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum( + array('repeat', 'repeat-x', 'repeat-y', 'no-repeat') + ); + $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum( + array('scroll', 'fixed') + ); + $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition(); + + $this->info['background-size'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'auto', + 'cover', + 'contain', + 'initial', + 'inherit', + ) + ), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $border_color = + $this->info['border-top-color'] = + $this->info['border-bottom-color'] = + $this->info['border-left-color'] = + $this->info['border-right-color'] = + $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('transparent')), + new HTMLPurifier_AttrDef_CSS_Color() + ) + ); + + $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config); + + $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color); + + $border_width = + $this->info['border-top-width'] = + $this->info['border-bottom-width'] = + $this->info['border-left-width'] = + $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')), + new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative + ) + ); + + $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width); + + $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'xx-small', + 'x-small', + 'small', + 'medium', + 'large', + 'x-large', + 'xx-large', + 'larger', + 'smaller' + ) + ), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_CSS_Length() + ) + ); + + $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum(array('normal')), + new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $margin = + $this->info['margin-top'] = + $this->info['margin-bottom'] = + $this->info['margin-left'] = + $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ); + + $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin); + + // non-negative + $padding = + $this->info['padding-top'] = + $this->info['padding-bottom'] = + $this->info['padding-left'] = + $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true) + ) + ); + + $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding); + + $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('auto', 'initial', 'inherit')) + ) + ); + $trusted_min_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ); + $trusted_max_wh = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0'), + new HTMLPurifier_AttrDef_CSS_Percentage(true), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ); + $max = $config->get('CSS.MaxImgLength'); + + $this->info['width'] = + $this->info['height'] = + $max === null ? + $trusted_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('auto')) + ) + ), + // For everyone else: + $trusted_wh + ); + $this->info['min-width'] = + $this->info['min-height'] = + $max === null ? + $trusted_min_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_min_wh + ); + $this->info['max-width'] = + $this->info['max-height'] = + $max === null ? + $trusted_max_wh : + new HTMLPurifier_AttrDef_Switch( + 'img', + // For img tags: + new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length('0', $max), + new HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')) + ) + ), + // For everyone else: + $trusted_max_wh + ); + + $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration(); + + $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily(); + + // this could use specialized code + $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum( + array( + 'normal', + 'bold', + 'bolder', + 'lighter', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900' + ), + false + ); + + // MUST be called after other font properties, as it references + // a CSSDefinition object + $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config); + + // same here + $this->info['border'] = + $this->info['border-bottom'] = + $this->info['border-top'] = + $this->info['border-left'] = + $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config); + + $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum( + array('collapse', 'separate') + ); + + $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum( + array('top', 'bottom') + ); + + $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum( + array('auto', 'fixed') + ); + + $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Enum( + array( + 'baseline', + 'sub', + 'super', + 'top', + 'text-top', + 'middle', + 'bottom', + 'text-bottom' + ) + ), + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage() + ) + ); + + $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2); + + // These CSS properties don't work on many browsers, but we live + // in THE FUTURE! + $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum( + array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line') + ); + + if ($config->get('CSS.Proprietary')) { + $this->doSetupProprietary($config); + } + + if ($config->get('CSS.AllowTricky')) { + $this->doSetupTricky($config); + } + + if ($config->get('CSS.Trusted')) { + $this->doSetupTrusted($config); + } + + $allow_important = $config->get('CSS.AllowImportant'); + // wrap all attr-defs with decorator that handles !important + foreach ($this->info as $k => $v) { + $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important); + } + + $this->setupConfigStuff($config); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupProprietary($config) + { + // Internet Explorer only scrollbar colors + $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color(); + + // vendor specific prefixes of opacity + $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + + // only opacity, for now + $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter(); + + // more CSS3 + $this->info['page-break-after'] = + $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum( + array( + 'auto', + 'always', + 'avoid', + 'left', + 'right' + ) + ); + $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid')); + + $border_radius = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Percentage(true), // disallow negative + new HTMLPurifier_AttrDef_CSS_Length('0') // disallow negative + )); + + $this->info['border-top-left-radius'] = + $this->info['border-top-right-radius'] = + $this->info['border-bottom-right-radius'] = + $this->info['border-bottom-left-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 2); + // TODO: support SLASH syntax + $this->info['border-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 4); + + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTricky($config) + { + $this->info['display'] = new HTMLPurifier_AttrDef_Enum( + array( + 'inline', + 'block', + 'list-item', + 'run-in', + 'compact', + 'marker', + 'table', + 'inline-block', + 'inline-table', + 'table-row-group', + 'table-header-group', + 'table-footer-group', + 'table-row', + 'table-column-group', + 'table-column', + 'table-cell', + 'table-caption', + 'none' + ) + ); + $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum( + array('visible', 'hidden', 'collapse') + ); + $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll')); + $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue(); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetupTrusted($config) + { + $this->info['position'] = new HTMLPurifier_AttrDef_Enum( + array('static', 'relative', 'absolute', 'fixed') + ); + $this->info['top'] = + $this->info['left'] = + $this->info['right'] = + $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_CSS_Length(), + new HTMLPurifier_AttrDef_CSS_Percentage(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite( + array( + new HTMLPurifier_AttrDef_Integer(), + new HTMLPurifier_AttrDef_Enum(array('auto')), + ) + ); + } + + /** + * Performs extra config-based processing. Based off of + * HTMLPurifier_HTMLDefinition. + * @param HTMLPurifier_Config $config + * @todo Refactor duplicate elements into common class (probably using + * composition, not inheritance). + */ + protected function setupConfigStuff($config) + { + // setup allowed elements + $support = "(for information on implementing this, see the " . + "support forums) "; + $allowed_properties = $config->get('CSS.AllowedProperties'); + if ($allowed_properties !== null) { + foreach ($this->info as $name => $d) { + if (!isset($allowed_properties[$name])) { + unset($this->info[$name]); + } + unset($allowed_properties[$name]); + } + // emit errors + foreach ($allowed_properties as $name => $d) { + // :TODO: Is this htmlspecialchars() call really necessary? + $name = htmlspecialchars($name); + trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING); + } + } + + $forbidden_properties = $config->get('CSS.ForbiddenProperties'); + if ($forbidden_properties !== null) { + foreach ($this->info as $name => $d) { + if (isset($forbidden_properties[$name])) { + unset($this->info[$name]); + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef.php new file mode 100644 index 00000000..8eb17b82 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef.php @@ -0,0 +1,52 @@ +elements; + } + + /** + * Validates nodes according to definition and returns modification. + * + * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node + * @param HTMLPurifier_Config $config HTMLPurifier_Config object + * @param HTMLPurifier_Context $context HTMLPurifier_Context object + * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children + */ + abstract public function validateChildren($children, $config, $context); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Chameleon.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Chameleon.php new file mode 100644 index 00000000..7439be26 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Chameleon.php @@ -0,0 +1,67 @@ +inline = new HTMLPurifier_ChildDef_Optional($inline); + $this->block = new HTMLPurifier_ChildDef_Optional($block); + $this->elements = $this->block->elements; + } + + /** + * @param HTMLPurifier_Node[] $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function validateChildren($children, $config, $context) + { + if ($context->get('IsInline') === false) { + return $this->block->validateChildren( + $children, + $config, + $context + ); + } else { + return $this->inline->validateChildren( + $children, + $config, + $context + ); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Custom.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Custom.php new file mode 100644 index 00000000..f515888a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Custom.php @@ -0,0 +1,102 @@ +dtd_regex = $dtd_regex; + $this->_compileRegex(); + } + + /** + * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex) + */ + protected function _compileRegex() + { + $raw = str_replace(' ', '', $this->dtd_regex); + if ($raw[0] != '(') { + $raw = "($raw)"; + } + $el = '[#a-zA-Z0-9_.-]+'; + $reg = $raw; + + // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M + // DOING! Seriously: if there's problems, please report them. + + // collect all elements into the $elements array + preg_match_all("/$el/", $reg, $matches); + foreach ($matches[0] as $match) { + $this->elements[$match] = true; + } + + // setup all elements as parentheticals with leading commas + $reg = preg_replace("/$el/", '(,\\0)', $reg); + + // remove commas when they were not solicited + $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg); + + // remove all non-paranthetical commas: they are handled by first regex + $reg = preg_replace("/,\(/", '(', $reg); + + $this->_pcre_regex = $reg; + } + + /** + * @param HTMLPurifier_Node[] $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function validateChildren($children, $config, $context) + { + $list_of_children = ''; + $nesting = 0; // depth into the nest + foreach ($children as $node) { + if (!empty($node->is_whitespace)) { + continue; + } + $list_of_children .= $node->name . ','; + } + // add leading comma to deal with stray comma declarations + $list_of_children = ',' . rtrim($list_of_children, ','); + $okay = + preg_match( + '/^,?' . $this->_pcre_regex . '$/', + $list_of_children + ); + return (bool)$okay; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Empty.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Empty.php new file mode 100644 index 00000000..a8a6cbdd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Empty.php @@ -0,0 +1,38 @@ + true, 'ul' => true, 'ol' => true); + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + // Flag for subclasses + $this->whitespace = false; + + // if there are no tokens, delete parent node + if (empty($children)) { + return false; + } + + // if li is not allowed, delete parent node + if (!isset($config->getHTMLDefinition()->info['li'])) { + trigger_error("Cannot allow ul/ol without allowing li", E_USER_WARNING); + return false; + } + + // the new set of children + $result = array(); + + // a little sanity check to make sure it's not ALL whitespace + $all_whitespace = true; + + $current_li = null; + + foreach ($children as $node) { + if (!empty($node->is_whitespace)) { + $result[] = $node; + continue; + } + $all_whitespace = false; // phew, we're not talking about whitespace + + if ($node->name === 'li') { + // good + $current_li = $node; + $result[] = $node; + } else { + // we want to tuck this into the previous li + // Invariant: we expect the node to be ol/ul + // ToDo: Make this more robust in the case of not ol/ul + // by distinguishing between existing li and li created + // to handle non-list elements; non-list elements should + // not be appended to an existing li; only li created + // for non-list. This distinction is not currently made. + if ($current_li === null) { + $current_li = new HTMLPurifier_Node_Element('li'); + $result[] = $current_li; + } + $current_li->children[] = $node; + $current_li->empty = false; // XXX fascinating! Check for this error elsewhere ToDo + } + } + if (empty($result)) { + return false; + } + if ($all_whitespace) { + return false; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Optional.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Optional.php new file mode 100644 index 00000000..b9468063 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Optional.php @@ -0,0 +1,45 @@ +whitespace) { + return $children; + } else { + return array(); + } + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Required.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Required.php new file mode 100644 index 00000000..0d1c8f5f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Required.php @@ -0,0 +1,118 @@ + $x) { + $elements[$i] = true; + if (empty($i)) { + unset($elements[$i]); + } // remove blank + } + } + $this->elements = $elements; + } + + /** + * @type bool + */ + public $allow_empty = false; + + /** + * @type string + */ + public $type = 'required'; + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + // Flag for subclasses + $this->whitespace = false; + + // if there are no tokens, delete parent node + if (empty($children)) { + return false; + } + + // the new set of children + $result = array(); + + // whether or not parsed character data is allowed + // this controls whether or not we silently drop a tag + // or generate escaped HTML from it + $pcdata_allowed = isset($this->elements['#PCDATA']); + + // a little sanity check to make sure it's not ALL whitespace + $all_whitespace = true; + + $stack = array_reverse($children); + while (!empty($stack)) { + $node = array_pop($stack); + if (!empty($node->is_whitespace)) { + $result[] = $node; + continue; + } + $all_whitespace = false; // phew, we're not talking about whitespace + + if (!isset($this->elements[$node->name])) { + // special case text + // XXX One of these ought to be redundant or something + if ($pcdata_allowed && $node instanceof HTMLPurifier_Node_Text) { + $result[] = $node; + continue; + } + // spill the child contents in + // ToDo: Make configurable + if ($node instanceof HTMLPurifier_Node_Element) { + for ($i = count($node->children) - 1; $i >= 0; $i--) { + $stack[] = $node->children[$i]; + } + continue; + } + continue; + } + $result[] = $node; + } + if (empty($result)) { + return false; + } + if ($all_whitespace) { + $this->whitespace = true; + return false; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/StrictBlockquote.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/StrictBlockquote.php new file mode 100644 index 00000000..3270a46e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/StrictBlockquote.php @@ -0,0 +1,110 @@ +init($config); + return $this->fake_elements; + } + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + $this->init($config); + + // trick the parent class into thinking it allows more + $this->elements = $this->fake_elements; + $result = parent::validateChildren($children, $config, $context); + $this->elements = $this->real_elements; + + if ($result === false) { + return array(); + } + if ($result === true) { + $result = $children; + } + + $def = $config->getHTMLDefinition(); + $block_wrap_name = $def->info_block_wrapper; + $block_wrap = false; + $ret = array(); + + foreach ($result as $node) { + if ($block_wrap === false) { + if (($node instanceof HTMLPurifier_Node_Text && !$node->is_whitespace) || + ($node instanceof HTMLPurifier_Node_Element && !isset($this->elements[$node->name]))) { + $block_wrap = new HTMLPurifier_Node_Element($def->info_block_wrapper); + $ret[] = $block_wrap; + } + } else { + if ($node instanceof HTMLPurifier_Node_Element && isset($this->elements[$node->name])) { + $block_wrap = false; + + } + } + if ($block_wrap) { + $block_wrap->children[] = $node; + } else { + $ret[] = $node; + } + } + return $ret; + } + + /** + * @param HTMLPurifier_Config $config + */ + private function init($config) + { + if (!$this->init) { + $def = $config->getHTMLDefinition(); + // allow all inline elements + $this->real_elements = $this->elements; + $this->fake_elements = $def->info_content_sets['Flow']; + $this->fake_elements['#PCDATA'] = true; + $this->init = true; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Table.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Table.php new file mode 100644 index 00000000..67c7e953 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ChildDef/Table.php @@ -0,0 +1,224 @@ + true, + 'tbody' => true, + 'thead' => true, + 'tfoot' => true, + 'caption' => true, + 'colgroup' => true, + 'col' => true + ); + + public function __construct() + { + } + + /** + * @param array $children + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array + */ + public function validateChildren($children, $config, $context) + { + if (empty($children)) { + return false; + } + + // only one of these elements is allowed in a table + $caption = false; + $thead = false; + $tfoot = false; + + // whitespace + $initial_ws = array(); + $after_caption_ws = array(); + $after_thead_ws = array(); + $after_tfoot_ws = array(); + + // as many of these as you want + $cols = array(); + $content = array(); + + $tbody_mode = false; // if true, then we need to wrap any stray + // s with a . + + $ws_accum =& $initial_ws; + + foreach ($children as $node) { + if ($node instanceof HTMLPurifier_Node_Comment) { + $ws_accum[] = $node; + continue; + } + switch ($node->name) { + case 'tbody': + $tbody_mode = true; + // fall through + case 'tr': + $content[] = $node; + $ws_accum =& $content; + break; + case 'caption': + // there can only be one caption! + if ($caption !== false) break; + $caption = $node; + $ws_accum =& $after_caption_ws; + break; + case 'thead': + $tbody_mode = true; + // XXX This breaks rendering properties with + // Firefox, which never floats a to + // the top. Ever. (Our scheme will float the + // first to the top.) So maybe + // s that are not first should be + // turned into ? Very tricky, indeed. + if ($thead === false) { + $thead = $node; + $ws_accum =& $after_thead_ws; + } else { + // Oops, there's a second one! What + // should we do? Current behavior is to + // transmutate the first and last entries into + // tbody tags, and then put into content. + // Maybe a better idea is to *attach + // it* to the existing thead or tfoot? + // We don't do this, because Firefox + // doesn't float an extra tfoot to the + // bottom like it does for the first one. + $node->name = 'tbody'; + $content[] = $node; + $ws_accum =& $content; + } + break; + case 'tfoot': + // see above for some aveats + $tbody_mode = true; + if ($tfoot === false) { + $tfoot = $node; + $ws_accum =& $after_tfoot_ws; + } else { + $node->name = 'tbody'; + $content[] = $node; + $ws_accum =& $content; + } + break; + case 'colgroup': + case 'col': + $cols[] = $node; + $ws_accum =& $cols; + break; + case '#PCDATA': + // How is whitespace handled? We treat is as sticky to + // the *end* of the previous element. So all of the + // nonsense we have worked on is to keep things + // together. + if (!empty($node->is_whitespace)) { + $ws_accum[] = $node; + } + break; + } + } + + if (empty($content) && $thead === false && $tfoot === false) { + return false; + } + + $ret = $initial_ws; + if ($caption !== false) { + $ret[] = $caption; + $ret = array_merge($ret, $after_caption_ws); + } + if ($cols !== false) { + $ret = array_merge($ret, $cols); + } + if ($thead !== false) { + $ret[] = $thead; + $ret = array_merge($ret, $after_thead_ws); + } + if ($tfoot !== false) { + $ret[] = $tfoot; + $ret = array_merge($ret, $after_tfoot_ws); + } + + if ($tbody_mode) { + // we have to shuffle tr into tbody + $current_tr_tbody = null; + + foreach($content as $node) { + switch ($node->name) { + case 'tbody': + $current_tr_tbody = null; + $ret[] = $node; + break; + case 'tr': + if ($current_tr_tbody === null) { + $current_tr_tbody = new HTMLPurifier_Node_Element('tbody'); + $ret[] = $current_tr_tbody; + } + $current_tr_tbody->children[] = $node; + break; + case '#PCDATA': + //assert($node->is_whitespace); + if ($current_tr_tbody === null) { + $ret[] = $node; + } else { + $current_tr_tbody->children[] = $node; + } + break; + } + } + } else { + $ret = array_merge($ret, $content); + } + + return $ret; + + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Config.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Config.php new file mode 100644 index 00000000..16a6b322 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Config.php @@ -0,0 +1,920 @@ +defaultPlist; + $this->plist = new HTMLPurifier_PropertyList($parent); + $this->def = $definition; // keep a copy around for checking + $this->parser = new HTMLPurifier_VarParser_Flexible(); + } + + /** + * Convenience constructor that creates a config object based on a mixed var + * @param mixed $config Variable that defines the state of the config + * object. Can be: a HTMLPurifier_Config() object, + * an array of directives based on loadArray(), + * or a string filename of an ini file. + * @param HTMLPurifier_ConfigSchema $schema Schema object + * @return HTMLPurifier_Config Configured object + */ + public static function create($config, $schema = null) + { + if ($config instanceof HTMLPurifier_Config) { + // pass-through + return $config; + } + if (!$schema) { + $ret = HTMLPurifier_Config::createDefault(); + } else { + $ret = new HTMLPurifier_Config($schema); + } + if (is_string($config)) { + $ret->loadIni($config); + } elseif (is_array($config)) $ret->loadArray($config); + return $ret; + } + + /** + * Creates a new config object that inherits from a previous one. + * @param HTMLPurifier_Config $config Configuration object to inherit from. + * @return HTMLPurifier_Config object with $config as its parent. + */ + public static function inherit(HTMLPurifier_Config $config) + { + return new HTMLPurifier_Config($config->def, $config->plist); + } + + /** + * Convenience constructor that creates a default configuration object. + * @return HTMLPurifier_Config default object. + */ + public static function createDefault() + { + $definition = HTMLPurifier_ConfigSchema::instance(); + $config = new HTMLPurifier_Config($definition); + return $config; + } + + /** + * Retrieves a value from the configuration. + * + * @param string $key String key + * @param mixed $a + * + * @return mixed + */ + public function get($key, $a = null) + { + if ($a !== null) { + $this->triggerError( + "Using deprecated API: use \$config->get('$key.$a') instead", + E_USER_WARNING + ); + $key = "$key.$a"; + } + if (!$this->finalized) { + $this->autoFinalize(); + } + if (!isset($this->def->info[$key])) { + // can't add % due to SimpleTest bug + $this->triggerError( + 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key), + E_USER_WARNING + ); + return; + } + if (isset($this->def->info[$key]->isAlias)) { + $d = $this->def->info[$key]; + $this->triggerError( + 'Cannot get value from aliased directive, use real name ' . $d->key, + E_USER_ERROR + ); + return; + } + if ($this->lock) { + list($ns) = explode('.', $key); + if ($ns !== $this->lock) { + $this->triggerError( + 'Cannot get value of namespace ' . $ns . ' when lock for ' . + $this->lock . + ' is active, this probably indicates a Definition setup method ' . + 'is accessing directives that are not within its namespace', + E_USER_ERROR + ); + return; + } + } + return $this->plist->get($key); + } + + /** + * Retrieves an array of directives to values from a given namespace + * + * @param string $namespace String namespace + * + * @return array + */ + public function getBatch($namespace) + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $full = $this->getAll(); + if (!isset($full[$namespace])) { + $this->triggerError( + 'Cannot retrieve undefined namespace ' . + htmlspecialchars($namespace), + E_USER_WARNING + ); + return; + } + return $full[$namespace]; + } + + /** + * Returns a SHA-1 signature of a segment of the configuration object + * that uniquely identifies that particular configuration + * + * @param string $namespace Namespace to get serial for + * + * @return string + * @note Revision is handled specially and is removed from the batch + * before processing! + */ + public function getBatchSerial($namespace) + { + if (empty($this->serials[$namespace])) { + $batch = $this->getBatch($namespace); + unset($batch['DefinitionRev']); + $this->serials[$namespace] = sha1(serialize($batch)); + } + return $this->serials[$namespace]; + } + + /** + * Returns a SHA-1 signature for the entire configuration object + * that uniquely identifies that particular configuration + * + * @return string + */ + public function getSerial() + { + if (empty($this->serial)) { + $this->serial = sha1(serialize($this->getAll())); + } + return $this->serial; + } + + /** + * Retrieves all directives, organized by namespace + * + * @warning This is a pretty inefficient function, avoid if you can + */ + public function getAll() + { + if (!$this->finalized) { + $this->autoFinalize(); + } + $ret = array(); + foreach ($this->plist->squash() as $name => $value) { + list($ns, $key) = explode('.', $name, 2); + $ret[$ns][$key] = $value; + } + return $ret; + } + + /** + * Sets a value to configuration. + * + * @param string $key key + * @param mixed $value value + * @param mixed $a + */ + public function set($key, $value, $a = null) + { + if (strpos($key, '.') === false) { + $namespace = $key; + $directive = $value; + $value = $a; + $key = "$key.$directive"; + $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE); + } else { + list($namespace) = explode('.', $key); + } + if ($this->isFinalized('Cannot set directive after finalization')) { + return; + } + if (!isset($this->def->info[$key])) { + $this->triggerError( + 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value', + E_USER_WARNING + ); + return; + } + $def = $this->def->info[$key]; + + if (isset($def->isAlias)) { + if ($this->aliasMode) { + $this->triggerError( + 'Double-aliases not allowed, please fix '. + 'ConfigSchema bug with' . $key, + E_USER_ERROR + ); + return; + } + $this->aliasMode = true; + $this->set($def->key, $value); + $this->aliasMode = false; + $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE); + return; + } + + // Raw type might be negative when using the fully optimized form + // of stdClass, which indicates allow_null == true + $rtype = is_int($def) ? $def : $def->type; + if ($rtype < 0) { + $type = -$rtype; + $allow_null = true; + } else { + $type = $rtype; + $allow_null = isset($def->allow_null); + } + + try { + $value = $this->parser->parse($value, $type, $allow_null); + } catch (HTMLPurifier_VarParserException $e) { + $this->triggerError( + 'Value for ' . $key . ' is of invalid type, should be ' . + HTMLPurifier_VarParser::getTypeName($type), + E_USER_WARNING + ); + return; + } + if (is_string($value) && is_object($def)) { + // resolve value alias if defined + if (isset($def->aliases[$value])) { + $value = $def->aliases[$value]; + } + // check to see if the value is allowed + if (isset($def->allowed) && !isset($def->allowed[$value])) { + $this->triggerError( + 'Value not supported, valid values are: ' . + $this->_listify($def->allowed), + E_USER_WARNING + ); + return; + } + } + $this->plist->set($key, $value); + + // reset definitions if the directives they depend on changed + // this is a very costly process, so it's discouraged + // with finalization + if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') { + $this->definitions[$namespace] = null; + } + + $this->serials[$namespace] = false; + } + + /** + * Convenience function for error reporting + * + * @param array $lookup + * + * @return string + */ + private function _listify($lookup) + { + $list = array(); + foreach ($lookup as $name => $b) { + $list[] = $name; + } + return implode(', ', $list); + } + + /** + * Retrieves object reference to the HTML definition. + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawHTMLDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_HTMLDefinition|null + */ + public function getHTMLDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('HTML', $raw, $optimized); + } + + /** + * Retrieves object reference to the CSS definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawCSSDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_CSSDefinition|null + */ + public function getCSSDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('CSS', $raw, $optimized); + } + + /** + * Retrieves object reference to the URI definition + * + * @param bool $raw Return a copy that has not been setup yet. Must be + * called before it's been setup, otherwise won't work. + * @param bool $optimized If true, this method may return null, to + * indicate that a cached version of the modified + * definition object is available and no further edits + * are necessary. Consider using + * maybeGetRawURIDefinition, which is more explicitly + * named, instead. + * + * @return HTMLPurifier_URIDefinition|null + */ + public function getURIDefinition($raw = false, $optimized = false) + { + return $this->getDefinition('URI', $raw, $optimized); + } + + /** + * Retrieves a definition + * + * @param string $type Type of definition: HTML, CSS, etc + * @param bool $raw Whether or not definition should be returned raw + * @param bool $optimized Only has an effect when $raw is true. Whether + * or not to return null if the result is already present in + * the cache. This is off by default for backwards + * compatibility reasons, but you need to do things this + * way in order to ensure that caching is done properly. + * Check out enduser-customize.html for more details. + * We probably won't ever change this default, as much as the + * maybe semantics is the "right thing to do." + * + * @throws HTMLPurifier_Exception + * @return HTMLPurifier_Definition|null + */ + public function getDefinition($type, $raw = false, $optimized = false) + { + if ($optimized && !$raw) { + throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false"); + } + if (!$this->finalized) { + $this->autoFinalize(); + } + // temporarily suspend locks, so we can handle recursive definition calls + $lock = $this->lock; + $this->lock = null; + $factory = HTMLPurifier_DefinitionCacheFactory::instance(); + $cache = $factory->create($type, $this); + $this->lock = $lock; + if (!$raw) { + // full definition + // --------------- + // check if definition is in memory + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + // check if the definition is setup + if ($def->setup) { + return $def; + } else { + $def->setup($this); + if ($def->optimized) { + $cache->add($def, $this); + } + return $def; + } + } + // check if definition is in cache + $def = $cache->get($this); + if ($def) { + // definition in cache, save to memory and return it + $this->definitions[$type] = $def; + return $def; + } + // initialize it + $def = $this->initDefinition($type); + // set it up + $this->lock = $type; + $def->setup($this); + $this->lock = null; + // save in cache + $cache->add($def, $this); + // return it + return $def; + } else { + // raw definition + // -------------- + // check preconditions + $def = null; + if ($optimized) { + if (is_null($this->get($type . '.DefinitionID'))) { + // fatally error out if definition ID not set + throw new HTMLPurifier_Exception( + "Cannot retrieve raw version without specifying %$type.DefinitionID" + ); + } + } + if (!empty($this->definitions[$type])) { + $def = $this->definitions[$type]; + if ($def->setup && !$optimized) { + $extra = $this->chatty ? + " (try moving this code block earlier in your initialization)" : + ""; + throw new HTMLPurifier_Exception( + "Cannot retrieve raw definition after it has already been setup" . + $extra + ); + } + if ($def->optimized === null) { + $extra = $this->chatty ? " (try flushing your cache)" : ""; + throw new HTMLPurifier_Exception( + "Optimization status of definition is unknown" . $extra + ); + } + if ($def->optimized !== $optimized) { + $msg = $optimized ? "optimized" : "unoptimized"; + $extra = $this->chatty ? + " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)" + : ""; + throw new HTMLPurifier_Exception( + "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra + ); + } + } + // check if definition was in memory + if ($def) { + if ($def->setup) { + // invariant: $optimized === true (checked above) + return null; + } else { + return $def; + } + } + // if optimized, check if definition was in cache + // (because we do the memory check first, this formulation + // is prone to cache slamming, but I think + // guaranteeing that either /all/ of the raw + // setup code or /none/ of it is run is more important.) + if ($optimized) { + // This code path only gets run once; once we put + // something in $definitions (which is guaranteed by the + // trailing code), we always short-circuit above. + $def = $cache->get($this); + if ($def) { + // save the full definition for later, but don't + // return it yet + $this->definitions[$type] = $def; + return null; + } + } + // check invariants for creation + if (!$optimized) { + if (!is_null($this->get($type . '.DefinitionID'))) { + if ($this->chatty) { + $this->triggerError( + 'Due to a documentation error in previous version of HTML Purifier, your ' . + 'definitions are not being cached. If this is OK, you can remove the ' . + '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' . + 'modify your code to use maybeGetRawDefinition, and test if the returned ' . + 'value is null before making any edits (if it is null, that means that a ' . + 'cached version is available, and no raw operations are necessary). See ' . + '' . + 'Customize for more details', + E_USER_WARNING + ); + } else { + $this->triggerError( + "Useless DefinitionID declaration", + E_USER_WARNING + ); + } + } + } + // initialize it + $def = $this->initDefinition($type); + $def->optimized = $optimized; + return $def; + } + throw new HTMLPurifier_Exception("The impossible happened!"); + } + + /** + * Initialise definition + * + * @param string $type What type of definition to create + * + * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition + * @throws HTMLPurifier_Exception + */ + private function initDefinition($type) + { + // quick checks failed, let's create the object + if ($type == 'HTML') { + $def = new HTMLPurifier_HTMLDefinition(); + } elseif ($type == 'CSS') { + $def = new HTMLPurifier_CSSDefinition(); + } elseif ($type == 'URI') { + $def = new HTMLPurifier_URIDefinition(); + } else { + throw new HTMLPurifier_Exception( + "Definition of $type type not supported" + ); + } + $this->definitions[$type] = $def; + return $def; + } + + public function maybeGetRawDefinition($name) + { + return $this->getDefinition($name, true, true); + } + + /** + * @return HTMLPurifier_HTMLDefinition|null + */ + public function maybeGetRawHTMLDefinition() + { + return $this->getDefinition('HTML', true, true); + } + + /** + * @return HTMLPurifier_CSSDefinition|null + */ + public function maybeGetRawCSSDefinition() + { + return $this->getDefinition('CSS', true, true); + } + + /** + * @return HTMLPurifier_URIDefinition|null + */ + public function maybeGetRawURIDefinition() + { + return $this->getDefinition('URI', true, true); + } + + /** + * Loads configuration values from an array with the following structure: + * Namespace.Directive => Value + * + * @param array $config_array Configuration associative array + */ + public function loadArray($config_array) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + foreach ($config_array as $key => $value) { + $key = str_replace('_', '.', $key); + if (strpos($key, '.') !== false) { + $this->set($key, $value); + } else { + $namespace = $key; + $namespace_values = $value; + foreach ($namespace_values as $directive => $value2) { + $this->set($namespace .'.'. $directive, $value2); + } + } + } + } + + /** + * Returns a list of array(namespace, directive) for all directives + * that are allowed in a web-form context as per an allowed + * namespaces/directives list. + * + * @param array $allowed List of allowed namespaces/directives + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function getAllowedDirectivesForForm($allowed, $schema = null) + { + if (!$schema) { + $schema = HTMLPurifier_ConfigSchema::instance(); + } + if ($allowed !== true) { + if (is_string($allowed)) { + $allowed = array($allowed); + } + $allowed_ns = array(); + $allowed_directives = array(); + $blacklisted_directives = array(); + foreach ($allowed as $ns_or_directive) { + if (strpos($ns_or_directive, '.') !== false) { + // directive + if ($ns_or_directive[0] == '-') { + $blacklisted_directives[substr($ns_or_directive, 1)] = true; + } else { + $allowed_directives[$ns_or_directive] = true; + } + } else { + // namespace + $allowed_ns[$ns_or_directive] = true; + } + } + } + $ret = array(); + foreach ($schema->info as $key => $def) { + list($ns, $directive) = explode('.', $key, 2); + if ($allowed !== true) { + if (isset($blacklisted_directives["$ns.$directive"])) { + continue; + } + if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) { + continue; + } + } + if (isset($def->isAlias)) { + continue; + } + if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') { + continue; + } + $ret[] = array($ns, $directive); + } + return $ret; + } + + /** + * Loads configuration values from $_GET/$_POST that were posted + * via ConfigForm + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return mixed + */ + public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema); + $config = HTMLPurifier_Config::create($ret, $schema); + return $config; + } + + /** + * Merges in configuration values from $_GET/$_POST to object. NOT STATIC. + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + */ + public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true) + { + $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def); + $this->loadArray($ret); + } + + /** + * Prepares an array from a form into something usable for the more + * strict parts of HTMLPurifier_Config + * + * @param array $array $_GET or $_POST array to import + * @param string|bool $index Index/name that the config variables are in + * @param array|bool $allowed List of allowed namespaces/directives + * @param bool $mq_fix Boolean whether or not to enable magic quotes fix + * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy + * + * @return array + */ + public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null) + { + if ($index !== false) { + $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array(); + } + $mq = $mq_fix && version_compare(PHP_VERSION, '7.4.0', '<') && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc(); + + $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema); + $ret = array(); + foreach ($allowed as $key) { + list($ns, $directive) = $key; + $skey = "$ns.$directive"; + if (!empty($array["Null_$skey"])) { + $ret[$ns][$directive] = null; + continue; + } + if (!isset($array[$skey])) { + continue; + } + $value = $mq ? stripslashes($array[$skey]) : $array[$skey]; + $ret[$ns][$directive] = $value; + } + return $ret; + } + + /** + * Loads configuration values from an ini file + * + * @param string $filename Name of ini file + */ + public function loadIni($filename) + { + if ($this->isFinalized('Cannot load directives after finalization')) { + return; + } + $array = parse_ini_file($filename, true); + $this->loadArray($array); + } + + /** + * Checks whether or not the configuration object is finalized. + * + * @param string|bool $error String error message, or false for no error + * + * @return bool + */ + public function isFinalized($error = false) + { + if ($this->finalized && $error) { + $this->triggerError($error, E_USER_ERROR); + } + return $this->finalized; + } + + /** + * Finalizes configuration only if auto finalize is on and not + * already finalized + */ + public function autoFinalize() + { + if ($this->autoFinalize) { + $this->finalize(); + } else { + $this->plist->squash(true); + } + } + + /** + * Finalizes a configuration object, prohibiting further change + */ + public function finalize() + { + $this->finalized = true; + $this->parser = null; + } + + /** + * Produces a nicely formatted error message by supplying the + * stack frame information OUTSIDE of HTMLPurifier_Config. + * + * @param string $msg An error message + * @param int $no An error number + */ + protected function triggerError($msg, $no) + { + // determine previous stack frame + $extra = ''; + if ($this->chatty) { + $trace = debug_backtrace(); + // zip(tail(trace), trace) -- but PHP is not Haskell har har + for ($i = 0, $c = count($trace); $i < $c - 1; $i++) { + // XXX this is not correct on some versions of HTML Purifier + if (isset($trace[$i + 1]['class']) && $trace[$i + 1]['class'] === 'HTMLPurifier_Config') { + continue; + } + $frame = $trace[$i]; + $extra = " invoked on line {$frame['line']} in file {$frame['file']}"; + break; + } + } + trigger_error($msg . $extra, $no); + } + + /** + * Returns a serialized form of the configuration object that can + * be reconstituted. + * + * @return string + */ + public function serialize() + { + $this->getDefinition('HTML'); + $this->getDefinition('CSS'); + $this->getDefinition('URI'); + return serialize($this); + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema.php new file mode 100644 index 00000000..c3fe8cd4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema.php @@ -0,0 +1,176 @@ + array( + * 'Directive' => new stdClass(), + * ) + * ) + * + * The stdClass may have the following properties: + * + * - If isAlias isn't set: + * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions + * - allow_null: If set, this directive allows null values + * - aliases: If set, an associative array of value aliases to real values + * - allowed: If set, a lookup array of allowed (string) values + * - If isAlias is set: + * - namespace: Namespace this directive aliases to + * - name: Directive name this directive aliases to + * + * In certain degenerate cases, stdClass will actually be an integer. In + * that case, the value is equivalent to an stdClass with the type + * property set to the integer. If the integer is negative, type is + * equal to the absolute value of integer, and allow_null is true. + * + * This class is friendly with HTMLPurifier_Config. If you need introspection + * about the schema, you're better of using the ConfigSchema_Interchange, + * which uses more memory but has much richer information. + * @type array + */ + public $info = array(); + + /** + * Application-wide singleton + * @type HTMLPurifier_ConfigSchema + */ + protected static $singleton; + + public function __construct() + { + $this->defaultPlist = new HTMLPurifier_PropertyList(); + } + + /** + * Unserializes the default ConfigSchema. + * @return HTMLPurifier_ConfigSchema + */ + public static function makeFromSerial() + { + $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser'); + $r = unserialize($contents); + if (!$r) { + $hash = sha1($contents); + trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR); + } + return $r; + } + + /** + * Retrieves an instance of the application-wide configuration definition. + * @param HTMLPurifier_ConfigSchema $prototype + * @return HTMLPurifier_ConfigSchema + */ + public static function instance($prototype = null) + { + if ($prototype !== null) { + HTMLPurifier_ConfigSchema::$singleton = $prototype; + } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) { + HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial(); + } + return HTMLPurifier_ConfigSchema::$singleton; + } + + /** + * Defines a directive for configuration + * @warning Will fail of directive's namespace is defined. + * @warning This method's signature is slightly different from the legacy + * define() static method! Beware! + * @param string $key Name of directive + * @param mixed $default Default value of directive + * @param string $type Allowed type of the directive. See + * HTMLPurifier_VarParser::$types for allowed values + * @param bool $allow_null Whether or not to allow null values + */ + public function add($key, $default, $type, $allow_null) + { + $obj = new stdClass(); + $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type]; + if ($allow_null) { + $obj->allow_null = true; + } + $this->info[$key] = $obj; + $this->defaults[$key] = $default; + $this->defaultPlist->set($key, $default); + } + + /** + * Defines a directive value alias. + * + * Directive value aliases are convenient for developers because it lets + * them set a directive to several values and get the same result. + * @param string $key Name of Directive + * @param array $aliases Hash of aliased values to the real alias + */ + public function addValueAliases($key, $aliases) + { + if (!isset($this->info[$key]->aliases)) { + $this->info[$key]->aliases = array(); + } + foreach ($aliases as $alias => $real) { + $this->info[$key]->aliases[$alias] = $real; + } + } + + /** + * Defines a set of allowed values for a directive. + * @warning This is slightly different from the corresponding static + * method definition. + * @param string $key Name of directive + * @param array $allowed Lookup array of allowed values + */ + public function addAllowedValues($key, $allowed) + { + $this->info[$key]->allowed = $allowed; + } + + /** + * Defines a directive alias for backwards compatibility + * @param string $key Directive that will be aliased + * @param string $new_key Directive that the alias will be to + */ + public function addAlias($key, $new_key) + { + $obj = new stdClass; + $obj->key = $new_key; + $obj->isAlias = true; + $this->info[$key] = $obj; + } + + /** + * Replaces any stdClass that only has the type property with type integer. + */ + public function postProcess() + { + foreach ($this->info as $key => $v) { + if (count((array) $v) == 1) { + $this->info[$key] = $v->type; + } elseif (count((array) $v) == 2 && isset($v->allow_null)) { + $this->info[$key] = -$v->type; + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php new file mode 100644 index 00000000..d5906cd4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/ConfigSchema.php @@ -0,0 +1,48 @@ +directives as $d) { + $schema->add( + $d->id->key, + $d->default, + $d->type, + $d->typeAllowsNull + ); + if ($d->allowed !== null) { + $schema->addAllowedValues( + $d->id->key, + $d->allowed + ); + } + foreach ($d->aliases as $alias) { + $schema->addAlias( + $alias->key, + $d->id->key + ); + } + if ($d->valueAliases !== null) { + $schema->addValueAliases( + $d->id->key, + $d->valueAliases + ); + } + } + $schema->postProcess(); + return $schema; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/Xml.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/Xml.php new file mode 100644 index 00000000..5fa56f7d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Builder/Xml.php @@ -0,0 +1,144 @@ +startElement('div'); + + $purifier = HTMLPurifier::getInstance(); + $html = $purifier->purify($html); + $this->writeAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); + $this->writeRaw($html); + + $this->endElement(); // div + } + + /** + * @param mixed $var + * @return string + */ + protected function export($var) + { + if ($var === array()) { + return 'array()'; + } + return var_export($var, true); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + */ + public function build($interchange) + { + // global access, only use as last resort + $this->interchange = $interchange; + + $this->setIndent(true); + $this->startDocument('1.0', 'UTF-8'); + $this->startElement('configdoc'); + $this->writeElement('title', $interchange->name); + + foreach ($interchange->directives as $directive) { + $this->buildDirective($directive); + } + + if ($this->namespace) { + $this->endElement(); + } // namespace + + $this->endElement(); // configdoc + $this->flush(); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive + */ + public function buildDirective($directive) + { + // Kludge, although I suppose having a notion of a "root namespace" + // certainly makes things look nicer when documentation is built. + // Depends on things being sorted. + if (!$this->namespace || $this->namespace !== $directive->id->getRootNamespace()) { + if ($this->namespace) { + $this->endElement(); + } // namespace + $this->namespace = $directive->id->getRootNamespace(); + $this->startElement('namespace'); + $this->writeAttribute('id', $this->namespace); + $this->writeElement('name', $this->namespace); + } + + $this->startElement('directive'); + $this->writeAttribute('id', $directive->id->toString()); + + $this->writeElement('name', $directive->id->getDirective()); + + $this->startElement('aliases'); + foreach ($directive->aliases as $alias) { + $this->writeElement('alias', $alias->toString()); + } + $this->endElement(); // aliases + + $this->startElement('constraints'); + if ($directive->version) { + $this->writeElement('version', $directive->version); + } + $this->startElement('type'); + if ($directive->typeAllowsNull) { + $this->writeAttribute('allow-null', 'yes'); + } + $this->text($directive->type); + $this->endElement(); // type + if ($directive->allowed) { + $this->startElement('allowed'); + foreach ($directive->allowed as $value => $x) { + $this->writeElement('value', $value); + } + $this->endElement(); // allowed + } + $this->writeElement('default', $this->export($directive->default)); + $this->writeAttribute('xml:space', 'preserve'); + if ($directive->external) { + $this->startElement('external'); + foreach ($directive->external as $project) { + $this->writeElement('project', $project); + } + $this->endElement(); + } + $this->endElement(); // constraints + + if ($directive->deprecatedVersion) { + $this->startElement('deprecated'); + $this->writeElement('version', $directive->deprecatedVersion); + $this->writeElement('use', $directive->deprecatedUse->toString()); + $this->endElement(); // deprecated + } + + $this->startElement('description'); + $this->writeHTMLDiv($directive->description); + $this->endElement(); // description + + $this->endElement(); // directive + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Exception.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Exception.php new file mode 100644 index 00000000..2671516c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Exception.php @@ -0,0 +1,11 @@ + array(directive info) + * @type HTMLPurifier_ConfigSchema_Interchange_Directive[] + */ + public $directives = array(); + + /** + * Adds a directive array to $directives + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $directive + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function addDirective($directive) + { + if (isset($this->directives[$i = $directive->id->toString()])) { + throw new HTMLPurifier_ConfigSchema_Exception("Cannot redefine directive '$i'"); + } + $this->directives[$i] = $directive; + } + + /** + * Convenience function to perform standard validation. Throws exception + * on failed validation. + */ + public function validate() + { + $validator = new HTMLPurifier_ConfigSchema_Validator(); + return $validator->validate($this); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php new file mode 100644 index 00000000..127a39a6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Directive.php @@ -0,0 +1,89 @@ + true). + * Null if all values are allowed. + * @type array + */ + public $allowed; + + /** + * List of aliases for the directive. + * e.g. array(new HTMLPurifier_ConfigSchema_Interchange_Id('Ns', 'Dir'))). + * @type HTMLPurifier_ConfigSchema_Interchange_Id[] + */ + public $aliases = array(); + + /** + * Hash of value aliases, e.g. array('alt' => 'real'). Null if value + * aliasing is disabled (necessary for non-scalar types). + * @type array + */ + public $valueAliases; + + /** + * Version of HTML Purifier the directive was introduced, e.g. '1.3.1'. + * Null if the directive has always existed. + * @type string + */ + public $version; + + /** + * ID of directive that supercedes this old directive. + * Null if not deprecated. + * @type HTMLPurifier_ConfigSchema_Interchange_Id + */ + public $deprecatedUse; + + /** + * Version of HTML Purifier this directive was deprecated. Null if not + * deprecated. + * @type string + */ + public $deprecatedVersion; + + /** + * List of external projects this directive depends on, e.g. array('CSSTidy'). + * @type array + */ + public $external = array(); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Id.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Id.php new file mode 100644 index 00000000..126f09d9 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Interchange/Id.php @@ -0,0 +1,58 @@ +key = $key; + } + + /** + * @return string + * @warning This is NOT magic, to ensure that people don't abuse SPL and + * cause problems for PHP 5.0 support. + */ + public function toString() + { + return $this->key; + } + + /** + * @return string + */ + public function getRootNamespace() + { + return substr($this->key, 0, strpos($this->key, ".")); + } + + /** + * @return string + */ + public function getDirective() + { + return substr($this->key, strpos($this->key, ".") + 1); + } + + /** + * @param string $id + * @return HTMLPurifier_ConfigSchema_Interchange_Id + */ + public static function make($id) + { + return new HTMLPurifier_ConfigSchema_Interchange_Id($id); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php new file mode 100644 index 00000000..655e6dd1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/InterchangeBuilder.php @@ -0,0 +1,226 @@ +varParser = $varParser ? $varParser : new HTMLPurifier_VarParser_Native(); + } + + /** + * @param string $dir + * @return HTMLPurifier_ConfigSchema_Interchange + */ + public static function buildFromDirectory($dir = null) + { + $builder = new HTMLPurifier_ConfigSchema_InterchangeBuilder(); + $interchange = new HTMLPurifier_ConfigSchema_Interchange(); + return $builder->buildDir($interchange, $dir); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param string $dir + * @return HTMLPurifier_ConfigSchema_Interchange + */ + public function buildDir($interchange, $dir = null) + { + if (!$dir) { + $dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema'; + } + if (file_exists($dir . '/info.ini')) { + $info = parse_ini_file($dir . '/info.ini'); + $interchange->name = $info['name']; + } + + $files = array(); + $dh = opendir($dir); + while (false !== ($file = readdir($dh))) { + if (!$file || $file[0] == '.' || strrchr($file, '.') !== '.txt') { + continue; + } + $files[] = $file; + } + closedir($dh); + + sort($files); + foreach ($files as $file) { + $this->buildFile($interchange, $dir . '/' . $file); + } + return $interchange; + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param string $file + */ + public function buildFile($interchange, $file) + { + $parser = new HTMLPurifier_StringHashParser(); + $this->build( + $interchange, + new HTMLPurifier_StringHash($parser->parseFile($file)) + ); + } + + /** + * Builds an interchange object based on a hash. + * @param HTMLPurifier_ConfigSchema_Interchange $interchange HTMLPurifier_ConfigSchema_Interchange object to build + * @param HTMLPurifier_StringHash $hash source data + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function build($interchange, $hash) + { + if (!$hash instanceof HTMLPurifier_StringHash) { + $hash = new HTMLPurifier_StringHash($hash); + } + if (!isset($hash['ID'])) { + throw new HTMLPurifier_ConfigSchema_Exception('Hash does not have any ID'); + } + if (strpos($hash['ID'], '.') === false) { + if (count($hash) == 2 && isset($hash['DESCRIPTION'])) { + $hash->offsetGet('DESCRIPTION'); // prevent complaining + } else { + throw new HTMLPurifier_ConfigSchema_Exception('All directives must have a namespace'); + } + } else { + $this->buildDirective($interchange, $hash); + } + $this->_findUnused($hash); + } + + /** + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @param HTMLPurifier_StringHash $hash + * @throws HTMLPurifier_ConfigSchema_Exception + */ + public function buildDirective($interchange, $hash) + { + $directive = new HTMLPurifier_ConfigSchema_Interchange_Directive(); + + // These are required elements: + $directive->id = $this->id($hash->offsetGet('ID')); + $id = $directive->id->toString(); // convenience + + if (isset($hash['TYPE'])) { + $type = explode('/', $hash->offsetGet('TYPE')); + if (isset($type[1])) { + $directive->typeAllowsNull = true; + } + $directive->type = $type[0]; + } else { + throw new HTMLPurifier_ConfigSchema_Exception("TYPE in directive hash '$id' not defined"); + } + + if (isset($hash['DEFAULT'])) { + try { + $directive->default = $this->varParser->parse( + $hash->offsetGet('DEFAULT'), + $directive->type, + $directive->typeAllowsNull + ); + } catch (HTMLPurifier_VarParserException $e) { + throw new HTMLPurifier_ConfigSchema_Exception($e->getMessage() . " in DEFAULT in directive hash '$id'"); + } + } + + if (isset($hash['DESCRIPTION'])) { + $directive->description = $hash->offsetGet('DESCRIPTION'); + } + + if (isset($hash['ALLOWED'])) { + $directive->allowed = $this->lookup($this->evalArray($hash->offsetGet('ALLOWED'))); + } + + if (isset($hash['VALUE-ALIASES'])) { + $directive->valueAliases = $this->evalArray($hash->offsetGet('VALUE-ALIASES')); + } + + if (isset($hash['ALIASES'])) { + $raw_aliases = trim($hash->offsetGet('ALIASES')); + $aliases = preg_split('/\s*,\s*/', $raw_aliases); + foreach ($aliases as $alias) { + $directive->aliases[] = $this->id($alias); + } + } + + if (isset($hash['VERSION'])) { + $directive->version = $hash->offsetGet('VERSION'); + } + + if (isset($hash['DEPRECATED-USE'])) { + $directive->deprecatedUse = $this->id($hash->offsetGet('DEPRECATED-USE')); + } + + if (isset($hash['DEPRECATED-VERSION'])) { + $directive->deprecatedVersion = $hash->offsetGet('DEPRECATED-VERSION'); + } + + if (isset($hash['EXTERNAL'])) { + $directive->external = preg_split('/\s*,\s*/', trim($hash->offsetGet('EXTERNAL'))); + } + + $interchange->addDirective($directive); + } + + /** + * Evaluates an array PHP code string without array() wrapper + * @param string $contents + */ + protected function evalArray($contents) + { + return eval('return array(' . $contents . ');'); + } + + /** + * Converts an array list into a lookup array. + * @param array $array + * @return array + */ + protected function lookup($array) + { + $ret = array(); + foreach ($array as $val) { + $ret[$val] = true; + } + return $ret; + } + + /** + * Convenience function that creates an HTMLPurifier_ConfigSchema_Interchange_Id + * object based on a string Id. + * @param string $id + * @return HTMLPurifier_ConfigSchema_Interchange_Id + */ + protected function id($id) + { + return HTMLPurifier_ConfigSchema_Interchange_Id::make($id); + } + + /** + * Triggers errors for any unused keys passed in the hash; such keys + * may indicate typos, missing values, etc. + * @param HTMLPurifier_StringHash $hash Hash to check. + */ + protected function _findUnused($hash) + { + $accessed = $hash->getAccessed(); + foreach ($hash as $k => $v) { + if (!isset($accessed[$k])) { + trigger_error("String hash key '$k' not used by builder", E_USER_NOTICE); + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Validator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Validator.php new file mode 100644 index 00000000..fb312778 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/Validator.php @@ -0,0 +1,248 @@ +parser = new HTMLPurifier_VarParser(); + } + + /** + * Validates a fully-formed interchange object. + * @param HTMLPurifier_ConfigSchema_Interchange $interchange + * @return bool + */ + public function validate($interchange) + { + $this->interchange = $interchange; + $this->aliases = array(); + // PHP is a bit lax with integer <=> string conversions in + // arrays, so we don't use the identical !== comparison + foreach ($interchange->directives as $i => $directive) { + $id = $directive->id->toString(); + if ($i != $id) { + $this->error(false, "Integrity violation: key '$i' does not match internal id '$id'"); + } + $this->validateDirective($directive); + } + return true; + } + + /** + * Validates a HTMLPurifier_ConfigSchema_Interchange_Id object. + * @param HTMLPurifier_ConfigSchema_Interchange_Id $id + */ + public function validateId($id) + { + $id_string = $id->toString(); + $this->context[] = "id '$id_string'"; + if (!$id instanceof HTMLPurifier_ConfigSchema_Interchange_Id) { + // handled by InterchangeBuilder + $this->error(false, 'is not an instance of HTMLPurifier_ConfigSchema_Interchange_Id'); + } + // keys are now unconstrained (we might want to narrow down to A-Za-z0-9.) + // we probably should check that it has at least one namespace + $this->with($id, 'key') + ->assertNotEmpty() + ->assertIsString(); // implicit assertIsString handled by InterchangeBuilder + array_pop($this->context); + } + + /** + * Validates a HTMLPurifier_ConfigSchema_Interchange_Directive object. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirective($d) + { + $id = $d->id->toString(); + $this->context[] = "directive '$id'"; + $this->validateId($d->id); + + $this->with($d, 'description') + ->assertNotEmpty(); + + // BEGIN - handled by InterchangeBuilder + $this->with($d, 'type') + ->assertNotEmpty(); + $this->with($d, 'typeAllowsNull') + ->assertIsBool(); + try { + // This also tests validity of $d->type + $this->parser->parse($d->default, $d->type, $d->typeAllowsNull); + } catch (HTMLPurifier_VarParserException $e) { + $this->error('default', 'had error: ' . $e->getMessage()); + } + // END - handled by InterchangeBuilder + + if (!is_null($d->allowed) || !empty($d->valueAliases)) { + // allowed and valueAliases require that we be dealing with + // strings, so check for that early. + $d_int = HTMLPurifier_VarParser::$types[$d->type]; + if (!isset(HTMLPurifier_VarParser::$stringTypes[$d_int])) { + $this->error('type', 'must be a string type when used with allowed or value aliases'); + } + } + + $this->validateDirectiveAllowed($d); + $this->validateDirectiveValueAliases($d); + $this->validateDirectiveAliases($d); + + array_pop($this->context); + } + + /** + * Extra validation if $allowed member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveAllowed($d) + { + if (is_null($d->allowed)) { + return; + } + $this->with($d, 'allowed') + ->assertNotEmpty() + ->assertIsLookup(); // handled by InterchangeBuilder + if (is_string($d->default) && !isset($d->allowed[$d->default])) { + $this->error('default', 'must be an allowed value'); + } + $this->context[] = 'allowed'; + foreach ($d->allowed as $val => $x) { + if (!is_string($val)) { + $this->error("value $val", 'must be a string'); + } + } + array_pop($this->context); + } + + /** + * Extra validation if $valueAliases member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveValueAliases($d) + { + if (is_null($d->valueAliases)) { + return; + } + $this->with($d, 'valueAliases') + ->assertIsArray(); // handled by InterchangeBuilder + $this->context[] = 'valueAliases'; + foreach ($d->valueAliases as $alias => $real) { + if (!is_string($alias)) { + $this->error("alias $alias", 'must be a string'); + } + if (!is_string($real)) { + $this->error("alias target $real from alias '$alias'", 'must be a string'); + } + if ($alias === $real) { + $this->error("alias '$alias'", "must not be an alias to itself"); + } + } + if (!is_null($d->allowed)) { + foreach ($d->valueAliases as $alias => $real) { + if (isset($d->allowed[$alias])) { + $this->error("alias '$alias'", 'must not be an allowed value'); + } elseif (!isset($d->allowed[$real])) { + $this->error("alias '$alias'", 'must be an alias to an allowed value'); + } + } + } + array_pop($this->context); + } + + /** + * Extra validation if $aliases member variable of + * HTMLPurifier_ConfigSchema_Interchange_Directive is defined. + * @param HTMLPurifier_ConfigSchema_Interchange_Directive $d + */ + public function validateDirectiveAliases($d) + { + $this->with($d, 'aliases') + ->assertIsArray(); // handled by InterchangeBuilder + $this->context[] = 'aliases'; + foreach ($d->aliases as $alias) { + $this->validateId($alias); + $s = $alias->toString(); + if (isset($this->interchange->directives[$s])) { + $this->error("alias '$s'", 'collides with another directive'); + } + if (isset($this->aliases[$s])) { + $other_directive = $this->aliases[$s]; + $this->error("alias '$s'", "collides with alias for directive '$other_directive'"); + } + $this->aliases[$s] = $d->id->toString(); + } + array_pop($this->context); + } + + // protected helper functions + + /** + * Convenience function for generating HTMLPurifier_ConfigSchema_ValidatorAtom + * for validating simple member variables of objects. + * @param $obj + * @param $member + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + protected function with($obj, $member) + { + return new HTMLPurifier_ConfigSchema_ValidatorAtom($this->getFormattedContext(), $obj, $member); + } + + /** + * Emits an error, providing helpful context. + * @throws HTMLPurifier_ConfigSchema_Exception + */ + protected function error($target, $msg) + { + if ($target !== false) { + $prefix = ucfirst($target) . ' in ' . $this->getFormattedContext(); + } else { + $prefix = ucfirst($this->getFormattedContext()); + } + throw new HTMLPurifier_ConfigSchema_Exception(trim($prefix . ' ' . $msg)); + } + + /** + * Returns a formatted context string. + * @return string + */ + protected function getFormattedContext() + { + return implode(' in ', array_reverse($this->context)); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php new file mode 100644 index 00000000..c9aa3644 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/ValidatorAtom.php @@ -0,0 +1,130 @@ +context = $context; + $this->obj = $obj; + $this->member = $member; + $this->contents =& $obj->$member; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsString() + { + if (!is_string($this->contents)) { + $this->error('must be a string'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsBool() + { + if (!is_bool($this->contents)) { + $this->error('must be a boolean'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsArray() + { + if (!is_array($this->contents)) { + $this->error('must be an array'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertNotNull() + { + if ($this->contents === null) { + $this->error('must not be null'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertAlnum() + { + $this->assertIsString(); + if (!ctype_alnum($this->contents)) { + $this->error('must be alphanumeric'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertNotEmpty() + { + if (empty($this->contents)) { + $this->error('must not be empty'); + } + return $this; + } + + /** + * @return HTMLPurifier_ConfigSchema_ValidatorAtom + */ + public function assertIsLookup() + { + $this->assertIsArray(); + foreach ($this->contents as $v) { + if ($v !== true) { + $this->error('must be a lookup array'); + } + } + return $this; + } + + /** + * @param string $msg + * @throws HTMLPurifier_ConfigSchema_Exception + */ + protected function error($msg) + { + throw new HTMLPurifier_ConfigSchema_Exception(ucfirst($this->member) . ' in ' . $this->context . ' ' . $msg); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema.ser b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema.ser new file mode 100644 index 00000000..a5426c73 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema.ser @@ -0,0 +1 @@ +O:25:"HTMLPurifier_ConfigSchema":3:{s:8:"defaults";a:127:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:10:"HTML.Forms";b:0;s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:12:"defaultPlist";O:25:"HTMLPurifier_PropertyList":3:{s:7:"*data";a:127:{s:19:"Attr.AllowedClasses";N;s:24:"Attr.AllowedFrameTargets";a:0:{}s:15:"Attr.AllowedRel";a:0:{}s:15:"Attr.AllowedRev";a:0:{}s:18:"Attr.ClassUseCDATA";N;s:20:"Attr.DefaultImageAlt";N;s:24:"Attr.DefaultInvalidImage";s:0:"";s:27:"Attr.DefaultInvalidImageAlt";s:13:"Invalid image";s:19:"Attr.DefaultTextDir";s:3:"ltr";s:13:"Attr.EnableID";b:0;s:21:"Attr.ForbiddenClasses";a:0:{}s:13:"Attr.ID.HTML5";N;s:16:"Attr.IDBlacklist";a:0:{}s:22:"Attr.IDBlacklistRegexp";N;s:13:"Attr.IDPrefix";s:0:"";s:18:"Attr.IDPrefixLocal";s:0:"";s:24:"AutoFormat.AutoParagraph";b:0;s:17:"AutoFormat.Custom";a:0:{}s:25:"AutoFormat.DisplayLinkURI";b:0;s:18:"AutoFormat.Linkify";b:0;s:33:"AutoFormat.PurifierLinkify.DocURL";s:3:"#%s";s:26:"AutoFormat.PurifierLinkify";b:0;s:32:"AutoFormat.RemoveEmpty.Predicate";a:4:{s:8:"colgroup";a:0:{}s:2:"th";a:0:{}s:2:"td";a:0:{}s:6:"iframe";a:1:{i:0;s:3:"src";}}s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";a:2:{s:2:"td";b:1;s:2:"th";b:1;}s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";b:0;s:22:"AutoFormat.RemoveEmpty";b:0;s:39:"AutoFormat.RemoveSpansWithoutAttributes";b:0;s:19:"CSS.AllowDuplicates";b:0;s:18:"CSS.AllowImportant";b:0;s:15:"CSS.AllowTricky";b:0;s:16:"CSS.AllowedFonts";N;s:21:"CSS.AllowedProperties";N;s:17:"CSS.DefinitionRev";i:1;s:23:"CSS.ForbiddenProperties";a:0:{}s:16:"CSS.MaxImgLength";s:6:"1200px";s:15:"CSS.Proprietary";b:0;s:11:"CSS.Trusted";b:0;s:20:"Cache.DefinitionImpl";s:10:"Serializer";s:20:"Cache.SerializerPath";N;s:27:"Cache.SerializerPermissions";i:493;s:22:"Core.AggressivelyFixLt";b:1;s:29:"Core.AggressivelyRemoveScript";b:1;s:28:"Core.AllowHostnameUnderscore";b:0;s:23:"Core.AllowParseManyTags";b:0;s:18:"Core.CollectErrors";b:0;s:18:"Core.ColorKeywords";a:148:{s:9:"aliceblue";s:7:"#F0F8FF";s:12:"antiquewhite";s:7:"#FAEBD7";s:4:"aqua";s:7:"#00FFFF";s:10:"aquamarine";s:7:"#7FFFD4";s:5:"azure";s:7:"#F0FFFF";s:5:"beige";s:7:"#F5F5DC";s:6:"bisque";s:7:"#FFE4C4";s:5:"black";s:7:"#000000";s:14:"blanchedalmond";s:7:"#FFEBCD";s:4:"blue";s:7:"#0000FF";s:10:"blueviolet";s:7:"#8A2BE2";s:5:"brown";s:7:"#A52A2A";s:9:"burlywood";s:7:"#DEB887";s:9:"cadetblue";s:7:"#5F9EA0";s:10:"chartreuse";s:7:"#7FFF00";s:9:"chocolate";s:7:"#D2691E";s:5:"coral";s:7:"#FF7F50";s:14:"cornflowerblue";s:7:"#6495ED";s:8:"cornsilk";s:7:"#FFF8DC";s:7:"crimson";s:7:"#DC143C";s:4:"cyan";s:7:"#00FFFF";s:8:"darkblue";s:7:"#00008B";s:8:"darkcyan";s:7:"#008B8B";s:13:"darkgoldenrod";s:7:"#B8860B";s:8:"darkgray";s:7:"#A9A9A9";s:8:"darkgrey";s:7:"#A9A9A9";s:9:"darkgreen";s:7:"#006400";s:9:"darkkhaki";s:7:"#BDB76B";s:11:"darkmagenta";s:7:"#8B008B";s:14:"darkolivegreen";s:7:"#556B2F";s:10:"darkorange";s:7:"#FF8C00";s:10:"darkorchid";s:7:"#9932CC";s:7:"darkred";s:7:"#8B0000";s:10:"darksalmon";s:7:"#E9967A";s:12:"darkseagreen";s:7:"#8FBC8F";s:13:"darkslateblue";s:7:"#483D8B";s:13:"darkslategray";s:7:"#2F4F4F";s:13:"darkslategrey";s:7:"#2F4F4F";s:13:"darkturquoise";s:7:"#00CED1";s:10:"darkviolet";s:7:"#9400D3";s:8:"deeppink";s:7:"#FF1493";s:11:"deepskyblue";s:7:"#00BFFF";s:7:"dimgray";s:7:"#696969";s:7:"dimgrey";s:7:"#696969";s:10:"dodgerblue";s:7:"#1E90FF";s:9:"firebrick";s:7:"#B22222";s:11:"floralwhite";s:7:"#FFFAF0";s:11:"forestgreen";s:7:"#228B22";s:7:"fuchsia";s:7:"#FF00FF";s:9:"gainsboro";s:7:"#DCDCDC";s:10:"ghostwhite";s:7:"#F8F8FF";s:4:"gold";s:7:"#FFD700";s:9:"goldenrod";s:7:"#DAA520";s:4:"gray";s:7:"#808080";s:4:"grey";s:7:"#808080";s:5:"green";s:7:"#008000";s:11:"greenyellow";s:7:"#ADFF2F";s:8:"honeydew";s:7:"#F0FFF0";s:7:"hotpink";s:7:"#FF69B4";s:9:"indianred";s:7:"#CD5C5C";s:6:"indigo";s:7:"#4B0082";s:5:"ivory";s:7:"#FFFFF0";s:5:"khaki";s:7:"#F0E68C";s:8:"lavender";s:7:"#E6E6FA";s:13:"lavenderblush";s:7:"#FFF0F5";s:9:"lawngreen";s:7:"#7CFC00";s:12:"lemonchiffon";s:7:"#FFFACD";s:9:"lightblue";s:7:"#ADD8E6";s:10:"lightcoral";s:7:"#F08080";s:9:"lightcyan";s:7:"#E0FFFF";s:20:"lightgoldenrodyellow";s:7:"#FAFAD2";s:9:"lightgray";s:7:"#D3D3D3";s:9:"lightgrey";s:7:"#D3D3D3";s:10:"lightgreen";s:7:"#90EE90";s:9:"lightpink";s:7:"#FFB6C1";s:11:"lightsalmon";s:7:"#FFA07A";s:13:"lightseagreen";s:7:"#20B2AA";s:12:"lightskyblue";s:7:"#87CEFA";s:14:"lightslategray";s:7:"#778899";s:14:"lightslategrey";s:7:"#778899";s:14:"lightsteelblue";s:7:"#B0C4DE";s:11:"lightyellow";s:7:"#FFFFE0";s:4:"lime";s:7:"#00FF00";s:9:"limegreen";s:7:"#32CD32";s:5:"linen";s:7:"#FAF0E6";s:7:"magenta";s:7:"#FF00FF";s:6:"maroon";s:7:"#800000";s:16:"mediumaquamarine";s:7:"#66CDAA";s:10:"mediumblue";s:7:"#0000CD";s:12:"mediumorchid";s:7:"#BA55D3";s:12:"mediumpurple";s:7:"#9370DB";s:14:"mediumseagreen";s:7:"#3CB371";s:15:"mediumslateblue";s:7:"#7B68EE";s:17:"mediumspringgreen";s:7:"#00FA9A";s:15:"mediumturquoise";s:7:"#48D1CC";s:15:"mediumvioletred";s:7:"#C71585";s:12:"midnightblue";s:7:"#191970";s:9:"mintcream";s:7:"#F5FFFA";s:9:"mistyrose";s:7:"#FFE4E1";s:8:"moccasin";s:7:"#FFE4B5";s:11:"navajowhite";s:7:"#FFDEAD";s:4:"navy";s:7:"#000080";s:7:"oldlace";s:7:"#FDF5E6";s:5:"olive";s:7:"#808000";s:9:"olivedrab";s:7:"#6B8E23";s:6:"orange";s:7:"#FFA500";s:9:"orangered";s:7:"#FF4500";s:6:"orchid";s:7:"#DA70D6";s:13:"palegoldenrod";s:7:"#EEE8AA";s:9:"palegreen";s:7:"#98FB98";s:13:"paleturquoise";s:7:"#AFEEEE";s:13:"palevioletred";s:7:"#DB7093";s:10:"papayawhip";s:7:"#FFEFD5";s:9:"peachpuff";s:7:"#FFDAB9";s:4:"peru";s:7:"#CD853F";s:4:"pink";s:7:"#FFC0CB";s:4:"plum";s:7:"#DDA0DD";s:10:"powderblue";s:7:"#B0E0E6";s:6:"purple";s:7:"#800080";s:13:"rebeccapurple";s:7:"#663399";s:3:"red";s:7:"#FF0000";s:9:"rosybrown";s:7:"#BC8F8F";s:9:"royalblue";s:7:"#4169E1";s:11:"saddlebrown";s:7:"#8B4513";s:6:"salmon";s:7:"#FA8072";s:10:"sandybrown";s:7:"#F4A460";s:8:"seagreen";s:7:"#2E8B57";s:8:"seashell";s:7:"#FFF5EE";s:6:"sienna";s:7:"#A0522D";s:6:"silver";s:7:"#C0C0C0";s:7:"skyblue";s:7:"#87CEEB";s:9:"slateblue";s:7:"#6A5ACD";s:9:"slategray";s:7:"#708090";s:9:"slategrey";s:7:"#708090";s:4:"snow";s:7:"#FFFAFA";s:11:"springgreen";s:7:"#00FF7F";s:9:"steelblue";s:7:"#4682B4";s:3:"tan";s:7:"#D2B48C";s:4:"teal";s:7:"#008080";s:7:"thistle";s:7:"#D8BFD8";s:6:"tomato";s:7:"#FF6347";s:9:"turquoise";s:7:"#40E0D0";s:6:"violet";s:7:"#EE82EE";s:5:"wheat";s:7:"#F5DEB3";s:5:"white";s:7:"#FFFFFF";s:10:"whitesmoke";s:7:"#F5F5F5";s:6:"yellow";s:7:"#FFFF00";s:11:"yellowgreen";s:7:"#9ACD32";}s:30:"Core.ConvertDocumentToFragment";b:1;s:36:"Core.DirectLexLineNumberSyncInterval";i:0;s:20:"Core.DisableExcludes";b:0;s:15:"Core.EnableIDNA";b:0;s:13:"Core.Encoding";s:5:"utf-8";s:26:"Core.EscapeInvalidChildren";b:0;s:22:"Core.EscapeInvalidTags";b:0;s:29:"Core.EscapeNonASCIICharacters";b:0;s:19:"Core.HiddenElements";a:2:{s:6:"script";b:1;s:5:"style";b:1;}s:13:"Core.Language";s:2:"en";s:24:"Core.LegacyEntityDecoder";b:0;s:14:"Core.LexerImpl";N;s:24:"Core.MaintainLineNumbers";N;s:22:"Core.NormalizeNewlines";b:1;s:21:"Core.RemoveInvalidImg";b:1;s:33:"Core.RemoveProcessingInstructions";b:0;s:25:"Core.RemoveScriptContents";N;s:13:"Filter.Custom";a:0:{}s:34:"Filter.ExtractStyleBlocks.Escaping";b:1;s:31:"Filter.ExtractStyleBlocks.Scope";N;s:34:"Filter.ExtractStyleBlocks.TidyImpl";N;s:25:"Filter.ExtractStyleBlocks";b:0;s:14:"Filter.YouTube";b:0;s:12:"HTML.Allowed";N;s:22:"HTML.AllowedAttributes";N;s:20:"HTML.AllowedComments";a:0:{}s:26:"HTML.AllowedCommentsRegexp";N;s:20:"HTML.AllowedElements";N;s:19:"HTML.AllowedModules";N;s:23:"HTML.Attr.Name.UseCDATA";b:0;s:17:"HTML.BlockWrapper";s:1:"p";s:16:"HTML.CoreModules";a:7:{s:9:"Structure";b:1;s:4:"Text";b:1;s:9:"Hypertext";b:1;s:4:"List";b:1;s:22:"NonXMLCommonAttributes";b:1;s:19:"XMLCommonAttributes";b:1;s:16:"CommonAttributes";b:1;}s:18:"HTML.CustomDoctype";N;s:17:"HTML.DefinitionID";N;s:18:"HTML.DefinitionRev";i:1;s:12:"HTML.Doctype";N;s:25:"HTML.FlashAllowFullScreen";b:0;s:24:"HTML.ForbiddenAttributes";a:0:{}s:22:"HTML.ForbiddenElements";a:0:{}s:10:"HTML.Forms";b:0;s:17:"HTML.MaxImgLength";i:1200;s:13:"HTML.Nofollow";b:0;s:11:"HTML.Parent";s:3:"div";s:16:"HTML.Proprietary";b:0;s:14:"HTML.SafeEmbed";b:0;s:15:"HTML.SafeIframe";b:0;s:15:"HTML.SafeObject";b:0;s:18:"HTML.SafeScripting";a:0:{}s:11:"HTML.Strict";b:0;s:16:"HTML.TargetBlank";b:0;s:19:"HTML.TargetNoopener";b:1;s:21:"HTML.TargetNoreferrer";b:1;s:12:"HTML.TidyAdd";a:0:{}s:14:"HTML.TidyLevel";s:6:"medium";s:15:"HTML.TidyRemove";a:0:{}s:12:"HTML.Trusted";b:0;s:10:"HTML.XHTML";b:1;s:28:"Output.CommentScriptContents";b:1;s:19:"Output.FixInnerHTML";b:1;s:18:"Output.FlashCompat";b:0;s:14:"Output.Newline";N;s:15:"Output.SortAttr";b:0;s:17:"Output.TidyFormat";b:0;s:17:"Test.ForceNoIconv";b:0;s:18:"URI.AllowedSchemes";a:7:{s:4:"http";b:1;s:5:"https";b:1;s:6:"mailto";b:1;s:3:"ftp";b:1;s:4:"nntp";b:1;s:4:"news";b:1;s:3:"tel";b:1;}s:8:"URI.Base";N;s:17:"URI.DefaultScheme";s:4:"http";s:16:"URI.DefinitionID";N;s:17:"URI.DefinitionRev";i:1;s:11:"URI.Disable";b:0;s:19:"URI.DisableExternal";b:0;s:28:"URI.DisableExternalResources";b:0;s:20:"URI.DisableResources";b:0;s:8:"URI.Host";N;s:17:"URI.HostBlacklist";a:0:{}s:16:"URI.MakeAbsolute";b:0;s:9:"URI.Munge";N;s:18:"URI.MungeResources";b:0;s:18:"URI.MungeSecretKey";N;s:26:"URI.OverrideAllowedSchemes";b:1;s:20:"URI.SafeIframeRegexp";N;}s:9:"*parent";N;s:8:"*cache";N;}s:4:"info";a:140:{s:19:"Attr.AllowedClasses";i:-8;s:24:"Attr.AllowedFrameTargets";i:8;s:15:"Attr.AllowedRel";i:8;s:15:"Attr.AllowedRev";i:8;s:18:"Attr.ClassUseCDATA";i:-7;s:20:"Attr.DefaultImageAlt";i:-1;s:24:"Attr.DefaultInvalidImage";i:1;s:27:"Attr.DefaultInvalidImageAlt";i:1;s:19:"Attr.DefaultTextDir";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:2:{s:3:"ltr";b:1;s:3:"rtl";b:1;}}s:13:"Attr.EnableID";i:7;s:17:"HTML.EnableAttrID";O:8:"stdClass":2:{s:3:"key";s:13:"Attr.EnableID";s:7:"isAlias";b:1;}s:21:"Attr.ForbiddenClasses";i:8;s:13:"Attr.ID.HTML5";i:-7;s:16:"Attr.IDBlacklist";i:9;s:22:"Attr.IDBlacklistRegexp";i:-1;s:13:"Attr.IDPrefix";i:1;s:18:"Attr.IDPrefixLocal";i:1;s:24:"AutoFormat.AutoParagraph";i:7;s:17:"AutoFormat.Custom";i:9;s:25:"AutoFormat.DisplayLinkURI";i:7;s:18:"AutoFormat.Linkify";i:7;s:33:"AutoFormat.PurifierLinkify.DocURL";i:1;s:37:"AutoFormatParam.PurifierLinkifyDocURL";O:8:"stdClass":2:{s:3:"key";s:33:"AutoFormat.PurifierLinkify.DocURL";s:7:"isAlias";b:1;}s:26:"AutoFormat.PurifierLinkify";i:7;s:32:"AutoFormat.RemoveEmpty.Predicate";i:10;s:44:"AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions";i:8;s:33:"AutoFormat.RemoveEmpty.RemoveNbsp";i:7;s:22:"AutoFormat.RemoveEmpty";i:7;s:39:"AutoFormat.RemoveSpansWithoutAttributes";i:7;s:19:"CSS.AllowDuplicates";i:7;s:18:"CSS.AllowImportant";i:7;s:15:"CSS.AllowTricky";i:7;s:16:"CSS.AllowedFonts";i:-8;s:21:"CSS.AllowedProperties";i:-8;s:17:"CSS.DefinitionRev";i:5;s:23:"CSS.ForbiddenProperties";i:8;s:16:"CSS.MaxImgLength";i:-1;s:15:"CSS.Proprietary";i:7;s:11:"CSS.Trusted";i:7;s:20:"Cache.DefinitionImpl";i:-1;s:20:"Core.DefinitionCache";O:8:"stdClass":2:{s:3:"key";s:20:"Cache.DefinitionImpl";s:7:"isAlias";b:1;}s:20:"Cache.SerializerPath";i:-1;s:27:"Cache.SerializerPermissions";i:-5;s:22:"Core.AggressivelyFixLt";i:7;s:29:"Core.AggressivelyRemoveScript";i:7;s:28:"Core.AllowHostnameUnderscore";i:7;s:23:"Core.AllowParseManyTags";i:7;s:18:"Core.CollectErrors";i:7;s:18:"Core.ColorKeywords";i:10;s:30:"Core.ConvertDocumentToFragment";i:7;s:24:"Core.AcceptFullDocuments";O:8:"stdClass":2:{s:3:"key";s:30:"Core.ConvertDocumentToFragment";s:7:"isAlias";b:1;}s:36:"Core.DirectLexLineNumberSyncInterval";i:5;s:20:"Core.DisableExcludes";i:7;s:15:"Core.EnableIDNA";i:7;s:13:"Core.Encoding";i:2;s:26:"Core.EscapeInvalidChildren";i:7;s:22:"Core.EscapeInvalidTags";i:7;s:29:"Core.EscapeNonASCIICharacters";i:7;s:19:"Core.HiddenElements";i:8;s:13:"Core.Language";i:1;s:24:"Core.LegacyEntityDecoder";i:7;s:14:"Core.LexerImpl";i:-11;s:24:"Core.MaintainLineNumbers";i:-7;s:22:"Core.NormalizeNewlines";i:7;s:21:"Core.RemoveInvalidImg";i:7;s:33:"Core.RemoveProcessingInstructions";i:7;s:25:"Core.RemoveScriptContents";i:-7;s:13:"Filter.Custom";i:9;s:34:"Filter.ExtractStyleBlocks.Escaping";i:7;s:33:"Filter.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:38:"FilterParam.ExtractStyleBlocksEscaping";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.Escaping";s:7:"isAlias";b:1;}s:31:"Filter.ExtractStyleBlocks.Scope";i:-1;s:30:"Filter.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:35:"FilterParam.ExtractStyleBlocksScope";O:8:"stdClass":2:{s:3:"key";s:31:"Filter.ExtractStyleBlocks.Scope";s:7:"isAlias";b:1;}s:34:"Filter.ExtractStyleBlocks.TidyImpl";i:-11;s:38:"FilterParam.ExtractStyleBlocksTidyImpl";O:8:"stdClass":2:{s:3:"key";s:34:"Filter.ExtractStyleBlocks.TidyImpl";s:7:"isAlias";b:1;}s:25:"Filter.ExtractStyleBlocks";i:7;s:14:"Filter.YouTube";i:7;s:12:"HTML.Allowed";i:-4;s:22:"HTML.AllowedAttributes";i:-8;s:20:"HTML.AllowedComments";i:8;s:26:"HTML.AllowedCommentsRegexp";i:-1;s:20:"HTML.AllowedElements";i:-8;s:19:"HTML.AllowedModules";i:-8;s:23:"HTML.Attr.Name.UseCDATA";i:7;s:17:"HTML.BlockWrapper";i:1;s:16:"HTML.CoreModules";i:8;s:18:"HTML.CustomDoctype";i:-1;s:17:"HTML.DefinitionID";i:-1;s:18:"HTML.DefinitionRev";i:5;s:12:"HTML.Doctype";O:8:"stdClass":3:{s:4:"type";i:1;s:10:"allow_null";b:1;s:7:"allowed";a:5:{s:22:"HTML 4.01 Transitional";b:1;s:16:"HTML 4.01 Strict";b:1;s:22:"XHTML 1.0 Transitional";b:1;s:16:"XHTML 1.0 Strict";b:1;s:9:"XHTML 1.1";b:1;}}s:25:"HTML.FlashAllowFullScreen";i:7;s:24:"HTML.ForbiddenAttributes";i:8;s:22:"HTML.ForbiddenElements";i:8;s:10:"HTML.Forms";i:7;s:17:"HTML.MaxImgLength";i:-5;s:13:"HTML.Nofollow";i:7;s:11:"HTML.Parent";i:1;s:16:"HTML.Proprietary";i:7;s:14:"HTML.SafeEmbed";i:7;s:15:"HTML.SafeIframe";i:7;s:15:"HTML.SafeObject";i:7;s:18:"HTML.SafeScripting";i:8;s:11:"HTML.Strict";i:7;s:16:"HTML.TargetBlank";i:7;s:19:"HTML.TargetNoopener";i:7;s:21:"HTML.TargetNoreferrer";i:7;s:12:"HTML.TidyAdd";i:8;s:14:"HTML.TidyLevel";O:8:"stdClass":2:{s:4:"type";i:1;s:7:"allowed";a:4:{s:4:"none";b:1;s:5:"light";b:1;s:6:"medium";b:1;s:5:"heavy";b:1;}}s:15:"HTML.TidyRemove";i:8;s:12:"HTML.Trusted";i:7;s:10:"HTML.XHTML";i:7;s:10:"Core.XHTML";O:8:"stdClass":2:{s:3:"key";s:10:"HTML.XHTML";s:7:"isAlias";b:1;}s:28:"Output.CommentScriptContents";i:7;s:26:"Core.CommentScriptContents";O:8:"stdClass":2:{s:3:"key";s:28:"Output.CommentScriptContents";s:7:"isAlias";b:1;}s:19:"Output.FixInnerHTML";i:7;s:18:"Output.FlashCompat";i:7;s:14:"Output.Newline";i:-1;s:15:"Output.SortAttr";i:7;s:17:"Output.TidyFormat";i:7;s:15:"Core.TidyFormat";O:8:"stdClass":2:{s:3:"key";s:17:"Output.TidyFormat";s:7:"isAlias";b:1;}s:17:"Test.ForceNoIconv";i:7;s:18:"URI.AllowedSchemes";i:8;s:8:"URI.Base";i:-1;s:17:"URI.DefaultScheme";i:-1;s:16:"URI.DefinitionID";i:-1;s:17:"URI.DefinitionRev";i:5;s:11:"URI.Disable";i:7;s:15:"Attr.DisableURI";O:8:"stdClass":2:{s:3:"key";s:11:"URI.Disable";s:7:"isAlias";b:1;}s:19:"URI.DisableExternal";i:7;s:28:"URI.DisableExternalResources";i:7;s:20:"URI.DisableResources";i:7;s:8:"URI.Host";i:-1;s:17:"URI.HostBlacklist";i:9;s:16:"URI.MakeAbsolute";i:7;s:9:"URI.Munge";i:-1;s:18:"URI.MungeResources";i:7;s:18:"URI.MungeSecretKey";i:-1;s:26:"URI.OverrideAllowedSchemes";i:7;s:20:"URI.SafeIframeRegexp";i:-1;}} \ No newline at end of file diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt new file mode 100644 index 00000000..0517fed0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedClasses.txt @@ -0,0 +1,8 @@ +Attr.AllowedClasses +TYPE: lookup/null +VERSION: 4.0.0 +DEFAULT: null +--DESCRIPTION-- +List of allowed class values in the class attribute. By default, this is null, +which means all classes are allowed. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt new file mode 100644 index 00000000..249edd64 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedFrameTargets.txt @@ -0,0 +1,12 @@ +Attr.AllowedFrameTargets +TYPE: lookup +DEFAULT: array() +--DESCRIPTION-- +Lookup table of all allowed link frame targets. Some commonly used link +targets include _blank, _self, _parent and _top. Values should be +lowercase, as validation will be done in a case-sensitive manner despite +W3C's recommendation. XHTML 1.0 Strict does not permit the target attribute +so this directive will have no effect in that doctype. XHTML 1.1 does not +enable the Target module by default, you will have to manually enable it +(see the module documentation for more details.) +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt new file mode 100644 index 00000000..9a8fa6a2 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRel.txt @@ -0,0 +1,9 @@ +Attr.AllowedRel +TYPE: lookup +VERSION: 1.6.0 +DEFAULT: array() +--DESCRIPTION-- +List of allowed forward document relationships in the rel attribute. Common +values may be nofollow or print. By default, this is empty, meaning that no +document relationships are allowed. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt new file mode 100644 index 00000000..b0178834 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.AllowedRev.txt @@ -0,0 +1,9 @@ +Attr.AllowedRev +TYPE: lookup +VERSION: 1.6.0 +DEFAULT: array() +--DESCRIPTION-- +List of allowed reverse document relationships in the rev attribute. This +attribute is a bit of an edge-case; if you don't know what it is for, stay +away. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt new file mode 100644 index 00000000..e774b823 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ClassUseCDATA.txt @@ -0,0 +1,19 @@ +Attr.ClassUseCDATA +TYPE: bool/null +DEFAULT: null +VERSION: 4.0.0 +--DESCRIPTION-- +If null, class will auto-detect the doctype and, if matching XHTML 1.1 or +XHTML 2.0, will use the restrictive NMTOKENS specification of class. Otherwise, +it will use a relaxed CDATA definition. If true, the relaxed CDATA definition +is forced; if false, the NMTOKENS definition is forced. To get behavior +of HTML Purifier prior to 4.0.0, set this directive to false. + +Some rational behind the auto-detection: +in previous versions of HTML Purifier, it was assumed that the form of +class was NMTOKENS, as specified by the XHTML Modularization (representing +XHTML 1.1 and XHTML 2.0). The DTDs for HTML 4.01 and XHTML 1.0, however +specify class as CDATA. HTML 5 effectively defines it as CDATA, but +with the additional constraint that each name should be unique (this is not +explicitly outlined in previous specifications). +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt new file mode 100644 index 00000000..533165e1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultImageAlt.txt @@ -0,0 +1,11 @@ +Attr.DefaultImageAlt +TYPE: string/null +DEFAULT: null +VERSION: 3.2.0 +--DESCRIPTION-- +This is the content of the alt tag of an image if the user had not +previously specified an alt attribute. This applies to all images without +a valid alt attribute, as opposed to %Attr.DefaultInvalidImageAlt, which +only applies to invalid images, and overrides in the case of an invalid image. +Default behavior with null is to use the basename of the src tag for the alt. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt new file mode 100644 index 00000000..9eb7e384 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImage.txt @@ -0,0 +1,9 @@ +Attr.DefaultInvalidImage +TYPE: string +DEFAULT: '' +--DESCRIPTION-- +This is the default image an img tag will be pointed to if it does not have +a valid src attribute. In future versions, we may allow the image tag to +be removed completely, but due to design issues, this is not possible right +now. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt new file mode 100644 index 00000000..2f17bf47 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultInvalidImageAlt.txt @@ -0,0 +1,8 @@ +Attr.DefaultInvalidImageAlt +TYPE: string +DEFAULT: 'Invalid image' +--DESCRIPTION-- +This is the content of the alt tag of an invalid image if the user had not +previously specified an alt attribute. It has no effect when the image is +valid but there was no alt attribute present. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt new file mode 100644 index 00000000..52654b53 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.DefaultTextDir.txt @@ -0,0 +1,10 @@ +Attr.DefaultTextDir +TYPE: string +DEFAULT: 'ltr' +--DESCRIPTION-- +Defines the default text direction (ltr or rtl) of the document being +parsed. This generally is the same as the value of the dir attribute in +HTML, or ltr if that is not specified. +--ALLOWED-- +'ltr', 'rtl' +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt new file mode 100644 index 00000000..6440d210 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.EnableID.txt @@ -0,0 +1,16 @@ +Attr.EnableID +TYPE: bool +DEFAULT: false +VERSION: 1.2.0 +--DESCRIPTION-- +Allows the ID attribute in HTML. This is disabled by default due to the +fact that without proper configuration user input can easily break the +validation of a webpage by specifying an ID that is already on the +surrounding HTML. If you don't mind throwing caution to the wind, enable +this directive, but I strongly recommend you also consider blacklisting IDs +you use (%Attr.IDBlacklist) or prefixing all user supplied IDs +(%Attr.IDPrefix). When set to true HTML Purifier reverts to the behavior of +pre-1.2.0 versions. +--ALIASES-- +HTML.EnableAttrID +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt new file mode 100644 index 00000000..f31d226f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ForbiddenClasses.txt @@ -0,0 +1,8 @@ +Attr.ForbiddenClasses +TYPE: lookup +VERSION: 4.0.0 +DEFAULT: array() +--DESCRIPTION-- +List of forbidden class values in the class attribute. By default, this is +empty, which means that no classes are forbidden. See also %Attr.AllowedClasses. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt new file mode 100644 index 00000000..735d4b7a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.ID.HTML5.txt @@ -0,0 +1,10 @@ +Attr.ID.HTML5 +TYPE: bool/null +DEFAULT: null +VERSION: 4.8.0 +--DESCRIPTION-- +In HTML5, restrictions on the format of the id attribute have been significantly +relaxed, such that any string is valid so long as it contains no spaces and +is at least one character. In lieu of a general HTML5 compatibility flag, +set this configuration directive to true to use the relaxed rules. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt new file mode 100644 index 00000000..5f2b5e3d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklist.txt @@ -0,0 +1,5 @@ +Attr.IDBlacklist +TYPE: list +DEFAULT: array() +DESCRIPTION: Array of IDs not allowed in the document. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt new file mode 100644 index 00000000..6f582458 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDBlacklistRegexp.txt @@ -0,0 +1,9 @@ +Attr.IDBlacklistRegexp +TYPE: string/null +VERSION: 1.6.0 +DEFAULT: NULL +--DESCRIPTION-- +PCRE regular expression to be matched against all IDs. If the expression is +matches, the ID is rejected. Use this with care: may cause significant +degradation. ID matching is done after all other validation. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt new file mode 100644 index 00000000..cc49d43f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefix.txt @@ -0,0 +1,12 @@ +Attr.IDPrefix +TYPE: string +VERSION: 1.2.0 +DEFAULT: '' +--DESCRIPTION-- +String to prefix to IDs. If you have no idea what IDs your pages may use, +you may opt to simply add a prefix to all user-submitted ID attributes so +that they are still usable, but will not conflict with core page IDs. +Example: setting the directive to 'user_' will result in a user submitted +'foo' to become 'user_foo' Be sure to set %HTML.EnableAttrID to true +before using this. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt new file mode 100644 index 00000000..2c5924a7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Attr.IDPrefixLocal.txt @@ -0,0 +1,14 @@ +Attr.IDPrefixLocal +TYPE: string +VERSION: 1.2.0 +DEFAULT: '' +--DESCRIPTION-- +Temporary prefix for IDs used in conjunction with %Attr.IDPrefix. If you +need to allow multiple sets of user content on web page, you may need to +have a seperate prefix that changes with each iteration. This way, +seperately submitted user content displayed on the same page doesn't +clobber each other. Ideal values are unique identifiers for the content it +represents (i.e. the id of the row in the database). Be sure to add a +seperator (like an underscore) at the end. Warning: this directive will +not work unless %Attr.IDPrefix is set to a non-empty value! +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt new file mode 100644 index 00000000..d5caa1bb --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.AutoParagraph.txt @@ -0,0 +1,31 @@ +AutoFormat.AutoParagraph +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

    + This directive turns on auto-paragraphing, where double newlines are + converted in to paragraphs whenever possible. Auto-paragraphing: +

    +
      +
    • Always applies to inline elements or text in the root node,
    • +
    • Applies to inline elements or text with double newlines in nodes + that allow paragraph tags,
    • +
    • Applies to double newlines in paragraph tags
    • +
    +

    + p tags must be allowed for this directive to take effect. + We do not use br tags for paragraphing, as that is + semantically incorrect. +

    +

    + To prevent auto-paragraphing as a content-producer, refrain from using + double-newlines except to specify a new paragraph or in contexts where + it has special meaning (whitespace usually has no meaning except in + tags like pre, so this should not be difficult.) To prevent + the paragraphing of inline text adjacent to block elements, wrap them + in div tags (the behavior is slightly different outside of + the root node.) +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt new file mode 100644 index 00000000..2a476481 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Custom.txt @@ -0,0 +1,12 @@ +AutoFormat.Custom +TYPE: list +VERSION: 2.0.1 +DEFAULT: array() +--DESCRIPTION-- + +

    + This directive can be used to add custom auto-format injectors. + Specify an array of injector names (class name minus the prefix) + or concrete implementations. Injector class must exist. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt new file mode 100644 index 00000000..663064a3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.DisplayLinkURI.txt @@ -0,0 +1,11 @@ +AutoFormat.DisplayLinkURI +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

    + This directive turns on the in-text display of URIs in <a> tags, and disables + those links. For example, example becomes + example (http://example.com). +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt new file mode 100644 index 00000000..3a48ba96 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.Linkify.txt @@ -0,0 +1,12 @@ +AutoFormat.Linkify +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

    + This directive turns on linkification, auto-linking http, ftp and + https URLs. a tags with the href attribute + must be allowed. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt new file mode 100644 index 00000000..db58b134 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.DocURL.txt @@ -0,0 +1,12 @@ +AutoFormat.PurifierLinkify.DocURL +TYPE: string +VERSION: 2.0.1 +DEFAULT: '#%s' +ALIASES: AutoFormatParam.PurifierLinkifyDocURL +--DESCRIPTION-- +

    + Location of configuration documentation to link to, let %s substitute + into the configuration's namespace and directive names sans the percent + sign. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt new file mode 100644 index 00000000..7996488b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.PurifierLinkify.txt @@ -0,0 +1,12 @@ +AutoFormat.PurifierLinkify +TYPE: bool +VERSION: 2.0.1 +DEFAULT: false +--DESCRIPTION-- + +

    + Internal auto-formatter that converts configuration directives in + syntax %Namespace.Directive to links. a tags + with the href attribute must be allowed. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt new file mode 100644 index 00000000..6367fe23 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.Predicate.txt @@ -0,0 +1,14 @@ +AutoFormat.RemoveEmpty.Predicate +TYPE: hash +VERSION: 4.7.0 +DEFAULT: array('colgroup' => array(), 'th' => array(), 'td' => array(), 'iframe' => array('src')) +--DESCRIPTION-- +

    + Given that an element has no contents, it will be removed by default, unless + this predicate dictates otherwise. The predicate can either be an associative + map from tag name to list of attributes that must be present for the element + to be considered preserved: thus, the default always preserves colgroup, + th and td, and also iframe if it + has a src. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt new file mode 100644 index 00000000..35c393b4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions.txt @@ -0,0 +1,11 @@ +AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions +TYPE: lookup +VERSION: 4.0.0 +DEFAULT: array('td' => true, 'th' => true) +--DESCRIPTION-- +

    + When %AutoFormat.RemoveEmpty and %AutoFormat.RemoveEmpty.RemoveNbsp + are enabled, this directive defines what HTML elements should not be + removede if they have only a non-breaking space in them. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt new file mode 100644 index 00000000..9228dee2 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.RemoveNbsp.txt @@ -0,0 +1,15 @@ +AutoFormat.RemoveEmpty.RemoveNbsp +TYPE: bool +VERSION: 4.0.0 +DEFAULT: false +--DESCRIPTION-- +

    + When enabled, HTML Purifier will treat any elements that contain only + non-breaking spaces as well as regular whitespace as empty, and remove + them when %AutoFormat.RemoveEmpty is enabled. +

    +

    + See %AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions for a list of elements + that don't have this behavior applied to them. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt new file mode 100644 index 00000000..34657ba4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveEmpty.txt @@ -0,0 +1,46 @@ +AutoFormat.RemoveEmpty +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

    + When enabled, HTML Purifier will attempt to remove empty elements that + contribute no semantic information to the document. The following types + of nodes will be removed: +

    +
    • + Tags with no attributes and no content, and that are not empty + elements (remove <a></a> but not + <br />), and +
    • +
    • + Tags with no content, except for:
        +
      • The colgroup element, or
      • +
      • + Elements with the id or name attribute, + when those attributes are permitted on those elements. +
      • +
    • +
    +

    + Please be very careful when using this functionality; while it may not + seem that empty elements contain useful information, they can alter the + layout of a document given appropriate styling. This directive is most + useful when you are processing machine-generated HTML, please avoid using + it on regular user HTML. +

    +

    + Elements that contain only whitespace will be treated as empty. Non-breaking + spaces, however, do not count as whitespace. See + %AutoFormat.RemoveEmpty.RemoveNbsp for alternate behavior. +

    +

    + This algorithm is not perfect; you may still notice some empty tags, + particularly if a node had elements, but those elements were later removed + because they were not permitted in that context, or tags that, after + being auto-closed by another tag, where empty. This is for safety reasons + to prevent clever code from breaking validation. The general rule of thumb: + if a tag looked empty on the way in, it will get removed; if HTML Purifier + made it empty, it will stay. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt new file mode 100644 index 00000000..dde990ab --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/AutoFormat.RemoveSpansWithoutAttributes.txt @@ -0,0 +1,11 @@ +AutoFormat.RemoveSpansWithoutAttributes +TYPE: bool +VERSION: 4.0.1 +DEFAULT: false +--DESCRIPTION-- +

    + This directive causes span tags without any attributes + to be removed. It will also remove spans that had all attributes + removed during processing. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt new file mode 100644 index 00000000..4d054b1f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowDuplicates.txt @@ -0,0 +1,11 @@ +CSS.AllowDuplicates +TYPE: bool +DEFAULT: false +VERSION: 4.8.0 +--DESCRIPTION-- +

    + By default, HTML Purifier removes duplicate CSS properties, + like color:red; color:blue. If this is set to + true, duplicate properties are allowed. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt new file mode 100644 index 00000000..b324608f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowImportant.txt @@ -0,0 +1,8 @@ +CSS.AllowImportant +TYPE: bool +DEFAULT: false +VERSION: 3.1.0 +--DESCRIPTION-- +This parameter determines whether or not !important cascade modifiers should +be allowed in user CSS. If false, !important will stripped. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt new file mode 100644 index 00000000..748be0ee --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowTricky.txt @@ -0,0 +1,11 @@ +CSS.AllowTricky +TYPE: bool +DEFAULT: false +VERSION: 3.1.0 +--DESCRIPTION-- +This parameter determines whether or not to allow "tricky" CSS properties and +values. Tricky CSS properties/values can drastically modify page layout or +be used for deceptive practices but do not directly constitute a security risk. +For example, display:none; is considered a tricky property that +will only be allowed if this directive is set to true. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt new file mode 100644 index 00000000..3fd46540 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedFonts.txt @@ -0,0 +1,12 @@ +CSS.AllowedFonts +TYPE: lookup/null +VERSION: 4.3.0 +DEFAULT: NULL +--DESCRIPTION-- +

    + Allows you to manually specify a set of allowed fonts. If + NULL, all fonts are allowed. This directive + affects generic names (serif, sans-serif, monospace, cursive, + fantasy) as well as specific font families. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt new file mode 100644 index 00000000..460112eb --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.AllowedProperties.txt @@ -0,0 +1,18 @@ +CSS.AllowedProperties +TYPE: lookup/null +VERSION: 3.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + If HTML Purifier's style attributes set is unsatisfactory for your needs, + you can overload it with your own list of tags to allow. Note that this + method is subtractive: it does its job by taking away from HTML Purifier + usual feature set, so you cannot add an attribute that HTML Purifier never + supported in the first place. +

    +

    + Warning: If another directive conflicts with the + elements here, that directive will win and override. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt new file mode 100644 index 00000000..5cb7dda3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.DefinitionRev.txt @@ -0,0 +1,11 @@ +CSS.DefinitionRev +TYPE: int +VERSION: 2.0.0 +DEFAULT: 1 +--DESCRIPTION-- + +

    + Revision identifier for your custom definition. See + %HTML.DefinitionRev for details. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt new file mode 100644 index 00000000..f1f5c5f1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.ForbiddenProperties.txt @@ -0,0 +1,13 @@ +CSS.ForbiddenProperties +TYPE: lookup +VERSION: 4.2.0 +DEFAULT: array() +--DESCRIPTION-- +

    + This is the logical inverse of %CSS.AllowedProperties, and it will + override that directive or any other directive. If possible, + %CSS.AllowedProperties is recommended over this directive, + because it can sometimes be difficult to tell whether or not you've + forbidden all of the CSS properties you truly would like to disallow. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt new file mode 100644 index 00000000..7a329147 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.MaxImgLength.txt @@ -0,0 +1,16 @@ +CSS.MaxImgLength +TYPE: string/null +DEFAULT: '1200px' +VERSION: 3.1.1 +--DESCRIPTION-- +

    + This parameter sets the maximum allowed length on img tags, + effectively the width and height properties. + Only absolute units of measurement (in, pt, pc, mm, cm) and pixels (px) are allowed. This is + in place to prevent imagecrash attacks, disable with null at your own risk. + This directive is similar to %HTML.MaxImgLength, and both should be + concurrently edited, although there are + subtle differences in the input format (the CSS max is a number with + a unit). +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt new file mode 100644 index 00000000..148eedb8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Proprietary.txt @@ -0,0 +1,10 @@ +CSS.Proprietary +TYPE: bool +VERSION: 3.0.0 +DEFAULT: false +--DESCRIPTION-- + +

    + Whether or not to allow safe, proprietary CSS values. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt new file mode 100644 index 00000000..e733a61e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/CSS.Trusted.txt @@ -0,0 +1,9 @@ +CSS.Trusted +TYPE: bool +VERSION: 4.2.1 +DEFAULT: false +--DESCRIPTION-- +Indicates whether or not the user's CSS input is trusted or not. If the +input is trusted, a more expansive set of allowed properties. See +also %HTML.Trusted. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt new file mode 100644 index 00000000..c486724c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.DefinitionImpl.txt @@ -0,0 +1,14 @@ +Cache.DefinitionImpl +TYPE: string/null +VERSION: 2.0.0 +DEFAULT: 'Serializer' +--DESCRIPTION-- + +This directive defines which method to use when caching definitions, +the complex data-type that makes HTML Purifier tick. Set to null +to disable caching (not recommended, as you will see a definite +performance degradation). + +--ALIASES-- +Core.DefinitionCache +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt new file mode 100644 index 00000000..54036507 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPath.txt @@ -0,0 +1,13 @@ +Cache.SerializerPath +TYPE: string/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + Absolute path with no trailing slash to store serialized definitions in. + Default is within the + HTML Purifier library inside DefinitionCache/Serializer. This + path must be writable by the webserver. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt new file mode 100644 index 00000000..2e0cc810 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Cache.SerializerPermissions.txt @@ -0,0 +1,16 @@ +Cache.SerializerPermissions +TYPE: int/null +VERSION: 4.3.0 +DEFAULT: 0755 +--DESCRIPTION-- + +

    + Directory permissions of the files and directories created inside + the DefinitionCache/Serializer or other custom serializer path. +

    +

    + In HTML Purifier 4.8.0, this also supports NULL, + which means that no chmod'ing or directory creation shall + occur. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt new file mode 100644 index 00000000..568cbf3b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyFixLt.txt @@ -0,0 +1,18 @@ +Core.AggressivelyFixLt +TYPE: bool +VERSION: 2.1.0 +DEFAULT: true +--DESCRIPTION-- +

    + This directive enables aggressive pre-filter fixes HTML Purifier can + perform in order to ensure that open angled-brackets do not get killed + during parsing stage. Enabling this will result in two preg_replace_callback + calls and at least two preg_replace calls for every HTML document parsed; + if your users make very well-formed HTML, you can set this directive false. + This has no effect when DirectLex is used. +

    +

    + Notice: This directive's default turned from false to true + in HTML Purifier 3.2.0. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt new file mode 100644 index 00000000..b2b6ab14 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AggressivelyRemoveScript.txt @@ -0,0 +1,16 @@ +Core.AggressivelyRemoveScript +TYPE: bool +VERSION: 4.9.0 +DEFAULT: true +--DESCRIPTION-- +

    + This directive enables aggressive pre-filter removal of + script tags. This is not necessary for security, + but it can help work around a bug in libxml where embedded + HTML elements inside script sections cause the parser to + choke. To revert to pre-4.9.0 behavior, set this to false. + This directive has no effect if %Core.Trusted is true, + %Core.RemoveScriptContents is false, or %Core.HiddenElements + does not contain script. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt new file mode 100644 index 00000000..2c910cc7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowHostnameUnderscore.txt @@ -0,0 +1,16 @@ +Core.AllowHostnameUnderscore +TYPE: bool +VERSION: 4.6.0 +DEFAULT: false +--DESCRIPTION-- +

    + By RFC 1123, underscores are not permitted in host names. + (This is in contrast to the specification for DNS, RFC + 2181, which allows underscores.) + However, most browsers do the right thing when faced with + an underscore in the host name, and so some poorly written + websites are written with the expectation this should work. + Setting this parameter to true relaxes our allowed character + check so that underscores are permitted. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt new file mode 100644 index 00000000..06278f82 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.AllowParseManyTags.txt @@ -0,0 +1,12 @@ +Core.AllowParseManyTags +TYPE: bool +DEFAULT: false +VERSION: 4.10.1 +--DESCRIPTION-- +

    + This directive allows parsing of many nested tags. + If you set true, relaxes any hardcoded limit from the parser. + However, in that case it may cause a Dos attack. + Be careful when enabling it. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt new file mode 100644 index 00000000..d7317911 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.CollectErrors.txt @@ -0,0 +1,12 @@ +Core.CollectErrors +TYPE: bool +VERSION: 2.0.0 +DEFAULT: false +--DESCRIPTION-- + +Whether or not to collect errors found while filtering the document. This +is a useful way to give feedback to your users. Warning: +Currently this feature is very patchy and experimental, with lots of +possible error messages not yet implemented. It will not cause any +problems, but it may not help your users either. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt new file mode 100644 index 00000000..a75844cd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ColorKeywords.txt @@ -0,0 +1,160 @@ +Core.ColorKeywords +TYPE: hash +VERSION: 2.0.0 +--DEFAULT-- +array ( + 'aliceblue' => '#F0F8FF', + 'antiquewhite' => '#FAEBD7', + 'aqua' => '#00FFFF', + 'aquamarine' => '#7FFFD4', + 'azure' => '#F0FFFF', + 'beige' => '#F5F5DC', + 'bisque' => '#FFE4C4', + 'black' => '#000000', + 'blanchedalmond' => '#FFEBCD', + 'blue' => '#0000FF', + 'blueviolet' => '#8A2BE2', + 'brown' => '#A52A2A', + 'burlywood' => '#DEB887', + 'cadetblue' => '#5F9EA0', + 'chartreuse' => '#7FFF00', + 'chocolate' => '#D2691E', + 'coral' => '#FF7F50', + 'cornflowerblue' => '#6495ED', + 'cornsilk' => '#FFF8DC', + 'crimson' => '#DC143C', + 'cyan' => '#00FFFF', + 'darkblue' => '#00008B', + 'darkcyan' => '#008B8B', + 'darkgoldenrod' => '#B8860B', + 'darkgray' => '#A9A9A9', + 'darkgrey' => '#A9A9A9', + 'darkgreen' => '#006400', + 'darkkhaki' => '#BDB76B', + 'darkmagenta' => '#8B008B', + 'darkolivegreen' => '#556B2F', + 'darkorange' => '#FF8C00', + 'darkorchid' => '#9932CC', + 'darkred' => '#8B0000', + 'darksalmon' => '#E9967A', + 'darkseagreen' => '#8FBC8F', + 'darkslateblue' => '#483D8B', + 'darkslategray' => '#2F4F4F', + 'darkslategrey' => '#2F4F4F', + 'darkturquoise' => '#00CED1', + 'darkviolet' => '#9400D3', + 'deeppink' => '#FF1493', + 'deepskyblue' => '#00BFFF', + 'dimgray' => '#696969', + 'dimgrey' => '#696969', + 'dodgerblue' => '#1E90FF', + 'firebrick' => '#B22222', + 'floralwhite' => '#FFFAF0', + 'forestgreen' => '#228B22', + 'fuchsia' => '#FF00FF', + 'gainsboro' => '#DCDCDC', + 'ghostwhite' => '#F8F8FF', + 'gold' => '#FFD700', + 'goldenrod' => '#DAA520', + 'gray' => '#808080', + 'grey' => '#808080', + 'green' => '#008000', + 'greenyellow' => '#ADFF2F', + 'honeydew' => '#F0FFF0', + 'hotpink' => '#FF69B4', + 'indianred' => '#CD5C5C', + 'indigo' => '#4B0082', + 'ivory' => '#FFFFF0', + 'khaki' => '#F0E68C', + 'lavender' => '#E6E6FA', + 'lavenderblush' => '#FFF0F5', + 'lawngreen' => '#7CFC00', + 'lemonchiffon' => '#FFFACD', + 'lightblue' => '#ADD8E6', + 'lightcoral' => '#F08080', + 'lightcyan' => '#E0FFFF', + 'lightgoldenrodyellow' => '#FAFAD2', + 'lightgray' => '#D3D3D3', + 'lightgrey' => '#D3D3D3', + 'lightgreen' => '#90EE90', + 'lightpink' => '#FFB6C1', + 'lightsalmon' => '#FFA07A', + 'lightseagreen' => '#20B2AA', + 'lightskyblue' => '#87CEFA', + 'lightslategray' => '#778899', + 'lightslategrey' => '#778899', + 'lightsteelblue' => '#B0C4DE', + 'lightyellow' => '#FFFFE0', + 'lime' => '#00FF00', + 'limegreen' => '#32CD32', + 'linen' => '#FAF0E6', + 'magenta' => '#FF00FF', + 'maroon' => '#800000', + 'mediumaquamarine' => '#66CDAA', + 'mediumblue' => '#0000CD', + 'mediumorchid' => '#BA55D3', + 'mediumpurple' => '#9370DB', + 'mediumseagreen' => '#3CB371', + 'mediumslateblue' => '#7B68EE', + 'mediumspringgreen' => '#00FA9A', + 'mediumturquoise' => '#48D1CC', + 'mediumvioletred' => '#C71585', + 'midnightblue' => '#191970', + 'mintcream' => '#F5FFFA', + 'mistyrose' => '#FFE4E1', + 'moccasin' => '#FFE4B5', + 'navajowhite' => '#FFDEAD', + 'navy' => '#000080', + 'oldlace' => '#FDF5E6', + 'olive' => '#808000', + 'olivedrab' => '#6B8E23', + 'orange' => '#FFA500', + 'orangered' => '#FF4500', + 'orchid' => '#DA70D6', + 'palegoldenrod' => '#EEE8AA', + 'palegreen' => '#98FB98', + 'paleturquoise' => '#AFEEEE', + 'palevioletred' => '#DB7093', + 'papayawhip' => '#FFEFD5', + 'peachpuff' => '#FFDAB9', + 'peru' => '#CD853F', + 'pink' => '#FFC0CB', + 'plum' => '#DDA0DD', + 'powderblue' => '#B0E0E6', + 'purple' => '#800080', + 'rebeccapurple' => '#663399', + 'red' => '#FF0000', + 'rosybrown' => '#BC8F8F', + 'royalblue' => '#4169E1', + 'saddlebrown' => '#8B4513', + 'salmon' => '#FA8072', + 'sandybrown' => '#F4A460', + 'seagreen' => '#2E8B57', + 'seashell' => '#FFF5EE', + 'sienna' => '#A0522D', + 'silver' => '#C0C0C0', + 'skyblue' => '#87CEEB', + 'slateblue' => '#6A5ACD', + 'slategray' => '#708090', + 'slategrey' => '#708090', + 'snow' => '#FFFAFA', + 'springgreen' => '#00FF7F', + 'steelblue' => '#4682B4', + 'tan' => '#D2B48C', + 'teal' => '#008080', + 'thistle' => '#D8BFD8', + 'tomato' => '#FF6347', + 'turquoise' => '#40E0D0', + 'violet' => '#EE82EE', + 'wheat' => '#F5DEB3', + 'white' => '#FFFFFF', + 'whitesmoke' => '#F5F5F5', + 'yellow' => '#FFFF00', + 'yellowgreen' => '#9ACD32' +) +--DESCRIPTION-- + +Lookup array of color names to six digit hexadecimal number corresponding +to color, with preceding hash mark. Used when parsing colors. The lookup +is done in a case-insensitive manner. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt new file mode 100644 index 00000000..64b114fc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.ConvertDocumentToFragment.txt @@ -0,0 +1,14 @@ +Core.ConvertDocumentToFragment +TYPE: bool +DEFAULT: true +--DESCRIPTION-- + +This parameter determines whether or not the filter should convert +input that is a full document with html and body tags to a fragment +of just the contents of a body tag. This parameter is simply something +HTML Purifier can do during an edge-case: for most inputs, this +processing is not necessary. + +--ALIASES-- +Core.AcceptFullDocuments +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt new file mode 100644 index 00000000..36f16e07 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DirectLexLineNumberSyncInterval.txt @@ -0,0 +1,17 @@ +Core.DirectLexLineNumberSyncInterval +TYPE: int +VERSION: 2.0.0 +DEFAULT: 0 +--DESCRIPTION-- + +

    + Specifies the number of tokens the DirectLex line number tracking + implementations should process before attempting to resyncronize the + current line count by manually counting all previous new-lines. When + at 0, this functionality is disabled. Lower values will decrease + performance, and this is only strictly necessary if the counting + algorithm is buggy (in which case you should report it as a bug). + This has no effect when %Core.MaintainLineNumbers is disabled or DirectLex is + not being used. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt new file mode 100644 index 00000000..1cd4c2c9 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.DisableExcludes.txt @@ -0,0 +1,14 @@ +Core.DisableExcludes +TYPE: bool +DEFAULT: false +VERSION: 4.5.0 +--DESCRIPTION-- +

    + This directive disables SGML-style exclusions, e.g. the exclusion of + <object> in any descendant of a + <pre> tag. Disabling excludes will allow some + invalid documents to pass through HTML Purifier, but HTML Purifier + will also be less likely to accidentally remove large documents during + processing. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt new file mode 100644 index 00000000..ce243c35 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EnableIDNA.txt @@ -0,0 +1,9 @@ +Core.EnableIDNA +TYPE: bool +DEFAULT: false +VERSION: 4.4.0 +--DESCRIPTION-- +Allows international domain names in URLs. This configuration option +requires the PEAR Net_IDNA2 module to be installed. It operates by +punycoding any internationalized host names for maximum portability. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt new file mode 100644 index 00000000..8bfb47c3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Encoding.txt @@ -0,0 +1,15 @@ +Core.Encoding +TYPE: istring +DEFAULT: 'utf-8' +--DESCRIPTION-- +If for some reason you are unable to convert all webpages to UTF-8, you can +use this directive as a stop-gap compatibility change to let HTML Purifier +deal with non UTF-8 input. This technique has notable deficiencies: +absolutely no characters outside of the selected character encoding will be +preserved, not even the ones that have been ampersand escaped (this is due +to a UTF-8 specific feature that automatically resolves all +entities), making it pretty useless for anything except the most I18N-blind +applications, although %Core.EscapeNonASCIICharacters offers fixes this +trouble with another tradeoff. This directive only accepts ISO-8859-1 if +iconv is not enabled. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt new file mode 100644 index 00000000..a3881be7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidChildren.txt @@ -0,0 +1,12 @@ +Core.EscapeInvalidChildren +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +

    Warning: this configuration option is no longer does anything as of 4.6.0.

    + +

    When true, a child is found that is not allowed in the context of the +parent element will be transformed into text as if it were ASCII. When +false, that element and all internal tags will be dropped, though text will +be preserved. There is no option for dropping the element but preserving +child nodes.

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt new file mode 100644 index 00000000..a7a5b249 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeInvalidTags.txt @@ -0,0 +1,7 @@ +Core.EscapeInvalidTags +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +When true, invalid tags will be written back to the document as plain text. +Otherwise, they are silently dropped. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt new file mode 100644 index 00000000..abb49994 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.EscapeNonASCIICharacters.txt @@ -0,0 +1,13 @@ +Core.EscapeNonASCIICharacters +TYPE: bool +VERSION: 1.4.0 +DEFAULT: false +--DESCRIPTION-- +This directive overcomes a deficiency in %Core.Encoding by blindly +converting all non-ASCII characters into decimal numeric entities before +converting it to its native encoding. This means that even characters that +can be expressed in the non-UTF-8 encoding will be entity-ized, which can +be a real downer for encodings like Big5. It also assumes that the ASCII +repetoire is available, although this is the case for almost all encodings. +Anyway, use UTF-8! +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt new file mode 100644 index 00000000..915391ed --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.HiddenElements.txt @@ -0,0 +1,19 @@ +Core.HiddenElements +TYPE: lookup +--DEFAULT-- +array ( + 'script' => true, + 'style' => true, +) +--DESCRIPTION-- + +

    + This directive is a lookup array of elements which should have their + contents removed when they are not allowed by the HTML definition. + For example, the contents of a script tag are not + normally shown in a document, so if script tags are to be removed, + their contents should be removed to. This is opposed to a b + tag, which defines some presentational changes but does not hide its + contents. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt new file mode 100644 index 00000000..233fca14 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.Language.txt @@ -0,0 +1,10 @@ +Core.Language +TYPE: string +VERSION: 2.0.0 +DEFAULT: 'en' +--DESCRIPTION-- + +ISO 639 language code for localizable things in HTML Purifier to use, +which is mainly error reporting. There is currently only an English (en) +translation, so this directive is currently useless. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt new file mode 100644 index 00000000..392b4364 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LegacyEntityDecoder.txt @@ -0,0 +1,36 @@ +Core.LegacyEntityDecoder +TYPE: bool +VERSION: 4.9.0 +DEFAULT: false +--DESCRIPTION-- +

    + Prior to HTML Purifier 4.9.0, entities were decoded by performing + a global search replace for all entities whose decoded versions + did not have special meanings under HTML, and replaced them with + their decoded versions. We would match all entities, even if they did + not have a trailing semicolon, but only if there weren't any trailing + alphanumeric characters. +

    + + + + + + +
    OriginalTextAttribute
    &yen;¥¥
    &yen¥¥
    &yena&yena&yena
    &yen=¥=¥=
    +

    + In HTML Purifier 4.9.0, we changed the behavior of entity parsing + to match entities that had missing trailing semicolons in less + cases, to more closely match HTML5 parsing behavior: +

    + + + + + + +
    OriginalTextAttribute
    &yen;¥¥
    &yen¥¥
    &yena¥a&yena
    &yen=¥=&yen=
    +

    + This flag reverts back to pre-HTML Purifier 4.9.0 behavior. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt new file mode 100644 index 00000000..8983e2cc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.LexerImpl.txt @@ -0,0 +1,34 @@ +Core.LexerImpl +TYPE: mixed/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + This parameter determines what lexer implementation can be used. The + valid values are: +

    +
    +
    null
    +
    + Recommended, the lexer implementation will be auto-detected based on + your PHP-version and configuration. +
    +
    string lexer identifier
    +
    + This is a slim way of manually overridding the implementation. + Currently recognized values are: DOMLex (the default PHP5 +implementation) + and DirectLex (the default PHP4 implementation). Only use this if + you know what you are doing: usually, the auto-detection will + manage things for cases you aren't even aware of. +
    +
    object lexer instance
    +
    + Super-advanced: you can specify your own, custom, implementation that + implements the interface defined by HTMLPurifier_Lexer. + I may remove this option simply because I don't expect anyone + to use it. +
    +
    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt new file mode 100644 index 00000000..eb841a75 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.MaintainLineNumbers.txt @@ -0,0 +1,16 @@ +Core.MaintainLineNumbers +TYPE: bool/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + If true, HTML Purifier will add line number information to all tokens. + This is useful when error reporting is turned on, but can result in + significant performance degradation and should not be used when + unnecessary. This directive must be used with the DirectLex lexer, + as the DOMLex lexer does not (yet) support this functionality. + If the value is null, an appropriate value will be selected based + on other configuration. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt new file mode 100644 index 00000000..d77f5360 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.NormalizeNewlines.txt @@ -0,0 +1,11 @@ +Core.NormalizeNewlines +TYPE: bool +VERSION: 4.2.0 +DEFAULT: true +--DESCRIPTION-- +

    + Whether or not to normalize newlines to the operating + system default. When false, HTML Purifier + will attempt to preserve mixed newline files. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt new file mode 100644 index 00000000..4070c2a0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveInvalidImg.txt @@ -0,0 +1,12 @@ +Core.RemoveInvalidImg +TYPE: bool +DEFAULT: true +VERSION: 1.3.0 +--DESCRIPTION-- + +

    + This directive enables pre-emptive URI checking in img + tags, as the attribute validation strategy is not authorized to + remove elements from the document. Revert to pre-1.3.0 behavior by setting to false. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt new file mode 100644 index 00000000..3397d9f7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveProcessingInstructions.txt @@ -0,0 +1,11 @@ +Core.RemoveProcessingInstructions +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +Instead of escaping processing instructions in the form <? ... +?>, remove it out-right. This may be useful if the HTML +you are validating contains XML processing instruction gunk, however, +it can also be user-unfriendly for people attempting to post PHP +snippets. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt new file mode 100644 index 00000000..a4cd966d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Core.RemoveScriptContents.txt @@ -0,0 +1,12 @@ +Core.RemoveScriptContents +TYPE: bool/null +DEFAULT: NULL +VERSION: 2.0.0 +DEPRECATED-VERSION: 2.1.0 +DEPRECATED-USE: Core.HiddenElements +--DESCRIPTION-- +

    + This directive enables HTML Purifier to remove not only script tags + but all of their contents. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt new file mode 100644 index 00000000..3db50ef2 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.Custom.txt @@ -0,0 +1,11 @@ +Filter.Custom +TYPE: list +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

    + This directive can be used to add custom filters; it is nearly the + equivalent of the now deprecated HTMLPurifier->addFilter() + method. Specify an array of concrete implementations. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt new file mode 100644 index 00000000..16829bcd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Escaping.txt @@ -0,0 +1,14 @@ +Filter.ExtractStyleBlocks.Escaping +TYPE: bool +VERSION: 3.0.0 +DEFAULT: true +ALIASES: Filter.ExtractStyleBlocksEscaping, FilterParam.ExtractStyleBlocksEscaping +--DESCRIPTION-- + +

    + Whether or not to escape the dangerous characters <, > and & + as \3C, \3E and \26, respectively. This is can be safely set to false + if the contents of StyleBlocks will be placed in an external stylesheet, + where there is no risk of it being interpreted as HTML. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt new file mode 100644 index 00000000..7f95f54d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.Scope.txt @@ -0,0 +1,29 @@ +Filter.ExtractStyleBlocks.Scope +TYPE: string/null +VERSION: 3.0.0 +DEFAULT: NULL +ALIASES: Filter.ExtractStyleBlocksScope, FilterParam.ExtractStyleBlocksScope +--DESCRIPTION-- + +

    + If you would like users to be able to define external stylesheets, but + only allow them to specify CSS declarations for a specific node and + prevent them from fiddling with other elements, use this directive. + It accepts any valid CSS selector, and will prepend this to any + CSS declaration extracted from the document. For example, if this + directive is set to #user-content and a user uses the + selector a:hover, the final selector will be + #user-content a:hover. +

    +

    + The comma shorthand may be used; consider the above example, with + #user-content, #user-content2, the final selector will + be #user-content a:hover, #user-content2 a:hover. +

    +

    + Warning: It is possible for users to bypass this measure + using a naughty + selector. This is a bug in CSS Tidy 1.3, not HTML + Purifier, and I am working to get it fixed. Until then, HTML Purifier + performs a basic check to prevent this. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt new file mode 100644 index 00000000..6c231b2d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.TidyImpl.txt @@ -0,0 +1,16 @@ +Filter.ExtractStyleBlocks.TidyImpl +TYPE: mixed/null +VERSION: 3.1.0 +DEFAULT: NULL +ALIASES: FilterParam.ExtractStyleBlocksTidyImpl +--DESCRIPTION-- +

    + If left NULL, HTML Purifier will attempt to instantiate a csstidy + class to use for internal cleaning. This will usually be good enough. +

    +

    + However, for trusted user input, you can set this to false to + disable cleaning. In addition, you can supply your own concrete implementation + of Tidy's interface to use, although I don't know why you'd want to do that. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt new file mode 100644 index 00000000..078d0874 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.ExtractStyleBlocks.txt @@ -0,0 +1,74 @@ +Filter.ExtractStyleBlocks +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +EXTERNAL: CSSTidy +--DESCRIPTION-- +

    + This directive turns on the style block extraction filter, which removes + style blocks from input HTML, cleans them up with CSSTidy, + and places them in the StyleBlocks context variable, for further + use by you, usually to be placed in an external stylesheet, or a + style block in the head of your document. +

    +

    + Sample usage: +

    +
    ';
    +?>
    +
    +
    +
    +  Filter.ExtractStyleBlocks
    +body {color:#F00;} Some text';
    +
    +    $config = HTMLPurifier_Config::createDefault();
    +    $config->set('Filter', 'ExtractStyleBlocks', true);
    +    $purifier = new HTMLPurifier($config);
    +
    +    $html = $purifier->purify($dirty);
    +
    +    // This implementation writes the stylesheets to the styles/ directory.
    +    // You can also echo the styles inside the document, but it's a bit
    +    // more difficult to make sure they get interpreted properly by
    +    // browsers; try the usual CSS armoring techniques.
    +    $styles = $purifier->context->get('StyleBlocks');
    +    $dir = 'styles/';
    +    if (!is_dir($dir)) mkdir($dir);
    +    $hash = sha1($_GET['html']);
    +    foreach ($styles as $i => $style) {
    +        file_put_contents($name = $dir . $hash . "_$i");
    +        echo '';
    +    }
    +?>
    +
    +
    +  
    + +
    + + +]]>
    +

    + Warning: It is possible for a user to mount an + imagecrash attack using this CSS. Counter-measures are difficult; + it is not simply enough to limit the range of CSS lengths (using + relative lengths with many nesting levels allows for large values + to be attained without actually specifying them in the stylesheet), + and the flexible nature of selectors makes it difficult to selectively + disable lengths on image tags (HTML Purifier, however, does disable + CSS width and height in inline styling). There are probably two effective + counter measures: an explicit width and height set to auto in all + images in your document (unlikely) or the disabling of width and + height (somewhat reasonable). Whether or not these measures should be + used is left to the reader. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt new file mode 100644 index 00000000..321eaa2d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Filter.YouTube.txt @@ -0,0 +1,16 @@ +Filter.YouTube +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +--DESCRIPTION-- +

    + Warning: Deprecated in favor of %HTML.SafeObject and + %Output.FlashCompat (turn both on to allow YouTube videos and other + Flash content). +

    +

    + This directive enables YouTube video embedding in HTML Purifier. Check + this document + on embedding videos for more information on what this filter does. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt new file mode 100644 index 00000000..0b2c106d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Allowed.txt @@ -0,0 +1,25 @@ +HTML.Allowed +TYPE: itext/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + This is a preferred convenience directive that combines + %HTML.AllowedElements and %HTML.AllowedAttributes. + Specify elements and attributes that are allowed using: + element1[attr1|attr2],element2.... For example, + if you would like to only allow paragraphs and links, specify + a[href],p. You can specify attributes that apply + to all elements using an asterisk, e.g. *[lang]. + You can also use newlines instead of commas to separate elements. +

    +

    + Warning: + All of the constraints on the component directives are still enforced. + The syntax is a subset of TinyMCE's valid_elements + whitelist: directly copy-pasting it here will probably result in + broken whitelists. If %HTML.AllowedElements or %HTML.AllowedAttributes + are set, this directive has no effect. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt new file mode 100644 index 00000000..fcf093f1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedAttributes.txt @@ -0,0 +1,19 @@ +HTML.AllowedAttributes +TYPE: lookup/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + If HTML Purifier's attribute set is unsatisfactory, overload it! + The syntax is "tag.attr" or "*.attr" for the global attributes + (style, id, class, dir, lang, xml:lang). +

    +

    + Warning: If another directive conflicts with the + elements here, that directive will win and override. For + example, %HTML.EnableAttrID will take precedence over *.id in this + directive. You must set that directive to true before you can use + IDs at all. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt new file mode 100644 index 00000000..140e2142 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedComments.txt @@ -0,0 +1,10 @@ +HTML.AllowedComments +TYPE: lookup +VERSION: 4.4.0 +DEFAULT: array() +--DESCRIPTION-- +A whitelist which indicates what explicit comment bodies should be +allowed, modulo leading and trailing whitespace. See also %HTML.AllowedCommentsRegexp +(these directives are union'ed together, so a comment is considered +valid if any directive deems it valid.) +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt new file mode 100644 index 00000000..f22e977d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedCommentsRegexp.txt @@ -0,0 +1,15 @@ +HTML.AllowedCommentsRegexp +TYPE: string/null +VERSION: 4.4.0 +DEFAULT: NULL +--DESCRIPTION-- +A regexp, which if it matches the body of a comment, indicates that +it should be allowed. Trailing and leading spaces are removed prior +to running this regular expression. +Warning: Make sure you specify +correct anchor metacharacters ^regex$, otherwise you may accept +comments that you did not mean to! In particular, the regex /foo|bar/ +is probably not sufficiently strict, since it also allows foobar. +See also %HTML.AllowedComments (these directives are union'ed together, +so a comment is considered valid if any directive deems it valid.) +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt new file mode 100644 index 00000000..1d3fa790 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedElements.txt @@ -0,0 +1,23 @@ +HTML.AllowedElements +TYPE: lookup/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- +

    + If HTML Purifier's tag set is unsatisfactory for your needs, you can + overload it with your own list of tags to allow. If you change + this, you probably also want to change %HTML.AllowedAttributes; see + also %HTML.Allowed which lets you set allowed elements and + attributes at the same time. +

    +

    + If you attempt to allow an element that HTML Purifier does not know + about, HTML Purifier will raise an error. You will need to manually + tell HTML Purifier about this element by using the + advanced customization features. +

    +

    + Warning: If another directive conflicts with the + elements here, that directive will win and override. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt new file mode 100644 index 00000000..5a59a55c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.AllowedModules.txt @@ -0,0 +1,20 @@ +HTML.AllowedModules +TYPE: lookup/null +VERSION: 2.0.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + A doctype comes with a set of usual modules to use. Without having + to mucking about with the doctypes, you can quickly activate or + disable these modules by specifying which modules you wish to allow + with this directive. This is most useful for unit testing specific + modules, although end users may find it useful for their own ends. +

    +

    + If you specify a module that does not exist, the manager will silently + fail to use it, so be careful! User-defined modules are not affected + by this directive. Modules defined in %HTML.CoreModules are not + affected by this directive. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt new file mode 100644 index 00000000..151fb7b8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Attr.Name.UseCDATA.txt @@ -0,0 +1,11 @@ +HTML.Attr.Name.UseCDATA +TYPE: bool +DEFAULT: false +VERSION: 4.0.0 +--DESCRIPTION-- +The W3C specification DTD defines the name attribute to be CDATA, not ID, due +to limitations of DTD. In certain documents, this relaxed behavior is desired, +whether it is to specify duplicate names, or to specify names that would be +illegal IDs (for example, names that begin with a digit.) Set this configuration +directive to true to use the relaxed parsing rules. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt new file mode 100644 index 00000000..45ae469e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.BlockWrapper.txt @@ -0,0 +1,18 @@ +HTML.BlockWrapper +TYPE: string +VERSION: 1.3.0 +DEFAULT: 'p' +--DESCRIPTION-- + +

    + String name of element to wrap inline elements that are inside a block + context. This only occurs in the children of blockquote in strict mode. +

    +

    + Example: by default value, + <blockquote>Foo</blockquote> would become + <blockquote><p>Foo</p></blockquote>. + The <p> tags can be replaced with whatever you desire, + as long as it is a block level element. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt new file mode 100644 index 00000000..52461887 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CoreModules.txt @@ -0,0 +1,23 @@ +HTML.CoreModules +TYPE: lookup +VERSION: 2.0.0 +--DEFAULT-- +array ( + 'Structure' => true, + 'Text' => true, + 'Hypertext' => true, + 'List' => true, + 'NonXMLCommonAttributes' => true, + 'XMLCommonAttributes' => true, + 'CommonAttributes' => true, +) +--DESCRIPTION-- + +

    + Certain modularized doctypes (XHTML, namely), have certain modules + that must be included for the doctype to be an conforming document + type: put those modules here. By default, XHTML's core modules + are used. You can set this to a blank array to disable core module + protection, but this is not recommended. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt new file mode 100644 index 00000000..6ed70b59 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.CustomDoctype.txt @@ -0,0 +1,9 @@ +HTML.CustomDoctype +TYPE: string/null +VERSION: 2.0.1 +DEFAULT: NULL +--DESCRIPTION-- + +A custom doctype for power-users who defined their own document +type. This directive only applies when %HTML.Doctype is blank. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt new file mode 100644 index 00000000..103db754 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt @@ -0,0 +1,33 @@ +HTML.DefinitionID +TYPE: string/null +DEFAULT: NULL +VERSION: 2.0.0 +--DESCRIPTION-- + +

    + Unique identifier for a custom-built HTML definition. If you edit + the raw version of the HTMLDefinition, introducing changes that the + configuration object does not reflect, you must specify this variable. + If you change your custom edits, you should change this directive, or + clear your cache. Example: +

    +
    +$config = HTMLPurifier_Config::createDefault();
    +$config->set('HTML', 'DefinitionID', '1');
    +$def = $config->getHTMLDefinition();
    +$def->addAttribute('a', 'tabindex', 'Number');
    +
    +

    + In the above example, the configuration is still at the defaults, but + using the advanced API, an extra attribute has been added. The + configuration object normally has no way of knowing that this change + has taken place, so it needs an extra directive: %HTML.DefinitionID. + If someone else attempts to use the default configuration, these two + pieces of code will not clobber each other in the cache, since one has + an extra directive attached to it. +

    +

    + You must specify a value to this directive to use the + advanced API features. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt new file mode 100644 index 00000000..229ae026 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionRev.txt @@ -0,0 +1,16 @@ +HTML.DefinitionRev +TYPE: int +VERSION: 2.0.0 +DEFAULT: 1 +--DESCRIPTION-- + +

    + Revision identifier for your custom definition specified in + %HTML.DefinitionID. This serves the same purpose: uniquely identifying + your custom definition, but this one does so in a chronological + context: revision 3 is more up-to-date then revision 2. Thus, when + this gets incremented, the cache handling is smart enough to clean + up any older revisions of your definition as well as flush the + cache. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt new file mode 100644 index 00000000..9dab497f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Doctype.txt @@ -0,0 +1,11 @@ +HTML.Doctype +TYPE: string/null +DEFAULT: NULL +--DESCRIPTION-- +Doctype to use during filtering. Technically speaking this is not actually +a doctype (as it does not identify a corresponding DTD), but we are using +this name for sake of simplicity. When non-blank, this will override any +older directives like %HTML.XHTML or %HTML.Strict. +--ALLOWED-- +'HTML 4.01 Transitional', 'HTML 4.01 Strict', 'XHTML 1.0 Transitional', 'XHTML 1.0 Strict', 'XHTML 1.1' +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt new file mode 100644 index 00000000..7878dc0b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.FlashAllowFullScreen.txt @@ -0,0 +1,11 @@ +HTML.FlashAllowFullScreen +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to permit embedded Flash content from + %HTML.SafeObject to expand to the full screen. Corresponds to + the allowFullScreen parameter. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt new file mode 100644 index 00000000..57358f9b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenAttributes.txt @@ -0,0 +1,21 @@ +HTML.ForbiddenAttributes +TYPE: lookup +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

    + While this directive is similar to %HTML.AllowedAttributes, for + forwards-compatibility with XML, this attribute has a different syntax. Instead of + tag.attr, use tag@attr. To disallow href + attributes in a tags, set this directive to + a@href. You can also disallow an attribute globally with + attr or *@attr (either syntax is fine; the latter + is provided for consistency with %HTML.AllowedAttributes). +

    +

    + Warning: This directive complements %HTML.ForbiddenElements, + accordingly, check + out that directive for a discussion of why you + should think twice before using this directive. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt new file mode 100644 index 00000000..93a53e14 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.ForbiddenElements.txt @@ -0,0 +1,20 @@ +HTML.ForbiddenElements +TYPE: lookup +VERSION: 3.1.0 +DEFAULT: array() +--DESCRIPTION-- +

    + This was, perhaps, the most requested feature ever in HTML + Purifier. Please don't abuse it! This is the logical inverse of + %HTML.AllowedElements, and it will override that directive, or any + other directive. +

    +

    + If possible, %HTML.Allowed is recommended over this directive, because it + can sometimes be difficult to tell whether or not you've forbidden all of + the behavior you would like to disallow. If you forbid img + with the expectation of preventing images on your site, you'll be in for + a nasty surprise when people start using the background-image + CSS property. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt new file mode 100644 index 00000000..4a432d89 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Forms.txt @@ -0,0 +1,11 @@ +HTML.Forms +TYPE: bool +VERSION: 4.13.0 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to permit form elements in the user input, regardless of + %HTML.Trusted value. Please be very careful when using this functionality, as + enabling forms in untrusted documents may allow for phishing attacks. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt new file mode 100644 index 00000000..e424c386 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.MaxImgLength.txt @@ -0,0 +1,14 @@ +HTML.MaxImgLength +TYPE: int/null +DEFAULT: 1200 +VERSION: 3.1.1 +--DESCRIPTION-- +

    + This directive controls the maximum number of pixels in the width and + height attributes in img tags. This is + in place to prevent imagecrash attacks, disable with null at your own risk. + This directive is similar to %CSS.MaxImgLength, and both should be + concurrently edited, although there are + subtle differences in the input format (the HTML max is an integer). +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt new file mode 100644 index 00000000..700b3092 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Nofollow.txt @@ -0,0 +1,7 @@ +HTML.Nofollow +TYPE: bool +VERSION: 4.3.0 +DEFAULT: FALSE +--DESCRIPTION-- +If enabled, nofollow rel attributes are added to all outgoing links. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt new file mode 100644 index 00000000..62e8e160 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Parent.txt @@ -0,0 +1,12 @@ +HTML.Parent +TYPE: string +VERSION: 1.3.0 +DEFAULT: 'div' +--DESCRIPTION-- + +

    + String name of element that HTML fragment passed to library will be + inserted in. An interesting variation would be using span as the + parent element, meaning that only inline tags would be allowed. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt new file mode 100644 index 00000000..dfb72049 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Proprietary.txt @@ -0,0 +1,12 @@ +HTML.Proprietary +TYPE: bool +VERSION: 3.1.0 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to allow proprietary elements and attributes in your + documents, as per HTMLPurifier_HTMLModule_Proprietary. + Warning: This can cause your documents to stop + validating! +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt new file mode 100644 index 00000000..cdda09a4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeEmbed.txt @@ -0,0 +1,13 @@ +HTML.SafeEmbed +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to permit embed tags in documents, with a number of extra + security features added to prevent script execution. This is similar to + what websites like MySpace do to embed tags. Embed is a proprietary + element and will cause your website to stop validating; you should + see if you can use %Output.FlashCompat with %HTML.SafeObject instead + first.

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt new file mode 100644 index 00000000..5eb6ec2b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeIframe.txt @@ -0,0 +1,13 @@ +HTML.SafeIframe +TYPE: bool +VERSION: 4.4.0 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to permit iframe tags in untrusted documents. This + directive must be accompanied by a whitelist of permitted iframes, + such as %URI.SafeIframeRegexp, otherwise it will fatally error. + This directive has no effect on strict doctypes, as iframes are not + valid. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt new file mode 100644 index 00000000..ceb342e2 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeObject.txt @@ -0,0 +1,13 @@ +HTML.SafeObject +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

    + Whether or not to permit object tags in documents, with a number of extra + security features added to prevent script execution. This is similar to + what websites like MySpace do to object tags. You should also enable + %Output.FlashCompat in order to generate Internet Explorer + compatibility code for your object tags. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt new file mode 100644 index 00000000..5ebc7a19 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.SafeScripting.txt @@ -0,0 +1,10 @@ +HTML.SafeScripting +TYPE: lookup +VERSION: 4.5.0 +DEFAULT: array() +--DESCRIPTION-- +

    + Whether or not to permit script tags to external scripts in documents. + Inline scripting is not allowed, and the script must match an explicit whitelist. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt new file mode 100644 index 00000000..a8b1de56 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Strict.txt @@ -0,0 +1,9 @@ +HTML.Strict +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +DEPRECATED-VERSION: 1.7.0 +DEPRECATED-USE: HTML.Doctype +--DESCRIPTION-- +Determines whether or not to use Transitional (loose) or Strict rulesets. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt new file mode 100644 index 00000000..587a1677 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetBlank.txt @@ -0,0 +1,8 @@ +HTML.TargetBlank +TYPE: bool +VERSION: 4.4.0 +DEFAULT: FALSE +--DESCRIPTION-- +If enabled, target=blank attributes are added to all outgoing links. +(This includes links from an HTTPS version of a page to an HTTP version.) +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt new file mode 100644 index 00000000..dd514c0d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoopener.txt @@ -0,0 +1,10 @@ +--# vim: et sw=4 sts=4 +HTML.TargetNoopener +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noopener rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt new file mode 100644 index 00000000..cb5a0b0e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TargetNoreferrer.txt @@ -0,0 +1,9 @@ +HTML.TargetNoreferrer +TYPE: bool +VERSION: 4.8.0 +DEFAULT: TRUE +--DESCRIPTION-- +If enabled, noreferrer rel attributes are added to links which have +a target attribute associated with them. This prevents malicious +destinations from overwriting the original window. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt new file mode 100644 index 00000000..b4c271b7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyAdd.txt @@ -0,0 +1,8 @@ +HTML.TidyAdd +TYPE: lookup +VERSION: 2.0.0 +DEFAULT: array() +--DESCRIPTION-- + +Fixes to add to the default set of Tidy fixes as per your level. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt new file mode 100644 index 00000000..4186ccd0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyLevel.txt @@ -0,0 +1,24 @@ +HTML.TidyLevel +TYPE: string +VERSION: 2.0.0 +DEFAULT: 'medium' +--DESCRIPTION-- + +

    General level of cleanliness the Tidy module should enforce. +There are four allowed values:

    +
    +
    none
    +
    No extra tidying should be done
    +
    light
    +
    Only fix elements that would be discarded otherwise due to + lack of support in doctype
    +
    medium
    +
    Enforce best practices
    +
    heavy
    +
    Transform all deprecated elements and attributes to standards + compliant equivalents
    +
    + +--ALLOWED-- +'none', 'light', 'medium', 'heavy' +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt new file mode 100644 index 00000000..996762bd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.TidyRemove.txt @@ -0,0 +1,8 @@ +HTML.TidyRemove +TYPE: lookup +VERSION: 2.0.0 +DEFAULT: array() +--DESCRIPTION-- + +Fixes to remove from the default set of Tidy fixes as per your level. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt new file mode 100644 index 00000000..1db9237e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.Trusted.txt @@ -0,0 +1,9 @@ +HTML.Trusted +TYPE: bool +VERSION: 2.0.0 +DEFAULT: false +--DESCRIPTION-- +Indicates whether or not the user input is trusted or not. If the input is +trusted, a more expansive set of allowed tags and attributes will be used. +See also %CSS.Trusted. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt new file mode 100644 index 00000000..2a47e384 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/HTML.XHTML.txt @@ -0,0 +1,11 @@ +HTML.XHTML +TYPE: bool +DEFAULT: true +VERSION: 1.1.0 +DEPRECATED-VERSION: 1.7.0 +DEPRECATED-USE: HTML.Doctype +--DESCRIPTION-- +Determines whether or not output is XHTML 1.0 or HTML 4.01 flavor. +--ALIASES-- +Core.XHTML +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt new file mode 100644 index 00000000..08921fde --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.CommentScriptContents.txt @@ -0,0 +1,10 @@ +Output.CommentScriptContents +TYPE: bool +VERSION: 2.0.0 +DEFAULT: true +--DESCRIPTION-- +Determines whether or not HTML Purifier should attempt to fix up the +contents of script tags for legacy browsers with comments. +--ALIASES-- +Core.CommentScriptContents +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt new file mode 100644 index 00000000..d6f0d9f2 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FixInnerHTML.txt @@ -0,0 +1,15 @@ +Output.FixInnerHTML +TYPE: bool +VERSION: 4.3.0 +DEFAULT: true +--DESCRIPTION-- +

    + If true, HTML Purifier will protect against Internet Explorer's + mishandling of the innerHTML attribute by appending + a space to any attribute that does not contain angled brackets, spaces + or quotes, but contains a backtick. This slightly changes the + semantics of any given attribute, so if this is unacceptable and + you do not use innerHTML on any of your pages, you can + turn this directive off. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt new file mode 100644 index 00000000..93398e85 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.FlashCompat.txt @@ -0,0 +1,11 @@ +Output.FlashCompat +TYPE: bool +VERSION: 4.1.0 +DEFAULT: false +--DESCRIPTION-- +

    + If true, HTML Purifier will generate Internet Explorer compatibility + code for all object code. This is highly recommended if you enable + %HTML.SafeObject. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt new file mode 100644 index 00000000..79f8ad82 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.Newline.txt @@ -0,0 +1,13 @@ +Output.Newline +TYPE: string/null +VERSION: 2.0.1 +DEFAULT: NULL +--DESCRIPTION-- + +

    + Newline string to format final output with. If left null, HTML Purifier + will auto-detect the default newline type of the system and use that; + you can manually override it here. Remember, \r\n is Windows, \r + is Mac, and \n is Unix. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt new file mode 100644 index 00000000..232b0236 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.SortAttr.txt @@ -0,0 +1,14 @@ +Output.SortAttr +TYPE: bool +VERSION: 3.2.0 +DEFAULT: false +--DESCRIPTION-- +

    + If true, HTML Purifier will sort attributes by name before writing them back + to the document, converting a tag like: <el b="" a="" c="" /> + to <el a="" b="" c="" />. This is a workaround for + a bug in FCKeditor which causes it to swap attributes order, adding noise + to text diffs. If you're not seeing this bug, chances are, you don't need + this directive. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt new file mode 100644 index 00000000..06bab00a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Output.TidyFormat.txt @@ -0,0 +1,25 @@ +Output.TidyFormat +TYPE: bool +VERSION: 1.1.1 +DEFAULT: false +--DESCRIPTION-- +

    + Determines whether or not to run Tidy on the final output for pretty + formatting reasons, such as indentation and wrap. +

    +

    + This can greatly improve readability for editors who are hand-editing + the HTML, but is by no means necessary as HTML Purifier has already + fixed all major errors the HTML may have had. Tidy is a non-default + extension, and this directive will silently fail if Tidy is not + available. +

    +

    + If you are looking to make the overall look of your page's source + better, I recommend running Tidy on the entire page rather than just + user-content (after all, the indentation relative to the containing + blocks will be incorrect). +

    +--ALIASES-- +Core.TidyFormat +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt new file mode 100644 index 00000000..071bc029 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/Test.ForceNoIconv.txt @@ -0,0 +1,7 @@ +Test.ForceNoIconv +TYPE: bool +DEFAULT: false +--DESCRIPTION-- +When set to true, HTMLPurifier_Encoder will act as if iconv does not exist +and use only pure PHP implementations. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt new file mode 100644 index 00000000..eb97307e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.AllowedSchemes.txt @@ -0,0 +1,18 @@ +URI.AllowedSchemes +TYPE: lookup +--DEFAULT-- +array ( + 'http' => true, + 'https' => true, + 'mailto' => true, + 'ftp' => true, + 'nntp' => true, + 'news' => true, + 'tel' => true, +) +--DESCRIPTION-- +Whitelist that defines the schemes that a URI is allowed to have. This +prevents XSS attacks from using pseudo-schemes like javascript or mocha. +There is also support for the data and file +URI schemes, but they are not enabled by default. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt new file mode 100644 index 00000000..876f0680 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Base.txt @@ -0,0 +1,17 @@ +URI.Base +TYPE: string/null +VERSION: 2.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + The base URI is the URI of the document this purified HTML will be + inserted into. This information is important if HTML Purifier needs + to calculate absolute URIs from relative URIs, such as when %URI.MakeAbsolute + is on. You may use a non-absolute URI for this value, but behavior + may vary (%URI.MakeAbsolute deals nicely with both absolute and + relative paths, but forwards-compatibility is not guaranteed). + Warning: If set, the scheme on this URI + overrides the one specified by %URI.DefaultScheme. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt new file mode 100644 index 00000000..834bc08c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefaultScheme.txt @@ -0,0 +1,15 @@ +URI.DefaultScheme +TYPE: string/null +DEFAULT: 'http' +--DESCRIPTION-- + +

    + Defines through what scheme the output will be served, in order to + select the proper object validator when no scheme information is present. +

    + +

    + Starting with HTML Purifier 4.9.0, the default scheme can be null, in + which case we reject all URIs which do not have explicit schemes. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt new file mode 100644 index 00000000..f05312ba --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionID.txt @@ -0,0 +1,11 @@ +URI.DefinitionID +TYPE: string/null +VERSION: 2.1.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + Unique identifier for a custom-built URI definition. If you want + to add custom URIFilters, you must specify this value. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt new file mode 100644 index 00000000..80cfea93 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DefinitionRev.txt @@ -0,0 +1,11 @@ +URI.DefinitionRev +TYPE: int +VERSION: 2.1.0 +DEFAULT: 1 +--DESCRIPTION-- + +

    + Revision identifier for your custom definition. See + %HTML.DefinitionRev for details. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt new file mode 100644 index 00000000..71ce025a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Disable.txt @@ -0,0 +1,14 @@ +URI.Disable +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +--DESCRIPTION-- + +

    + Disables all URIs in all forms. Not sure why you'd want to do that + (after all, the Internet's founded on the notion of a hyperlink). +

    + +--ALIASES-- +Attr.DisableURI +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt new file mode 100644 index 00000000..13c122c8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternal.txt @@ -0,0 +1,11 @@ +URI.DisableExternal +TYPE: bool +VERSION: 1.2.0 +DEFAULT: false +--DESCRIPTION-- +Disables links to external websites. This is a highly effective anti-spam +and anti-pagerank-leech measure, but comes at a hefty price: nolinks or +images outside of your domain will be allowed. Non-linkified URIs will +still be preserved. If you want to be able to link to subdomains or use +absolute URIs, specify %URI.Host for your website. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt new file mode 100644 index 00000000..abcc1efd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableExternalResources.txt @@ -0,0 +1,13 @@ +URI.DisableExternalResources +TYPE: bool +VERSION: 1.3.0 +DEFAULT: false +--DESCRIPTION-- +Disables the embedding of external resources, preventing users from +embedding things like images from other hosts. This prevents access +tracking (good for email viewers), bandwidth leeching, cross-site request +forging, goatse.cx posting, and other nasties, but also results in a loss +of end-user functionality (they can't directly post a pic they posted from +Flickr anymore). Use it if you don't have a robust user-content moderation +team. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt new file mode 100644 index 00000000..f891de49 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.DisableResources.txt @@ -0,0 +1,15 @@ +URI.DisableResources +TYPE: bool +VERSION: 4.2.0 +DEFAULT: false +--DESCRIPTION-- +

    + Disables embedding resources, essentially meaning no pictures. You can + still link to them though. See %URI.DisableExternalResources for why + this might be a good idea. +

    +

    + Note: While this directive has been available since 1.3.0, + it didn't actually start doing anything until 4.2.0. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt new file mode 100644 index 00000000..ee83b121 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Host.txt @@ -0,0 +1,19 @@ +URI.Host +TYPE: string/null +VERSION: 1.2.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + Defines the domain name of the server, so we can determine whether or + an absolute URI is from your website or not. Not strictly necessary, + as users should be using relative URIs to reference resources on your + website. It will, however, let you use absolute URIs to link to + subdomains of the domain you post here: i.e. example.com will allow + sub.example.com. However, higher up domains will still be excluded: + if you set %URI.Host to sub.example.com, example.com will be blocked. + Note: This directive overrides %URI.Base because + a given page may be on a sub-domain, but you wish HTML Purifier to be + more relaxed and allow some of the parent domains too. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt new file mode 100644 index 00000000..0b6df762 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.HostBlacklist.txt @@ -0,0 +1,9 @@ +URI.HostBlacklist +TYPE: list +VERSION: 1.3.0 +DEFAULT: array() +--DESCRIPTION-- +List of strings that are forbidden in the host of any URI. Use it to kill +domain names of spam, etc. Note that it will catch anything in the domain, +so moo.com will catch moo.com.example.com. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt new file mode 100644 index 00000000..4214900a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MakeAbsolute.txt @@ -0,0 +1,13 @@ +URI.MakeAbsolute +TYPE: bool +VERSION: 2.1.0 +DEFAULT: false +--DESCRIPTION-- + +

    + Converts all URIs into absolute forms. This is useful when the HTML + being filtered assumes a specific base path, but will actually be + viewed in a different context (and setting an alternate base URI is + not possible). %URI.Base must be set for this directive to work. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt new file mode 100644 index 00000000..58c81dcc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.Munge.txt @@ -0,0 +1,83 @@ +URI.Munge +TYPE: string/null +VERSION: 1.3.0 +DEFAULT: NULL +--DESCRIPTION-- + +

    + Munges all browsable (usually http, https and ftp) + absolute URIs into another URI, usually a URI redirection service. + This directive accepts a URI, formatted with a %s where + the url-encoded original URI should be inserted (sample: + http://www.google.com/url?q=%s). +

    +

    + Uses for this directive: +

    +
      +
    • + Prevent PageRank leaks, while being fairly transparent + to users (you may also want to add some client side JavaScript to + override the text in the statusbar). Notice: + Many security experts believe that this form of protection does not deter spam-bots. +
    • +
    • + Redirect users to a splash page telling them they are leaving your + website. While this is poor usability practice, it is often mandated + in corporate environments. +
    • +
    +

    + Prior to HTML Purifier 3.1.1, this directive also enabled the munging + of browsable external resources, which could break things if your redirection + script was a splash page or used meta tags. To revert to + previous behavior, please use %URI.MungeResources. +

    +

    + You may want to also use %URI.MungeSecretKey along with this directive + in order to enforce what URIs your redirector script allows. Open + redirector scripts can be a security risk and negatively affect the + reputation of your domain name. +

    +

    + Starting with HTML Purifier 3.1.1, there is also these substitutions: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    KeyDescriptionExample <a href="">
    %r1 - The URI embeds a resource
    (blank) - The URI is merely a link
    %nThe name of the tag this URI came froma
    %mThe name of the attribute this URI came fromhref
    %pThe name of the CSS property this URI came from, or blank if irrelevant
    +

    + Admittedly, these letters are somewhat arbitrary; the only stipulation + was that they couldn't be a through f. r is for resource (I would have preferred + e, but you take what you can get), n is for name, m + was picked because it came after n (and I couldn't use a), p is for + property. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt new file mode 100644 index 00000000..6fce0fdc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeResources.txt @@ -0,0 +1,17 @@ +URI.MungeResources +TYPE: bool +VERSION: 3.1.1 +DEFAULT: false +--DESCRIPTION-- +

    + If true, any URI munging directives like %URI.Munge + will also apply to embedded resources, such as <img src="">. + Be careful enabling this directive if you have a redirector script + that does not use the Location HTTP header; all of your images + and other embedded resources will break. +

    +

    + Warning: It is strongly advised you use this in conjunction + %URI.MungeSecretKey to mitigate the security risk of an open redirector. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt new file mode 100644 index 00000000..1e17c1d4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt @@ -0,0 +1,30 @@ +URI.MungeSecretKey +TYPE: string/null +VERSION: 3.1.1 +DEFAULT: NULL +--DESCRIPTION-- +

    + This directive enables secure checksum generation along with %URI.Munge. + It should be set to a secure key that is not shared with anyone else. + The checksum can be placed in the URI using %t. Use of this checksum + affords an additional level of protection by allowing a redirector + to check if a URI has passed through HTML Purifier with this line: +

    + +
    $checksum === hash_hmac("sha256", $url, $secret_key)
    + +

    + If the output is TRUE, the redirector script should accept the URI. +

    + +

    + Please note that it would still be possible for an attacker to procure + secure hashes en-mass by abusing your website's Preview feature or the + like, but this service affords an additional level of protection + that should be combined with website blacklisting. +

    + +

    + Remember this has no effect if %URI.Munge is not on. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt new file mode 100644 index 00000000..23331a4e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.OverrideAllowedSchemes.txt @@ -0,0 +1,9 @@ +URI.OverrideAllowedSchemes +TYPE: bool +DEFAULT: true +--DESCRIPTION-- +If this is set to true (which it is by default), you can override +%URI.AllowedSchemes by simply registering a HTMLPurifier_URIScheme to the +registry. If false, you will also have to update that directive in order +to add more schemes. +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt new file mode 100644 index 00000000..79084832 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/URI.SafeIframeRegexp.txt @@ -0,0 +1,22 @@ +URI.SafeIframeRegexp +TYPE: string/null +VERSION: 4.4.0 +DEFAULT: NULL +--DESCRIPTION-- +

    + A PCRE regular expression that will be matched against an iframe URI. This is + a relatively inflexible scheme, but works well enough for the most common + use-case of iframes: embedded video. This directive only has an effect if + %HTML.SafeIframe is enabled. Here are some example values: +

    +
      +
    • %^http://www.youtube.com/embed/% - Allow YouTube videos
    • +
    • %^http://player.vimeo.com/video/% - Allow Vimeo videos
    • +
    • %^http://(www.youtube.com/embed/|player.vimeo.com/video/)% - Allow both
    • +
    +

    + Note that this directive does not give you enough granularity to, say, disable + all autoplay videos. Pipe up on the HTML Purifier forums if this + is a capability you want. +

    +--# vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/info.ini b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/info.ini new file mode 100644 index 00000000..5de4505e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ConfigSchema/schema/info.ini @@ -0,0 +1,3 @@ +name = "HTML Purifier" + +; vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ContentSets.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ContentSets.php new file mode 100644 index 00000000..543e3f8f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ContentSets.php @@ -0,0 +1,170 @@ + true) indexed by name. + * @type array + * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets + */ + public $lookup = array(); + + /** + * Synchronized list of defined content sets (keys of info). + * @type array + */ + protected $keys = array(); + /** + * Synchronized list of defined content values (values of info). + * @type array + */ + protected $values = array(); + + /** + * Merges in module's content sets, expands identifiers in the content + * sets and populates the keys, values and lookup member variables. + * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule + */ + public function __construct($modules) + { + if (!is_array($modules)) { + $modules = array($modules); + } + // populate content_sets based on module hints + // sorry, no way of overloading + foreach ($modules as $module) { + foreach ($module->content_sets as $key => $value) { + $temp = $this->convertToLookup($value); + if (isset($this->lookup[$key])) { + // add it into the existing content set + $this->lookup[$key] = array_merge($this->lookup[$key], $temp); + } else { + $this->lookup[$key] = $temp; + } + } + } + $old_lookup = false; + while ($old_lookup !== $this->lookup) { + $old_lookup = $this->lookup; + foreach ($this->lookup as $i => $set) { + $add = array(); + foreach ($set as $element => $x) { + if (isset($this->lookup[$element])) { + $add += $this->lookup[$element]; + unset($this->lookup[$i][$element]); + } + } + $this->lookup[$i] += $add; + } + } + + foreach ($this->lookup as $key => $lookup) { + $this->info[$key] = implode(' | ', array_keys($lookup)); + } + $this->keys = array_keys($this->info); + $this->values = array_values($this->info); + } + + /** + * Accepts a definition; generates and assigns a ChildDef for it + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + */ + public function generateChildDef(&$def, $module) + { + if (!empty($def->child)) { // already done! + return; + } + $content_model = $def->content_model; + if (is_string($content_model)) { + // Assume that $this->keys is alphanumeric + $def->content_model = preg_replace_callback( + '/\b(' . implode('|', $this->keys) . ')\b/', + array($this, 'generateChildDefCallback'), + $content_model + ); + //$def->content_model = str_replace( + // $this->keys, $this->values, $content_model); + } + $def->child = $this->getChildDef($def, $module); + } + + public function generateChildDefCallback($matches) + { + return $this->info[$matches[0]]; + } + + /** + * Instantiates a ChildDef based on content_model and content_model_type + * member variables in HTMLPurifier_ElementDef + * @note This will also defer to modules for custom HTMLPurifier_ChildDef + * subclasses that need content set expansion + * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted + * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef + * @return HTMLPurifier_ChildDef corresponding to ElementDef + */ + public function getChildDef($def, $module) + { + $value = $def->content_model; + if (is_object($value)) { + trigger_error( + 'Literal object child definitions should be stored in '. + 'ElementDef->child not ElementDef->content_model', + E_USER_NOTICE + ); + return $value; + } + switch ($def->content_model_type) { + case 'required': + return new HTMLPurifier_ChildDef_Required($value); + case 'optional': + return new HTMLPurifier_ChildDef_Optional($value); + case 'empty': + return new HTMLPurifier_ChildDef_Empty(); + case 'custom': + return new HTMLPurifier_ChildDef_Custom($value); + } + // defer to its module + $return = false; + if ($module->defines_child_def) { // save a func call + $return = $module->getChildDef($def); + } + if ($return !== false) { + return $return; + } + // error-out + trigger_error( + 'Could not determine which ChildDef class to instantiate', + E_USER_ERROR + ); + return false; + } + + /** + * Converts a string list of elements separated by pipes into + * a lookup array. + * @param string $string List of elements + * @return array Lookup array of elements + */ + protected function convertToLookup($string) + { + $array = explode('|', str_replace(' ', '', $string)); + $ret = array(); + foreach ($array as $k) { + $ret[$k] = true; + } + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Context.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Context.php new file mode 100644 index 00000000..00e509c8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Context.php @@ -0,0 +1,95 @@ +_storage)) { + trigger_error( + "Name $name produces collision, cannot re-register", + E_USER_ERROR + ); + return; + } + $this->_storage[$name] =& $ref; + } + + /** + * Retrieves a variable reference from the context. + * @param string $name String name + * @param bool $ignore_error Boolean whether or not to ignore error + * @return mixed + */ + public function &get($name, $ignore_error = false) + { + if (!array_key_exists($name, $this->_storage)) { + if (!$ignore_error) { + trigger_error( + "Attempted to retrieve non-existent variable $name", + E_USER_ERROR + ); + } + $var = null; // so we can return by reference + return $var; + } + return $this->_storage[$name]; + } + + /** + * Destroys a variable in the context. + * @param string $name String name + */ + public function destroy($name) + { + if (!array_key_exists($name, $this->_storage)) { + trigger_error( + "Attempted to destroy non-existent variable $name", + E_USER_ERROR + ); + return; + } + unset($this->_storage[$name]); + } + + /** + * Checks whether or not the variable exists. + * @param string $name String name + * @return bool + */ + public function exists($name) + { + return array_key_exists($name, $this->_storage); + } + + /** + * Loads a series of variables from an associative array + * @param array $context_array Assoc array of variables to load + */ + public function loadArray($context_array) + { + foreach ($context_array as $key => $discard) { + $this->register($key, $context_array[$key]); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Definition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Definition.php new file mode 100644 index 00000000..bc6d4336 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Definition.php @@ -0,0 +1,55 @@ +setup) { + return; + } + $this->setup = true; + $this->doSetup($config); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache.php new file mode 100644 index 00000000..9aa8ff35 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache.php @@ -0,0 +1,129 @@ +type = $type; + } + + /** + * Generates a unique identifier for a particular configuration + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config + * @return string + */ + public function generateKey($config) + { + return $config->version . ',' . // possibly replace with function calls + $config->getBatchSerial($this->type) . ',' . + $config->get($this->type . '.DefinitionRev'); + } + + /** + * Tests whether or not a key is old with respect to the configuration's + * version and revision number. + * @param string $key Key to test + * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against + * @return bool + */ + public function isOld($key, $config) + { + if (substr_count($key, ',') < 2) { + return true; + } + list($version, $hash, $revision) = explode(',', $key, 3); + $compare = version_compare($version, $config->version); + // version mismatch, is always old + if ($compare != 0) { + return true; + } + // versions match, ids match, check revision number + if ($hash == $config->getBatchSerial($this->type) && + $revision < $config->get($this->type . '.DefinitionRev')) { + return true; + } + return false; + } + + /** + * Checks if a definition's type jives with the cache's type + * @note Throws an error on failure + * @param HTMLPurifier_Definition $def Definition object to check + * @return bool true if good, false if not + */ + public function checkDefType($def) + { + if ($def->type !== $this->type) { + trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}"); + return false; + } + return true; + } + + /** + * Adds a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function add($def, $config); + + /** + * Unconditionally saves a definition object to the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function set($def, $config); + + /** + * Replace an object in the cache + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + */ + abstract public function replace($def, $config); + + /** + * Retrieves a definition object from the cache + * @param HTMLPurifier_Config $config + */ + abstract public function get($config); + + /** + * Removes a definition object to the cache + * @param HTMLPurifier_Config $config + */ + abstract public function remove($config); + + /** + * Clears all objects from cache + * @param HTMLPurifier_Config $config + */ + abstract public function flush($config); + + /** + * Clears all expired (older version or revision) objects from cache + * @note Be careful implementing this method as flush. Flush must + * not interfere with other Definition types, and cleanup() + * should not be repeatedly called by userland code. + * @param HTMLPurifier_Config $config + */ + abstract public function cleanup($config); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator.php new file mode 100644 index 00000000..b57a51b6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator.php @@ -0,0 +1,112 @@ +copy(); + // reference is necessary for mocks in PHP 4 + $decorator->cache =& $cache; + $decorator->type = $cache->type; + return $decorator; + } + + /** + * Cross-compatible clone substitute + * @return HTMLPurifier_DefinitionCache_Decorator + */ + public function copy() + { + return new HTMLPurifier_DefinitionCache_Decorator(); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function add($def, $config) + { + return $this->cache->add($def, $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function set($def, $config) + { + return $this->cache->set($def, $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function replace($def, $config) + { + return $this->cache->replace($def, $config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function get($config) + { + return $this->cache->get($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function remove($config) + { + return $this->cache->remove($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function flush($config) + { + return $this->cache->flush($config); + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function cleanup($config) + { + return $this->cache->cleanup($config); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php new file mode 100644 index 00000000..4991777c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Cleanup.php @@ -0,0 +1,78 @@ +definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function set($def, $config) + { + $status = parent::set($def, $config); + if ($status) { + $this->definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function replace($def, $config) + { + $status = parent::replace($def, $config); + if ($status) { + $this->definitions[$this->generateKey($config)] = $def; + } + return $status; + } + + /** + * @param HTMLPurifier_Config $config + * @return mixed + */ + public function get($config) + { + $key = $this->generateKey($config); + if (isset($this->definitions[$key])) { + return $this->definitions[$key]; + } + $this->definitions[$key] = parent::get($config); + return $this->definitions[$key]; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in new file mode 100644 index 00000000..b1fec8d3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Decorator/Template.php.in @@ -0,0 +1,82 @@ +checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (file_exists($file)) { + return false; + } + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return int|bool + */ + public function set($def, $config) + { + if (!$this->checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Definition $def + * @param HTMLPurifier_Config $config + * @return int|bool + */ + public function replace($def, $config) + { + if (!$this->checkDefType($def)) { + return; + } + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + if (!$this->_prepareDir($config)) { + return false; + } + return $this->_write($file, serialize($def), $config); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool|HTMLPurifier_Config + */ + public function get($config) + { + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + return unserialize(file_get_contents($file)); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function remove($config) + { + $file = $this->generateFilePath($config); + if (!file_exists($file)) { + return false; + } + return unlink($file); + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function flush($config) + { + if (!$this->_prepareDir($config)) { + return false; + } + $dir = $this->generateDirectoryPath($config); + $dh = opendir($dir); + // Apparently, on some versions of PHP, readdir will return + // an empty string if you pass an invalid argument to readdir. + // So you need this test. See #49. + if (false === $dh) { + return false; + } + while (false !== ($filename = readdir($dh))) { + if (empty($filename)) { + continue; + } + if ($filename[0] === '.') { + continue; + } + unlink($dir . '/' . $filename); + } + closedir($dh); + return true; + } + + /** + * @param HTMLPurifier_Config $config + * @return bool + */ + public function cleanup($config) + { + if (!$this->_prepareDir($config)) { + return false; + } + $dir = $this->generateDirectoryPath($config); + $dh = opendir($dir); + // See #49 (and above). + if (false === $dh) { + return false; + } + while (false !== ($filename = readdir($dh))) { + if (empty($filename)) { + continue; + } + if ($filename[0] === '.') { + continue; + } + $key = substr($filename, 0, strlen($filename) - 4); + if ($this->isOld($key, $config)) { + unlink($dir . '/' . $filename); + } + } + closedir($dh); + return true; + } + + /** + * Generates the file path to the serial file corresponding to + * the configuration and definition name + * @param HTMLPurifier_Config $config + * @return string + * @todo Make protected + */ + public function generateFilePath($config) + { + $key = $this->generateKey($config); + return $this->generateDirectoryPath($config) . '/' . $key . '.ser'; + } + + /** + * Generates the path to the directory contain this cache's serial files + * @param HTMLPurifier_Config $config + * @return string + * @note No trailing slash + * @todo Make protected + */ + public function generateDirectoryPath($config) + { + $base = $this->generateBaseDirectoryPath($config); + return $base . '/' . $this->type; + } + + /** + * Generates path to base directory that contains all definition type + * serials + * @param HTMLPurifier_Config $config + * @return mixed|string + * @todo Make protected + */ + public function generateBaseDirectoryPath($config) + { + $base = $config->get('Cache.SerializerPath'); + $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base; + return $base; + } + + /** + * Convenience wrapper function for file_put_contents + * @param string $file File name to write to + * @param string $data Data to write into file + * @param HTMLPurifier_Config $config + * @return int|bool Number of bytes written if success, or false if failure. + */ + private function _write($file, $data, $config) + { + $result = file_put_contents($file, $data); + if ($result !== false) { + // set permissions of the new file (no execute) + $chmod = $config->get('Cache.SerializerPermissions'); + if ($chmod !== null) { + chmod($file, $chmod & 0666); + } + } + return $result; + } + + /** + * Prepares the directory that this type stores the serials in + * @param HTMLPurifier_Config $config + * @return bool True if successful + */ + private function _prepareDir($config) + { + $directory = $this->generateDirectoryPath($config); + $chmod = $config->get('Cache.SerializerPermissions'); + if ($chmod === null) { + if (!@mkdir($directory) && !is_dir($directory)) { + trigger_error( + 'Could not create directory ' . $directory . '', + E_USER_WARNING + ); + return false; + } + return true; + } + if (!is_dir($directory)) { + $base = $this->generateBaseDirectoryPath($config); + if (!is_dir($base)) { + trigger_error( + 'Base directory ' . $base . ' does not exist, + please create or change using %Cache.SerializerPath', + E_USER_WARNING + ); + return false; + } elseif (!$this->_testPermissions($base, $chmod)) { + return false; + } + if (!@mkdir($directory, $chmod) && !is_dir($directory)) { + trigger_error( + 'Could not create directory ' . $directory . '', + E_USER_WARNING + ); + return false; + } + if (!$this->_testPermissions($directory, $chmod)) { + return false; + } + } elseif (!$this->_testPermissions($directory, $chmod)) { + return false; + } + return true; + } + + /** + * Tests permissions on a directory and throws out friendly + * error messages and attempts to chmod it itself if possible + * @param string $dir Directory path + * @param int $chmod Permissions + * @return bool True if directory is writable + */ + private function _testPermissions($dir, $chmod) + { + // early abort, if it is writable, everything is hunky-dory + if (is_writable($dir)) { + return true; + } + if (!is_dir($dir)) { + // generally, you'll want to handle this beforehand + // so a more specific error message can be given + trigger_error( + 'Directory ' . $dir . ' does not exist', + E_USER_WARNING + ); + return false; + } + if (function_exists('posix_getuid') && $chmod !== null) { + // POSIX system, we can give more specific advice + if (fileowner($dir) === posix_getuid()) { + // we can chmod it ourselves + $chmod = $chmod | 0700; + if (chmod($dir, $chmod)) { + return true; + } + } elseif (filegroup($dir) === posix_getgid()) { + $chmod = $chmod | 0070; + } else { + // PHP's probably running as nobody, so we'll + // need to give global permissions + $chmod = $chmod | 0777; + } + trigger_error( + 'Directory ' . $dir . ' not writable, ' . + 'please chmod to ' . decoct($chmod), + E_USER_WARNING + ); + } else { + // generic error message + trigger_error( + 'Directory ' . $dir . ' not writable, ' . + 'please alter file permissions', + E_USER_WARNING + ); + } + return false; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/README b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/README new file mode 100755 index 00000000..2e35c1c3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/README @@ -0,0 +1,3 @@ +This is a dummy file to prevent Git from ignoring this empty directory. + + vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCacheFactory.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCacheFactory.php new file mode 100644 index 00000000..fd1cc9be --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DefinitionCacheFactory.php @@ -0,0 +1,106 @@ + array()); + + /** + * @type array + */ + protected $implementations = array(); + + /** + * @type HTMLPurifier_DefinitionCache_Decorator[] + */ + protected $decorators = array(); + + /** + * Initialize default decorators + */ + public function setup() + { + $this->addDecorator('Cleanup'); + } + + /** + * Retrieves an instance of global definition cache factory. + * @param HTMLPurifier_DefinitionCacheFactory $prototype + * @return HTMLPurifier_DefinitionCacheFactory + */ + public static function instance($prototype = null) + { + static $instance; + if ($prototype !== null) { + $instance = $prototype; + } elseif ($instance === null || $prototype === true) { + $instance = new HTMLPurifier_DefinitionCacheFactory(); + $instance->setup(); + } + return $instance; + } + + /** + * Registers a new definition cache object + * @param string $short Short name of cache object, for reference + * @param string $long Full class name of cache object, for construction + */ + public function register($short, $long) + { + $this->implementations[$short] = $long; + } + + /** + * Factory method that creates a cache object based on configuration + * @param string $type Name of definitions handled by cache + * @param HTMLPurifier_Config $config Config instance + * @return mixed + */ + public function create($type, $config) + { + $method = $config->get('Cache.DefinitionImpl'); + if ($method === null) { + return new HTMLPurifier_DefinitionCache_Null($type); + } + if (!empty($this->caches[$method][$type])) { + return $this->caches[$method][$type]; + } + if (isset($this->implementations[$method]) && + class_exists($class = $this->implementations[$method], false)) { + $cache = new $class($type); + } else { + if ($method != 'Serializer') { + trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING); + } + $cache = new HTMLPurifier_DefinitionCache_Serializer($type); + } + foreach ($this->decorators as $decorator) { + $new_cache = $decorator->decorate($cache); + // prevent infinite recursion in PHP 4 + unset($cache); + $cache = $new_cache; + } + $this->caches[$method][$type] = $cache; + return $this->caches[$method][$type]; + } + + /** + * Registers a decorator to add to all new cache objects + * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator + */ + public function addDecorator($decorator) + { + if (is_string($decorator)) { + $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator"; + $decorator = new $class; + } + $this->decorators[$decorator->name] = $decorator; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Doctype.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Doctype.php new file mode 100644 index 00000000..4acd06e5 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Doctype.php @@ -0,0 +1,73 @@ +renderDoctype. + * If structure changes, please update that function. + */ +class HTMLPurifier_Doctype +{ + /** + * Full name of doctype + * @type string + */ + public $name; + + /** + * List of standard modules (string identifiers or literal objects) + * that this doctype uses + * @type array + */ + public $modules = array(); + + /** + * List of modules to use for tidying up code + * @type array + */ + public $tidyModules = array(); + + /** + * Is the language derived from XML (i.e. XHTML)? + * @type bool + */ + public $xml = true; + + /** + * List of aliases for this doctype + * @type array + */ + public $aliases = array(); + + /** + * Public DTD identifier + * @type string + */ + public $dtdPublic; + + /** + * System DTD identifier + * @type string + */ + public $dtdSystem; + + public function __construct( + $name = null, + $xml = true, + $modules = array(), + $tidyModules = array(), + $aliases = array(), + $dtd_public = null, + $dtd_system = null + ) { + $this->name = $name; + $this->xml = $xml; + $this->modules = $modules; + $this->tidyModules = $tidyModules; + $this->aliases = $aliases; + $this->dtdPublic = $dtd_public; + $this->dtdSystem = $dtd_system; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/DoctypeRegistry.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DoctypeRegistry.php new file mode 100644 index 00000000..acc1d64a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/DoctypeRegistry.php @@ -0,0 +1,142 @@ +doctypes[$doctype->name] = $doctype; + $name = $doctype->name; + // hookup aliases + foreach ($doctype->aliases as $alias) { + if (isset($this->doctypes[$alias])) { + continue; + } + $this->aliases[$alias] = $name; + } + // remove old aliases + if (isset($this->aliases[$name])) { + unset($this->aliases[$name]); + } + return $doctype; + } + + /** + * Retrieves reference to a doctype of a certain name + * @note This function resolves aliases + * @note When possible, use the more fully-featured make() + * @param string $doctype Name of doctype + * @return HTMLPurifier_Doctype Editable doctype object + */ + public function get($doctype) + { + if (isset($this->aliases[$doctype])) { + $doctype = $this->aliases[$doctype]; + } + if (!isset($this->doctypes[$doctype])) { + trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR); + $anon = new HTMLPurifier_Doctype($doctype); + return $anon; + } + return $this->doctypes[$doctype]; + } + + /** + * Creates a doctype based on a configuration object, + * will perform initialization on the doctype + * @note Use this function to get a copy of doctype that config + * can hold on to (this is necessary in order to tell + * Generator whether or not the current document is XML + * based or not). + * @param HTMLPurifier_Config $config + * @return HTMLPurifier_Doctype + */ + public function make($config) + { + return clone $this->get($this->getDoctypeFromConfig($config)); + } + + /** + * Retrieves the doctype from the configuration object + * @param HTMLPurifier_Config $config + * @return string + */ + public function getDoctypeFromConfig($config) + { + // recommended test + $doctype = $config->get('HTML.Doctype'); + if (!empty($doctype)) { + return $doctype; + } + $doctype = $config->get('HTML.CustomDoctype'); + if (!empty($doctype)) { + return $doctype; + } + // backwards-compatibility + if ($config->get('HTML.XHTML')) { + $doctype = 'XHTML 1.0'; + } else { + $doctype = 'HTML 4.01'; + } + if ($config->get('HTML.Strict')) { + $doctype .= ' Strict'; + } else { + $doctype .= ' Transitional'; + } + return $doctype; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ElementDef.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ElementDef.php new file mode 100644 index 00000000..d5311ced --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ElementDef.php @@ -0,0 +1,216 @@ +setup(), this array may also + * contain an array at index 0 that indicates which attribute + * collections to load into the full array. It may also + * contain string indentifiers in lieu of HTMLPurifier_AttrDef, + * see HTMLPurifier_AttrTypes on how they are expanded during + * HTMLPurifier_HTMLDefinition->setup() processing. + */ + public $attr = array(); + + // XXX: Design note: currently, it's not possible to override + // previously defined AttrTransforms without messing around with + // the final generated config. This is by design; a previous version + // used an associated list of attr_transform, but it was extremely + // easy to accidentally override other attribute transforms by + // forgetting to specify an index (and just using 0.) While we + // could check this by checking the index number and complaining, + // there is a second problem which is that it is not at all easy to + // tell when something is getting overridden. Combine this with a + // codebase where this isn't really being used, and it's perfect for + // nuking. + + /** + * List of tags HTMLPurifier_AttrTransform to be done before validation. + * @type array + */ + public $attr_transform_pre = array(); + + /** + * List of tags HTMLPurifier_AttrTransform to be done after validation. + * @type array + */ + public $attr_transform_post = array(); + + /** + * HTMLPurifier_ChildDef of this tag. + * @type HTMLPurifier_ChildDef + */ + public $child; + + /** + * Abstract string representation of internal ChildDef rules. + * @see HTMLPurifier_ContentSets for how this is parsed and then transformed + * into an HTMLPurifier_ChildDef. + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model; + + /** + * Value of $child->type, used to determine which ChildDef to use, + * used in combination with $content_model. + * @warning This must be lowercase + * @warning This is a temporary variable that is not available after + * being processed by HTMLDefinition + * @type string + */ + public $content_model_type; + + /** + * Does the element have a content model (#PCDATA | Inline)*? This + * is important for chameleon ins and del processing in + * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't + * have to worry about this one. + * @type bool + */ + public $descendants_are_inline = false; + + /** + * List of the names of required attributes this element has. + * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement() + * @type array + */ + public $required_attr = array(); + + /** + * Lookup table of tags excluded from all descendants of this tag. + * @type array + * @note SGML permits exclusions for all descendants, but this is + * not possible with DTDs or XML Schemas. W3C has elected to + * use complicated compositions of content_models to simulate + * exclusion for children, but we go the simpler, SGML-style + * route of flat-out exclusions, which correctly apply to + * all descendants and not just children. Note that the XHTML + * Modularization Abstract Modules are blithely unaware of such + * distinctions. + */ + public $excludes = array(); + + /** + * This tag is explicitly auto-closed by the following tags. + * @type array + */ + public $autoclose = array(); + + /** + * If a foreign element is found in this element, test if it is + * allowed by this sub-element; if it is, instead of closing the + * current element, place it inside this element. + * @type string + */ + public $wrap; + + /** + * Whether or not this is a formatting element affected by the + * "Active Formatting Elements" algorithm. + * @type bool + */ + public $formatting; + + /** + * Low-level factory constructor for creating new standalone element defs + */ + public static function create($content_model, $content_model_type, $attr) + { + $def = new HTMLPurifier_ElementDef(); + $def->content_model = $content_model; + $def->content_model_type = $content_model_type; + $def->attr = $attr; + return $def; + } + + /** + * Merges the values of another element definition into this one. + * Values from the new element def take precedence if a value is + * not mergeable. + * @param HTMLPurifier_ElementDef $def + */ + public function mergeIn($def) + { + // later keys takes precedence + foreach ($def->attr as $k => $v) { + if ($k === 0) { + // merge in the includes + // sorry, no way to override an include + foreach ($v as $v2) { + $this->attr[0][] = $v2; + } + continue; + } + if ($v === false) { + if (isset($this->attr[$k])) { + unset($this->attr[$k]); + } + continue; + } + $this->attr[$k] = $v; + } + $this->_mergeAssocArray($this->excludes, $def->excludes); + $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre); + $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post); + + if (!empty($def->content_model)) { + $this->content_model = + str_replace("#SUPER", $this->content_model, $def->content_model); + $this->child = false; + } + if (!empty($def->content_model_type)) { + $this->content_model_type = $def->content_model_type; + $this->child = false; + } + if (!is_null($def->child)) { + $this->child = $def->child; + } + if (!is_null($def->formatting)) { + $this->formatting = $def->formatting; + } + if ($def->descendants_are_inline) { + $this->descendants_are_inline = $def->descendants_are_inline; + } + } + + /** + * Merges one array into another, removes values which equal false + * @param $a1 Array by reference that is merged into + * @param $a2 Array that merges into $a1 + */ + private function _mergeAssocArray(&$a1, $a2) + { + foreach ($a2 as $k => $v) { + if ($v === false) { + if (isset($a1[$k])) { + unset($a1[$k]); + } + continue; + } + $a1[$k] = $v; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Encoder.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Encoder.php new file mode 100644 index 00000000..40a24266 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Encoder.php @@ -0,0 +1,617 @@ += $c) { + $r .= self::unsafeIconv($in, $out, substr($text, $i)); + break; + } + // wibble the boundary + if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) { + $chunk_size = $max_chunk_size; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) { + $chunk_size = $max_chunk_size - 1; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) { + $chunk_size = $max_chunk_size - 2; + } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) { + $chunk_size = $max_chunk_size - 3; + } else { + return false; // rather confusing UTF-8... + } + $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths + $r .= self::unsafeIconv($in, $out, $chunk); + $i += $chunk_size; + } + return $r; + } else { + return false; + } + } else { + return false; + } + } + + /** + * Cleans a UTF-8 string for well-formedness and SGML validity + * + * It will parse according to UTF-8 and return a valid UTF8 string, with + * non-SGML codepoints excluded. + * + * Specifically, it will permit: + * \x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF} + * Source: https://www.w3.org/TR/REC-xml/#NT-Char + * Arguably this function should be modernized to the HTML5 set + * of allowed characters: + * https://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream + * which simultaneously expand and restrict the set of allowed characters. + * + * @param string $str The string to clean + * @param bool $force_php + * @return string + * + * @note Just for reference, the non-SGML code points are 0 to 31 and + * 127 to 159, inclusive. However, we allow code points 9, 10 + * and 13, which are the tab, line feed and carriage return + * respectively. 128 and above the code points map to multibyte + * UTF-8 representations. + * + * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and + * hsivonen@iki.fi at under the + * LGPL license. Notes on what changed are inside, but in general, + * the original code transformed UTF-8 text into an array of integer + * Unicode codepoints. Understandably, transforming that back to + * a string would be somewhat expensive, so the function was modded to + * directly operate on the string. However, this discourages code + * reuse, and the logic enumerated here would be useful for any + * function that needs to be able to understand UTF-8 characters. + * As of right now, only smart lossless character encoding converters + * would need that, and I'm probably not going to implement them. + */ + public static function cleanUTF8($str, $force_php = false) + { + // UTF-8 validity is checked since PHP 4.3.5 + // This is an optimization: if the string is already valid UTF-8, no + // need to do PHP stuff. 99% of the time, this will be the case. + if (preg_match( + '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', + $str + )) { + return $str; + } + + $mState = 0; // cached expected number of octets after the current octet + // until the beginning of the next UTF8 character sequence + $mUcs4 = 0; // cached Unicode character + $mBytes = 1; // cached expected number of octets in the current sequence + + // original code involved an $out that was an array of Unicode + // codepoints. Instead of having to convert back into UTF-8, we've + // decided to directly append valid UTF-8 characters onto a string + // $out once they're done. $char accumulates raw bytes, while $mUcs4 + // turns into the Unicode code point, so there's some redundancy. + + $out = ''; + $char = ''; + + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $in = ord($str[$i]); + $char .= $str[$i]; // append byte to char + if (0 == $mState) { + // When mState is zero we expect either a US-ASCII character + // or a multi-octet sequence. + if (0 == (0x80 & ($in))) { + // US-ASCII, pass straight through. + if (($in <= 31 || $in == 127) && + !($in == 9 || $in == 13 || $in == 10) // save \r\t\n + ) { + // control characters, remove + } else { + $out .= $char; + } + // reset + $char = ''; + $mBytes = 1; + } elseif (0xC0 == (0xE0 & ($in))) { + // First octet of 2 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x1F) << 6; + $mState = 1; + $mBytes = 2; + } elseif (0xE0 == (0xF0 & ($in))) { + // First octet of 3 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x0F) << 12; + $mState = 2; + $mBytes = 3; + } elseif (0xF0 == (0xF8 & ($in))) { + // First octet of 4 octet sequence + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x07) << 18; + $mState = 3; + $mBytes = 4; + } elseif (0xF8 == (0xFC & ($in))) { + // First octet of 5 octet sequence. + // + // This is illegal because the encoded codepoint must be + // either: + // (a) not the shortest form or + // (b) outside the Unicode range of 0-0x10FFFF. + // Rather than trying to resynchronize, we will carry on + // until the end of the sequence and let the later error + // handling code catch it. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 0x03) << 24; + $mState = 4; + $mBytes = 5; + } elseif (0xFC == (0xFE & ($in))) { + // First octet of 6 octet sequence, see comments for 5 + // octet sequence. + $mUcs4 = ($in); + $mUcs4 = ($mUcs4 & 1) << 30; + $mState = 5; + $mBytes = 6; + } else { + // Current octet is neither in the US-ASCII range nor a + // legal first octet of a multi-octet sequence. + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // When mState is non-zero, we expect a continuation of the + // multi-octet sequence + if (0x80 == (0xC0 & ($in))) { + // Legal continuation. + $shift = ($mState - 1) * 6; + $tmp = $in; + $tmp = ($tmp & 0x0000003F) << $shift; + $mUcs4 |= $tmp; + + if (0 == --$mState) { + // End of the multi-octet sequence. mUcs4 now contains + // the final Unicode codepoint to be output + + // Check for illegal sequences and codepoints. + + // From Unicode 3.1, non-shortest form is illegal + if (((2 == $mBytes) && ($mUcs4 < 0x0080)) || + ((3 == $mBytes) && ($mUcs4 < 0x0800)) || + ((4 == $mBytes) && ($mUcs4 < 0x10000)) || + (4 < $mBytes) || + // From Unicode 3.2, surrogate characters = illegal + (($mUcs4 & 0xFFFFF800) == 0xD800) || + // Codepoints outside the Unicode range are illegal + ($mUcs4 > 0x10FFFF) + ) { + + } elseif (0xFEFF != $mUcs4 && // omit BOM + // check for valid Char unicode codepoints + ( + 0x9 == $mUcs4 || + 0xA == $mUcs4 || + 0xD == $mUcs4 || + (0x20 <= $mUcs4 && 0x7E >= $mUcs4) || + // 7F-9F is not strictly prohibited by XML, + // but it is non-SGML, and thus we don't allow it + (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) || + (0xE000 <= $mUcs4 && 0xFFFD >= $mUcs4) || + (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4) + ) + ) { + $out .= $char; + } + // initialize UTF8 cache (reset) + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char = ''; + } + } else { + // ((0xC0 & (*in) != 0x80) && (mState != 0)) + // Incomplete multi-octet sequence. + // used to result in complete fail, but we'll reset + $mState = 0; + $mUcs4 = 0; + $mBytes = 1; + $char =''; + } + } + } + return $out; + } + + /** + * Translates a Unicode codepoint into its corresponding UTF-8 character. + * @note Based on Feyd's function at + * , + * which is in public domain. + * @note While we're going to do code point parsing anyway, a good + * optimization would be to refuse to translate code points that + * are non-SGML characters. However, this could lead to duplication. + * @note This is very similar to the unichr function in + * maintenance/generate-entity-file.php (although this is superior, + * due to its sanity checks). + */ + + // +----------+----------+----------+----------+ + // | 33222222 | 22221111 | 111111 | | + // | 10987654 | 32109876 | 54321098 | 76543210 | bit + // +----------+----------+----------+----------+ + // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F + // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF + // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF + // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF + // +----------+----------+----------+----------+ + // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF) + // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes + // +----------+----------+----------+----------+ + + public static function unichr($code) + { + if ($code > 1114111 or $code < 0 or + ($code >= 55296 and $code <= 57343) ) { + // bits are set outside the "valid" range as defined + // by UNICODE 4.1.0 + return ''; + } + + $x = $y = $z = $w = 0; + if ($code < 128) { + // regular ASCII character + $x = $code; + } else { + // set up bits for UTF-8 + $x = ($code & 63) | 128; + if ($code < 2048) { + $y = (($code & 2047) >> 6) | 192; + } else { + $y = (($code & 4032) >> 6) | 128; + if ($code < 65536) { + $z = (($code >> 12) & 15) | 224; + } else { + $z = (($code >> 12) & 63) | 128; + $w = (($code >> 18) & 7) | 240; + } + } + } + // set up the actual character + $ret = ''; + if ($w) { + $ret .= chr($w); + } + if ($z) { + $ret .= chr($z); + } + if ($y) { + $ret .= chr($y); + } + $ret .= chr($x); + + return $ret; + } + + /** + * @return bool + */ + public static function iconvAvailable() + { + static $iconv = null; + if ($iconv === null) { + $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE; + } + return $iconv; + } + + /** + * Convert a string to UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public static function convertToUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // unaffected by bugs, since UTF-8 support all characters + $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str); + if ($str === false) { + // $encoding is not a valid encoding + trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR); + return ''; + } + // If the string is bjorked by Shift_JIS or a similar encoding + // that doesn't support all of ASCII, convert the naughty + // characters to their true byte-wise ASCII/UTF-8 equivalents. + $str = strtr($str, self::testEncodingSupportsASCII($encoding)); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_encode($str); + return $str; + } + $bug = HTMLPurifier_Encoder::testIconvTruncateBug(); + if ($bug == self::ICONV_OK) { + trigger_error('Encoding not supported, please install iconv', E_USER_ERROR); + } else { + trigger_error( + 'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' . + 'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', + E_USER_ERROR + ); + } + } + + /** + * Converts a string from UTF-8 based on configuration. + * @param string $str The string to convert + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + * @note Currently, this is a lossy conversion, with unexpressable + * characters being omitted. + */ + public static function convertFromUTF8($str, $config, $context) + { + $encoding = $config->get('Core.Encoding'); + if ($escape = $config->get('Core.EscapeNonASCIICharacters')) { + $str = self::convertToASCIIDumbLossless($str); + } + if ($encoding === 'utf-8') { + return $str; + } + static $iconv = null; + if ($iconv === null) { + $iconv = self::iconvAvailable(); + } + if ($iconv && !$config->get('Test.ForceNoIconv')) { + // Undo our previous fix in convertToUTF8, otherwise iconv will barf + $ascii_fix = self::testEncodingSupportsASCII($encoding); + if (!$escape && !empty($ascii_fix)) { + $clear_fix = array(); + foreach ($ascii_fix as $utf8 => $native) { + $clear_fix[$utf8] = ''; + } + $str = strtr($str, $clear_fix); + } + $str = strtr($str, array_flip($ascii_fix)); + // Normal stuff + $str = self::iconv('utf-8', $encoding . '//IGNORE', $str); + return $str; + } elseif ($encoding === 'iso-8859-1') { + $str = utf8_decode($str); + return $str; + } + trigger_error('Encoding not supported', E_USER_ERROR); + // You might be tempted to assume that the ASCII representation + // might be OK, however, this is *not* universally true over all + // encodings. So we take the conservative route here, rather + // than forcibly turn on %Core.EscapeNonASCIICharacters + } + + /** + * Lossless (character-wise) conversion of HTML to ASCII + * @param string $str UTF-8 string to be converted to ASCII + * @return string ASCII encoded string with non-ASCII character entity-ized + * @warning Adapted from MediaWiki, claiming fair use: this is a common + * algorithm. If you disagree with this license fudgery, + * implement it yourself. + * @note Uses decimal numeric entities since they are best supported. + * @note This is a DUMB function: it has no concept of keeping + * character entities that the projected character encoding + * can allow. We could possibly implement a smart version + * but that would require it to also know which Unicode + * codepoints the charset supported (not an easy task). + * @note Sort of with cleanUTF8() but it assumes that $str is + * well-formed UTF-8 + */ + public static function convertToASCIIDumbLossless($str) + { + $bytesleft = 0; + $result = ''; + $working = 0; + $len = strlen($str); + for ($i = 0; $i < $len; $i++) { + $bytevalue = ord($str[$i]); + if ($bytevalue <= 0x7F) { //0xxx xxxx + $result .= chr($bytevalue); + $bytesleft = 0; + } elseif ($bytevalue <= 0xBF) { //10xx xxxx + $working = $working << 6; + $working += ($bytevalue & 0x3F); + $bytesleft--; + if ($bytesleft <= 0) { + $result .= "&#" . $working . ";"; + } + } elseif ($bytevalue <= 0xDF) { //110x xxxx + $working = $bytevalue & 0x1F; + $bytesleft = 1; + } elseif ($bytevalue <= 0xEF) { //1110 xxxx + $working = $bytevalue & 0x0F; + $bytesleft = 2; + } else { //1111 0xxx + $working = $bytevalue & 0x07; + $bytesleft = 3; + } + } + return $result; + } + + /** No bugs detected in iconv. */ + const ICONV_OK = 0; + + /** Iconv truncates output if converting from UTF-8 to another + * character set with //IGNORE, and a non-encodable character is found */ + const ICONV_TRUNCATES = 1; + + /** Iconv does not support //IGNORE, making it unusable for + * transcoding purposes */ + const ICONV_UNUSABLE = 2; + + /** + * glibc iconv has a known bug where it doesn't handle the magic + * //IGNORE stanza correctly. In particular, rather than ignore + * characters, it will return an EILSEQ after consuming some number + * of characters, and expect you to restart iconv as if it were + * an E2BIG. Old versions of PHP did not respect the errno, and + * returned the fragment, so as a result you would see iconv + * mysteriously truncating output. We can work around this by + * manually chopping our input into segments of about 8000 + * characters, as long as PHP ignores the error code. If PHP starts + * paying attention to the error code, iconv becomes unusable. + * + * @return int Error code indicating severity of bug. + */ + public static function testIconvTruncateBug() + { + static $code = null; + if ($code === null) { + // better not use iconv, otherwise infinite loop! + $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000)); + if ($r === false) { + $code = self::ICONV_UNUSABLE; + } elseif (($c = strlen($r)) < 9000) { + $code = self::ICONV_TRUNCATES; + } elseif ($c > 9000) { + trigger_error( + 'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' . + 'include your iconv version as per phpversion()', + E_USER_ERROR + ); + } else { + $code = self::ICONV_OK; + } + } + return $code; + } + + /** + * This expensive function tests whether or not a given character + * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will + * fail this test, and require special processing. Variable width + * encodings shouldn't ever fail. + * + * @param string $encoding Encoding name to test, as per iconv format + * @param bool $bypass Whether or not to bypass the precompiled arrays. + * @return Array of UTF-8 characters to their corresponding ASCII, + * which can be used to "undo" any overzealous iconv action. + */ + public static function testEncodingSupportsASCII($encoding, $bypass = false) + { + // All calls to iconv here are unsafe, proof by case analysis: + // If ICONV_OK, no difference. + // If ICONV_TRUNCATE, all calls involve one character inputs, + // so bug is not triggered. + // If ICONV_UNUSABLE, this call is irrelevant + static $encodings = array(); + if (!$bypass) { + if (isset($encodings[$encoding])) { + return $encodings[$encoding]; + } + $lenc = strtolower($encoding); + switch ($lenc) { + case 'shift_jis': + return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~'); + case 'johab': + return array("\xE2\x82\xA9" => '\\'); + } + if (strpos($lenc, 'iso-8859-') === 0) { + return array(); + } + } + $ret = array(); + if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) { + return false; + } + for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars + $c = chr($i); // UTF-8 char + $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion + if ($r === '' || + // This line is needed for iconv implementations that do not + // omit characters that do not exist in the target character set + ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c) + ) { + // Reverse engineer: what's the UTF-8 equiv of this byte + // sequence? This assumes that there's no variable width + // encoding that doesn't support ASCII. + $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c; + } + } + $encodings[$encoding] = $ret; + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup.php new file mode 100644 index 00000000..f12ff13a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup.php @@ -0,0 +1,48 @@ +table = unserialize(file_get_contents($file)); + } + + /** + * Retrieves sole instance of the object. + * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with. + * @return HTMLPurifier_EntityLookup + */ + public static function instance($prototype = false) + { + // no references, since PHP doesn't copy unless modified + static $instance = null; + if ($prototype) { + $instance = $prototype; + } elseif (!$instance) { + $instance = new HTMLPurifier_EntityLookup(); + $instance->setup(); + } + return $instance; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup/entities.ser b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup/entities.ser new file mode 100644 index 00000000..e8b08128 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityLookup/entities.ser @@ -0,0 +1 @@ +a:253:{s:4:"fnof";s:2:"ƒ";s:5:"Alpha";s:2:"Α";s:4:"Beta";s:2:"Β";s:5:"Gamma";s:2:"Γ";s:5:"Delta";s:2:"Δ";s:7:"Epsilon";s:2:"Ε";s:4:"Zeta";s:2:"Ζ";s:3:"Eta";s:2:"Η";s:5:"Theta";s:2:"Θ";s:4:"Iota";s:2:"Ι";s:5:"Kappa";s:2:"Κ";s:6:"Lambda";s:2:"Λ";s:2:"Mu";s:2:"Μ";s:2:"Nu";s:2:"Ν";s:2:"Xi";s:2:"Ξ";s:7:"Omicron";s:2:"Ο";s:2:"Pi";s:2:"Π";s:3:"Rho";s:2:"Ρ";s:5:"Sigma";s:2:"Σ";s:3:"Tau";s:2:"Τ";s:7:"Upsilon";s:2:"Υ";s:3:"Phi";s:2:"Φ";s:3:"Chi";s:2:"Χ";s:3:"Psi";s:2:"Ψ";s:5:"Omega";s:2:"Ω";s:5:"alpha";s:2:"α";s:4:"beta";s:2:"β";s:5:"gamma";s:2:"γ";s:5:"delta";s:2:"δ";s:7:"epsilon";s:2:"ε";s:4:"zeta";s:2:"ζ";s:3:"eta";s:2:"η";s:5:"theta";s:2:"θ";s:4:"iota";s:2:"ι";s:5:"kappa";s:2:"κ";s:6:"lambda";s:2:"λ";s:2:"mu";s:2:"μ";s:2:"nu";s:2:"ν";s:2:"xi";s:2:"ξ";s:7:"omicron";s:2:"ο";s:2:"pi";s:2:"π";s:3:"rho";s:2:"ρ";s:6:"sigmaf";s:2:"ς";s:5:"sigma";s:2:"σ";s:3:"tau";s:2:"τ";s:7:"upsilon";s:2:"υ";s:3:"phi";s:2:"φ";s:3:"chi";s:2:"χ";s:3:"psi";s:2:"ψ";s:5:"omega";s:2:"ω";s:8:"thetasym";s:2:"ϑ";s:5:"upsih";s:2:"ϒ";s:3:"piv";s:2:"ϖ";s:4:"bull";s:3:"•";s:6:"hellip";s:3:"…";s:5:"prime";s:3:"′";s:5:"Prime";s:3:"″";s:5:"oline";s:3:"‾";s:5:"frasl";s:3:"⁄";s:6:"weierp";s:3:"℘";s:5:"image";s:3:"ℑ";s:4:"real";s:3:"ℜ";s:5:"trade";s:3:"™";s:7:"alefsym";s:3:"ℵ";s:4:"larr";s:3:"←";s:4:"uarr";s:3:"↑";s:4:"rarr";s:3:"→";s:4:"darr";s:3:"↓";s:4:"harr";s:3:"↔";s:5:"crarr";s:3:"↵";s:4:"lArr";s:3:"⇐";s:4:"uArr";s:3:"⇑";s:4:"rArr";s:3:"⇒";s:4:"dArr";s:3:"⇓";s:4:"hArr";s:3:"⇔";s:6:"forall";s:3:"∀";s:4:"part";s:3:"∂";s:5:"exist";s:3:"∃";s:5:"empty";s:3:"∅";s:5:"nabla";s:3:"∇";s:4:"isin";s:3:"∈";s:5:"notin";s:3:"∉";s:2:"ni";s:3:"∋";s:4:"prod";s:3:"∏";s:3:"sum";s:3:"∑";s:5:"minus";s:3:"−";s:6:"lowast";s:3:"∗";s:5:"radic";s:3:"√";s:4:"prop";s:3:"∝";s:5:"infin";s:3:"∞";s:3:"ang";s:3:"∠";s:3:"and";s:3:"∧";s:2:"or";s:3:"∨";s:3:"cap";s:3:"∩";s:3:"cup";s:3:"∪";s:3:"int";s:3:"∫";s:6:"there4";s:3:"∴";s:3:"sim";s:3:"∼";s:4:"cong";s:3:"≅";s:5:"asymp";s:3:"≈";s:2:"ne";s:3:"≠";s:5:"equiv";s:3:"≡";s:2:"le";s:3:"≤";s:2:"ge";s:3:"≥";s:3:"sub";s:3:"⊂";s:3:"sup";s:3:"⊃";s:4:"nsub";s:3:"⊄";s:4:"sube";s:3:"⊆";s:4:"supe";s:3:"⊇";s:5:"oplus";s:3:"⊕";s:6:"otimes";s:3:"⊗";s:4:"perp";s:3:"⊥";s:4:"sdot";s:3:"⋅";s:5:"lceil";s:3:"⌈";s:5:"rceil";s:3:"⌉";s:6:"lfloor";s:3:"⌊";s:6:"rfloor";s:3:"⌋";s:4:"lang";s:3:"〈";s:4:"rang";s:3:"〉";s:3:"loz";s:3:"◊";s:6:"spades";s:3:"♠";s:5:"clubs";s:3:"♣";s:6:"hearts";s:3:"♥";s:5:"diams";s:3:"♦";s:4:"quot";s:1:""";s:3:"amp";s:1:"&";s:2:"lt";s:1:"<";s:2:"gt";s:1:">";s:4:"apos";s:1:"'";s:5:"OElig";s:2:"Œ";s:5:"oelig";s:2:"œ";s:6:"Scaron";s:2:"Š";s:6:"scaron";s:2:"š";s:4:"Yuml";s:2:"Ÿ";s:4:"circ";s:2:"ˆ";s:5:"tilde";s:2:"˜";s:4:"ensp";s:3:" ";s:4:"emsp";s:3:" ";s:6:"thinsp";s:3:" ";s:4:"zwnj";s:3:"‌";s:3:"zwj";s:3:"‍";s:3:"lrm";s:3:"‎";s:3:"rlm";s:3:"‏";s:5:"ndash";s:3:"–";s:5:"mdash";s:3:"—";s:5:"lsquo";s:3:"‘";s:5:"rsquo";s:3:"’";s:5:"sbquo";s:3:"‚";s:5:"ldquo";s:3:"“";s:5:"rdquo";s:3:"”";s:5:"bdquo";s:3:"„";s:6:"dagger";s:3:"†";s:6:"Dagger";s:3:"‡";s:6:"permil";s:3:"‰";s:6:"lsaquo";s:3:"‹";s:6:"rsaquo";s:3:"›";s:4:"euro";s:3:"€";s:4:"nbsp";s:2:" ";s:5:"iexcl";s:2:"¡";s:4:"cent";s:2:"¢";s:5:"pound";s:2:"£";s:6:"curren";s:2:"¤";s:3:"yen";s:2:"¥";s:6:"brvbar";s:2:"¦";s:4:"sect";s:2:"§";s:3:"uml";s:2:"¨";s:4:"copy";s:2:"©";s:4:"ordf";s:2:"ª";s:5:"laquo";s:2:"«";s:3:"not";s:2:"¬";s:3:"shy";s:2:"­";s:3:"reg";s:2:"®";s:4:"macr";s:2:"¯";s:3:"deg";s:2:"°";s:6:"plusmn";s:2:"±";s:4:"sup2";s:2:"²";s:4:"sup3";s:2:"³";s:5:"acute";s:2:"´";s:5:"micro";s:2:"µ";s:4:"para";s:2:"¶";s:6:"middot";s:2:"·";s:5:"cedil";s:2:"¸";s:4:"sup1";s:2:"¹";s:4:"ordm";s:2:"º";s:5:"raquo";s:2:"»";s:6:"frac14";s:2:"¼";s:6:"frac12";s:2:"½";s:6:"frac34";s:2:"¾";s:6:"iquest";s:2:"¿";s:6:"Agrave";s:2:"À";s:6:"Aacute";s:2:"Á";s:5:"Acirc";s:2:"Â";s:6:"Atilde";s:2:"Ã";s:4:"Auml";s:2:"Ä";s:5:"Aring";s:2:"Å";s:5:"AElig";s:2:"Æ";s:6:"Ccedil";s:2:"Ç";s:6:"Egrave";s:2:"È";s:6:"Eacute";s:2:"É";s:5:"Ecirc";s:2:"Ê";s:4:"Euml";s:2:"Ë";s:6:"Igrave";s:2:"Ì";s:6:"Iacute";s:2:"Í";s:5:"Icirc";s:2:"Î";s:4:"Iuml";s:2:"Ï";s:3:"ETH";s:2:"Ð";s:6:"Ntilde";s:2:"Ñ";s:6:"Ograve";s:2:"Ò";s:6:"Oacute";s:2:"Ó";s:5:"Ocirc";s:2:"Ô";s:6:"Otilde";s:2:"Õ";s:4:"Ouml";s:2:"Ö";s:5:"times";s:2:"×";s:6:"Oslash";s:2:"Ø";s:6:"Ugrave";s:2:"Ù";s:6:"Uacute";s:2:"Ú";s:5:"Ucirc";s:2:"Û";s:4:"Uuml";s:2:"Ü";s:6:"Yacute";s:2:"Ý";s:5:"THORN";s:2:"Þ";s:5:"szlig";s:2:"ß";s:6:"agrave";s:2:"à";s:6:"aacute";s:2:"á";s:5:"acirc";s:2:"â";s:6:"atilde";s:2:"ã";s:4:"auml";s:2:"ä";s:5:"aring";s:2:"å";s:5:"aelig";s:2:"æ";s:6:"ccedil";s:2:"ç";s:6:"egrave";s:2:"è";s:6:"eacute";s:2:"é";s:5:"ecirc";s:2:"ê";s:4:"euml";s:2:"ë";s:6:"igrave";s:2:"ì";s:6:"iacute";s:2:"í";s:5:"icirc";s:2:"î";s:4:"iuml";s:2:"ï";s:3:"eth";s:2:"ð";s:6:"ntilde";s:2:"ñ";s:6:"ograve";s:2:"ò";s:6:"oacute";s:2:"ó";s:5:"ocirc";s:2:"ô";s:6:"otilde";s:2:"õ";s:4:"ouml";s:2:"ö";s:6:"divide";s:2:"÷";s:6:"oslash";s:2:"ø";s:6:"ugrave";s:2:"ù";s:6:"uacute";s:2:"ú";s:5:"ucirc";s:2:"û";s:4:"uuml";s:2:"ü";s:6:"yacute";s:2:"ý";s:5:"thorn";s:2:"þ";s:4:"yuml";s:2:"ÿ";} \ No newline at end of file diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityParser.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityParser.php new file mode 100644 index 00000000..3ef2d09e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/EntityParser.php @@ -0,0 +1,285 @@ +_semiOptionalPrefixRegex = "/&()()()($semi_optional)/"; + + $this->_textEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + "($semi_optional)". + ')/'; + + $this->_attrEntitiesRegex = + '/&(?:'. + // hex + '[#]x([a-fA-F0-9]+);?|'. + // dec + '[#]0*(\d+);?|'. + // string (mandatory semicolon) + // NB: order matters: match semicolon preferentially + '([A-Za-z_:][A-Za-z0-9.\-_:]*);|'. + // string (optional semicolon) + // don't match if trailing is equals or alphanumeric (URL + // like) + "($semi_optional)(?![=;A-Za-z0-9])". + ')/'; + + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * textual data in an HTML document (as opposed to attributes.) + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteTextEntities($string) + { + return preg_replace_callback( + $this->_textEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Substitute entities with the parsed equivalents. Use this on + * attribute contents in documents. + * + * @param string $string String to have entities parsed. + * @return string Parsed string. + */ + public function substituteAttrEntities($string) + { + return preg_replace_callback( + $this->_attrEntitiesRegex, + array($this, 'entityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function entityCallback($matches) + { + $entity = $matches[0]; + $hex_part = @$matches[1]; + $dec_part = @$matches[2]; + $named_part = empty($matches[3]) ? (empty($matches[4]) ? "" : $matches[4]) : $matches[3]; + if ($hex_part !== NULL && $hex_part !== "") { + return HTMLPurifier_Encoder::unichr(hexdec($hex_part)); + } elseif ($dec_part !== NULL && $dec_part !== "") { + return HTMLPurifier_Encoder::unichr((int) $dec_part); + } else { + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$named_part])) { + return $this->_entity_lookup->table[$named_part]; + } else { + // exact match didn't match anything, so test if + // any of the semicolon optional match the prefix. + // Test that this is an EXACT match is important to + // prevent infinite loop + if (!empty($matches[3])) { + return preg_replace_callback( + $this->_semiOptionalPrefixRegex, + array($this, 'entityCallback'), + $entity + ); + } + return $entity; + } + } + } + + // LEGACY CODE BELOW + + /** + * Callback regex string for parsing entities. + * @type string + */ + protected $_substituteEntitiesRegex = + '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/'; + // 1. hex 2. dec 3. string (XML style) + + /** + * Decimal to parsed string conversion table for special entities. + * @type array + */ + protected $_special_dec2str = + array( + 34 => '"', + 38 => '&', + 39 => "'", + 60 => '<', + 62 => '>' + ); + + /** + * Stripped entity names to decimal conversion table for special entities. + * @type array + */ + protected $_special_ent2dec = + array( + 'quot' => 34, + 'amp' => 38, + 'lt' => 60, + 'gt' => 62 + ); + + /** + * Substitutes non-special entities with their parsed equivalents. Since + * running this whenever you have parsed character is t3h 5uck, we run + * it before everything else. + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteNonSpecialEntities($string) + { + // it will try to detect missing semicolons, but don't rely on it + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'nonSpecialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteNonSpecialEntities() that does the work. + * + * @param array $matches PCRE matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + + protected function nonSpecialEntityCallback($matches) + { + // replaces all but big five + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + // abort for special characters + if (isset($this->_special_dec2str[$code])) { + return $entity; + } + return HTMLPurifier_Encoder::unichr($code); + } else { + if (isset($this->_special_ent2dec[$matches[3]])) { + return $entity; + } + if (!$this->_entity_lookup) { + $this->_entity_lookup = HTMLPurifier_EntityLookup::instance(); + } + if (isset($this->_entity_lookup->table[$matches[3]])) { + return $this->_entity_lookup->table[$matches[3]]; + } else { + return $entity; + } + } + } + + /** + * Substitutes only special entities with their parsed equivalents. + * + * @notice We try to avoid calling this function because otherwise, it + * would have to be called a lot (for every parsed section). + * + * @param string $string String to have non-special entities parsed. + * @return string Parsed string. + */ + public function substituteSpecialEntities($string) + { + return preg_replace_callback( + $this->_substituteEntitiesRegex, + array($this, 'specialEntityCallback'), + $string + ); + } + + /** + * Callback function for substituteSpecialEntities() that does the work. + * + * This callback has same syntax as nonSpecialEntityCallback(). + * + * @param array $matches PCRE-style matches array, with 0 the entire match, and + * either index 1, 2 or 3 set with a hex value, dec value, + * or string (respectively). + * @return string Replacement string. + */ + protected function specialEntityCallback($matches) + { + $entity = $matches[0]; + $is_num = (@$matches[0][1] === '#'); + if ($is_num) { + $is_hex = (@$entity[2] === 'x'); + $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2]; + return isset($this->_special_dec2str[$int]) ? + $this->_special_dec2str[$int] : + $entity; + } else { + return isset($this->_special_ent2dec[$matches[3]]) ? + $this->_special_dec2str[$this->_special_ent2dec[$matches[3]]] : + $entity; + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorCollector.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorCollector.php new file mode 100644 index 00000000..d47e3f2e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorCollector.php @@ -0,0 +1,244 @@ +locale =& $context->get('Locale'); + $this->context = $context; + $this->_current =& $this->_stacks[0]; + $this->errors =& $this->_stacks[0]; + } + + /** + * Sends an error message to the collector for later use + * @param int $severity Error severity, PHP error style (don't use E_USER_) + * @param string $msg Error message text + */ + public function send($severity, $msg) + { + $args = array(); + if (func_num_args() > 2) { + $args = func_get_args(); + array_shift($args); + unset($args[0]); + } + + $token = $this->context->get('CurrentToken', true); + $line = $token ? $token->line : $this->context->get('CurrentLine', true); + $col = $token ? $token->col : $this->context->get('CurrentCol', true); + $attr = $this->context->get('CurrentAttr', true); + + // perform special substitutions, also add custom parameters + $subst = array(); + if (!is_null($token)) { + $args['CurrentToken'] = $token; + } + if (!is_null($attr)) { + $subst['$CurrentAttr.Name'] = $attr; + if (isset($token->attr[$attr])) { + $subst['$CurrentAttr.Value'] = $token->attr[$attr]; + } + } + + if (empty($args)) { + $msg = $this->locale->getMessage($msg); + } else { + $msg = $this->locale->formatMessage($msg, $args); + } + + if (!empty($subst)) { + $msg = strtr($msg, $subst); + } + + // (numerically indexed) + $error = array( + self::LINENO => $line, + self::SEVERITY => $severity, + self::MESSAGE => $msg, + self::CHILDREN => array() + ); + $this->_current[] = $error; + + // NEW CODE BELOW ... + // Top-level errors are either: + // TOKEN type, if $value is set appropriately, or + // "syntax" type, if $value is null + $new_struct = new HTMLPurifier_ErrorStruct(); + $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN; + if ($token) { + $new_struct->value = clone $token; + } + if (is_int($line) && is_int($col)) { + if (isset($this->lines[$line][$col])) { + $struct = $this->lines[$line][$col]; + } else { + $struct = $this->lines[$line][$col] = $new_struct; + } + // These ksorts may present a performance problem + ksort($this->lines[$line], SORT_NUMERIC); + } else { + if (isset($this->lines[-1])) { + $struct = $this->lines[-1]; + } else { + $struct = $this->lines[-1] = $new_struct; + } + } + ksort($this->lines, SORT_NUMERIC); + + // Now, check if we need to operate on a lower structure + if (!empty($attr)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr); + if (!$struct->value) { + $struct->value = array($attr, 'PUT VALUE HERE'); + } + } + if (!empty($cssprop)) { + $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop); + if (!$struct->value) { + // if we tokenize CSS this might be a little more difficult to do + $struct->value = array($cssprop, 'PUT VALUE HERE'); + } + } + + // Ok, structs are all setup, now time to register the error + $struct->addError($severity, $msg); + } + + /** + * Retrieves raw error data for custom formatter to use + */ + public function getRaw() + { + return $this->errors; + } + + /** + * Default HTML formatting implementation for error messages + * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature + * @param array $errors Errors array to display; used for recursion. + * @return string + */ + public function getHTMLFormatted($config, $errors = null) + { + $ret = array(); + + $this->generator = new HTMLPurifier_Generator($config, $this->context); + if ($errors === null) { + $errors = $this->errors; + } + + // 'At line' message needs to be removed + + // generation code for new structure goes here. It needs to be recursive. + foreach ($this->lines as $line => $col_array) { + if ($line == -1) { + continue; + } + foreach ($col_array as $col => $struct) { + $this->_renderStruct($ret, $struct, $line, $col); + } + } + if (isset($this->lines[-1])) { + $this->_renderStruct($ret, $this->lines[-1]); + } + + if (empty($errors)) { + return '

    ' . $this->locale->getMessage('ErrorCollector: No errors') . '

    '; + } else { + return '
    • ' . implode('
    • ', $ret) . '
    '; + } + + } + + private function _renderStruct(&$ret, $struct, $line = null, $col = null) + { + $stack = array($struct); + $context_stack = array(array()); + while ($current = array_pop($stack)) { + $context = array_pop($context_stack); + foreach ($current->errors as $error) { + list($severity, $msg) = $error; + $string = ''; + $string .= '
    '; + // W3C uses an icon to indicate the severity of the error. + $error = $this->locale->getErrorName($severity); + $string .= "$error "; + if (!is_null($line) && !is_null($col)) { + $string .= "Line $line, Column $col: "; + } else { + $string .= 'End of Document: '; + } + $string .= '' . $this->generator->escape($msg) . ' '; + $string .= '
    '; + // Here, have a marker for the character on the column appropriate. + // Be sure to clip extremely long lines. + //$string .= '
    ';
    +                //$string .= '';
    +                //$string .= '
    '; + $ret[] = $string; + } + foreach ($current->children as $array) { + $context[] = $current; + $stack = array_merge($stack, array_reverse($array, true)); + for ($i = count($array); $i > 0; $i--) { + $context_stack[] = $context; + } + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorStruct.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorStruct.php new file mode 100644 index 00000000..cf869d32 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/ErrorStruct.php @@ -0,0 +1,74 @@ +children[$type][$id])) { + $this->children[$type][$id] = new HTMLPurifier_ErrorStruct(); + $this->children[$type][$id]->type = $type; + } + return $this->children[$type][$id]; + } + + /** + * @param int $severity + * @param string $message + */ + public function addError($severity, $message) + { + $this->errors[] = array($severity, $message); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Exception.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Exception.php new file mode 100644 index 00000000..be85b4c5 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Exception.php @@ -0,0 +1,12 @@ +preFilter, + * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter, + * 1->postFilter. + * + * @note Methods are not declared abstract as it is perfectly legitimate + * for an implementation not to want anything to happen on a step + */ + +class HTMLPurifier_Filter +{ + + /** + * Name of the filter for identification purposes. + * @type string + */ + public $name; + + /** + * Pre-processor function, handles HTML before HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function preFilter($html, $config, $context) + { + return $html; + } + + /** + * Post-processor function, handles HTML after HTML Purifier + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + return $html; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/ExtractStyleBlocks.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/ExtractStyleBlocks.php new file mode 100644 index 00000000..66f70b0f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/ExtractStyleBlocks.php @@ -0,0 +1,341 @@ + blocks from input HTML, cleans them up + * using CSSTidy, and then places them in $purifier->context->get('StyleBlocks') + * so they can be used elsewhere in the document. + * + * @note + * See tests/HTMLPurifier/Filter/ExtractStyleBlocksTest.php for + * sample usage. + * + * @note + * This filter can also be used on stylesheets not included in the + * document--something purists would probably prefer. Just directly + * call HTMLPurifier_Filter_ExtractStyleBlocks->cleanCSS() + */ +class HTMLPurifier_Filter_ExtractStyleBlocks extends HTMLPurifier_Filter +{ + /** + * @type string + */ + public $name = 'ExtractStyleBlocks'; + + /** + * @type array + */ + private $_styleMatches = array(); + + /** + * @type csstidy + */ + private $_tidy; + + /** + * @type HTMLPurifier_AttrDef_HTML_ID + */ + private $_id_attrdef; + + /** + * @type HTMLPurifier_AttrDef_CSS_Ident + */ + private $_class_attrdef; + + /** + * @type HTMLPurifier_AttrDef_Enum + */ + private $_enum_attrdef; + + public function __construct() + { + $this->_tidy = new csstidy(); + $this->_tidy->set_cfg('lowercase_s', false); + $this->_id_attrdef = new HTMLPurifier_AttrDef_HTML_ID(true); + $this->_class_attrdef = new HTMLPurifier_AttrDef_CSS_Ident(); + $this->_enum_attrdef = new HTMLPurifier_AttrDef_Enum( + array( + 'first-child', + 'link', + 'visited', + 'active', + 'hover', + 'focus' + ) + ); + } + + /** + * Save the contents of CSS blocks to style matches + * @param array $matches preg_replace style $matches array + */ + protected function styleCallback($matches) + { + $this->_styleMatches[] = $matches[1]; + } + + /** + * Removes inline + // we must not grab foo in a font-family prop). + if ($config->get('Filter.ExtractStyleBlocks.Escaping')) { + $css = str_replace( + array('<', '>', '&'), + array('\3C ', '\3E ', '\26 '), + $css + ); + } + return $css; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/YouTube.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/YouTube.php new file mode 100644 index 00000000..276d8362 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Filter/YouTube.php @@ -0,0 +1,65 @@ +]+>.+?' . + '(?:http:)?//www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?#s'; + $pre_replace = '\1'; + return preg_replace($pre_regex, $pre_replace, $html); + } + + /** + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function postFilter($html, $config, $context) + { + $post_regex = '#((?:v|cp)/[A-Za-z0-9\-_=]+)#'; + return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html); + } + + /** + * @param $url + * @return string + */ + protected function armorUrl($url) + { + return str_replace('--', '--', $url); + } + + /** + * @param array $matches + * @return string + */ + protected function postFilterCallback($matches) + { + $url = $this->armorUrl($matches[1]); + return '' . + '' . + '' . + ''; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Generator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Generator.php new file mode 100644 index 00000000..eb56e2df --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Generator.php @@ -0,0 +1,286 @@ + tags. + * @type bool + */ + private $_scriptFix = false; + + /** + * Cache of HTMLDefinition during HTML output to determine whether or + * not attributes should be minimized. + * @type HTMLPurifier_HTMLDefinition + */ + private $_def; + + /** + * Cache of %Output.SortAttr. + * @type bool + */ + private $_sortAttr; + + /** + * Cache of %Output.FlashCompat. + * @type bool + */ + private $_flashCompat; + + /** + * Cache of %Output.FixInnerHTML. + * @type bool + */ + private $_innerHTMLFix; + + /** + * Stack for keeping track of object information when outputting IE + * compatibility code. + * @type array + */ + private $_flashStack = array(); + + /** + * Configuration for the generator + * @type HTMLPurifier_Config + */ + protected $config; + + /** + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + */ + public function __construct($config, $context) + { + $this->config = $config; + $this->_scriptFix = $config->get('Output.CommentScriptContents'); + $this->_innerHTMLFix = $config->get('Output.FixInnerHTML'); + $this->_sortAttr = $config->get('Output.SortAttr'); + $this->_flashCompat = $config->get('Output.FlashCompat'); + $this->_def = $config->getHTMLDefinition(); + $this->_xhtml = $this->_def->doctype->xml; + } + + /** + * Generates HTML from an array of tokens. + * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token + * @return string Generated HTML + */ + public function generateFromTokens($tokens) + { + if (!$tokens) { + return ''; + } + + // Basic algorithm + $html = ''; + for ($i = 0, $size = count($tokens); $i < $size; $i++) { + if ($this->_scriptFix && $tokens[$i]->name === 'script' + && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) { + // script special case + // the contents of the script block must be ONE token + // for this to work. + $html .= $this->generateFromToken($tokens[$i++]); + $html .= $this->generateScriptFromToken($tokens[$i++]); + } + $html .= $this->generateFromToken($tokens[$i]); + } + + // Tidy cleanup + if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) { + $tidy = new Tidy; + $tidy->parseString( + $html, + array( + 'indent'=> true, + 'output-xhtml' => $this->_xhtml, + 'show-body-only' => true, + 'indent-spaces' => 2, + 'wrap' => 68, + ), + 'utf8' + ); + $tidy->cleanRepair(); + $html = (string) $tidy; // explicit cast necessary + } + + // Normalize newlines to system defined value + if ($this->config->get('Core.NormalizeNewlines')) { + $nl = $this->config->get('Output.Newline'); + if ($nl === null) { + $nl = PHP_EOL; + } + if ($nl !== "\n") { + $html = str_replace("\n", $nl, $html); + } + } + return $html; + } + + /** + * Generates HTML from a single token. + * @param HTMLPurifier_Token $token HTMLPurifier_Token object. + * @return string Generated HTML + */ + public function generateFromToken($token) + { + if (!$token instanceof HTMLPurifier_Token) { + trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING); + return ''; + + } elseif ($token instanceof HTMLPurifier_Token_Start) { + $attr = $this->generateAttributes($token->attr, $token->name); + if ($this->_flashCompat) { + if ($token->name == "object") { + $flash = new stdClass(); + $flash->attr = $token->attr; + $flash->param = array(); + $this->_flashStack[] = $flash; + } + } + return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>'; + + } elseif ($token instanceof HTMLPurifier_Token_End) { + $_extra = ''; + if ($this->_flashCompat) { + if ($token->name == "object" && !empty($this->_flashStack)) { + // doesn't do anything for now + } + } + return $_extra . 'name . '>'; + + } elseif ($token instanceof HTMLPurifier_Token_Empty) { + if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) { + $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value']; + } + $attr = $this->generateAttributes($token->attr, $token->name); + return '<' . $token->name . ($attr ? ' ' : '') . $attr . + ( $this->_xhtml ? ' /': '' ) //
    v.
    + . '>'; + + } elseif ($token instanceof HTMLPurifier_Token_Text) { + return $this->escape($token->data, ENT_NOQUOTES); + + } elseif ($token instanceof HTMLPurifier_Token_Comment) { + return ''; + } else { + return ''; + + } + } + + /** + * Special case processor for the contents of script tags + * @param HTMLPurifier_Token $token HTMLPurifier_Token object. + * @return string + * @warning This runs into problems if there's already a literal + * --> somewhere inside the script contents. + */ + public function generateScriptFromToken($token) + { + if (!$token instanceof HTMLPurifier_Token_Text) { + return $this->generateFromToken($token); + } + // Thanks + $data = preg_replace('#//\s*$#', '', $token->data); + return ''; + } + + /** + * Generates attribute declarations from attribute array. + * @note This does not include the leading or trailing space. + * @param array $assoc_array_of_attributes Attribute array + * @param string $element Name of element attributes are for, used to check + * attribute minimization. + * @return string Generated HTML fragment for insertion. + */ + public function generateAttributes($assoc_array_of_attributes, $element = '') + { + $html = ''; + if ($this->_sortAttr) { + ksort($assoc_array_of_attributes); + } + foreach ($assoc_array_of_attributes as $key => $value) { + if (!$this->_xhtml) { + // Remove namespaced attributes + if (strpos($key, ':') !== false) { + continue; + } + // Check if we should minimize the attribute: val="val" -> val + if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) { + $html .= $key . ' '; + continue; + } + } + // Workaround for Internet Explorer innerHTML bug. + // Essentially, Internet Explorer, when calculating + // innerHTML, omits quotes if there are no instances of + // angled brackets, quotes or spaces. However, when parsing + // HTML (for example, when you assign to innerHTML), it + // treats backticks as quotes. Thus, + // `` + // becomes + // `` + // becomes + // + // Fortunately, all we need to do is trigger an appropriate + // quoting style, which we do by adding an extra space. + // This also is consistent with the W3C spec, which states + // that user agents may ignore leading or trailing + // whitespace (in fact, most don't, at least for attributes + // like alt, but an extra space at the end is barely + // noticeable). Still, we have a configuration knob for + // this, since this transformation is not necesary if you + // don't process user input with innerHTML or you don't plan + // on supporting Internet Explorer. + if ($this->_innerHTMLFix) { + if (strpos($value, '`') !== false) { + // check if correct quoting style would not already be + // triggered + if (strcspn($value, '"\' <>') === strlen($value)) { + // protect! + $value .= ' '; + } + } + } + $html .= $key.'="'.$this->escape($value).'" '; + } + return rtrim($html); + } + + /** + * Escapes raw text data. + * @todo This really ought to be protected, but until we have a facility + * for properly generating HTML here w/o using tokens, it stays + * public. + * @param string $string String data to escape for HTML. + * @param int $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is + * permissible for non-attribute output. + * @return string escaped data. + */ + public function escape($string, $quote = null) + { + // Workaround for APC bug on Mac Leopard reported by sidepodcast + // http://htmlpurifier.org/phorum/read.php?3,4823,4846 + if ($quote === null) { + $quote = ENT_COMPAT; + } + return htmlspecialchars($string, $quote, 'UTF-8'); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLDefinition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLDefinition.php new file mode 100644 index 00000000..9b7b334d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLDefinition.php @@ -0,0 +1,493 @@ +getAnonymousModule(); + if (!isset($module->info[$element_name])) { + $element = $module->addBlankElement($element_name); + } else { + $element = $module->info[$element_name]; + } + $element->attr[$attr_name] = $def; + } + + /** + * Adds a custom element to your HTML definition + * @see HTMLPurifier_HTMLModule::addElement() for detailed + * parameter and return value descriptions. + */ + public function addElement($element_name, $type, $contents, $attr_collections, $attributes = array()) + { + $module = $this->getAnonymousModule(); + // assume that if the user is calling this, the element + // is safe. This may not be a good idea + $element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes); + return $element; + } + + /** + * Adds a blank element to your HTML definition, for overriding + * existing behavior + * @param string $element_name + * @return HTMLPurifier_ElementDef + * @see HTMLPurifier_HTMLModule::addBlankElement() for detailed + * parameter and return value descriptions. + */ + public function addBlankElement($element_name) + { + $module = $this->getAnonymousModule(); + $element = $module->addBlankElement($element_name); + return $element; + } + + /** + * Retrieves a reference to the anonymous module, so you can + * bust out advanced features without having to make your own + * module. + * @return HTMLPurifier_HTMLModule + */ + public function getAnonymousModule() + { + if (!$this->_anonModule) { + $this->_anonModule = new HTMLPurifier_HTMLModule(); + $this->_anonModule->name = 'Anonymous'; + } + return $this->_anonModule; + } + + private $_anonModule = null; + + // PUBLIC BUT INTERNAL VARIABLES -------------------------------------- + + /** + * @type string + */ + public $type = 'HTML'; + + /** + * @type HTMLPurifier_HTMLModuleManager + */ + public $manager; + + /** + * Performs low-cost, preliminary initialization. + */ + public function __construct() + { + $this->manager = new HTMLPurifier_HTMLModuleManager(); + } + + /** + * @param HTMLPurifier_Config $config + */ + protected function doSetup($config) + { + $this->processModules($config); + $this->setupConfigStuff($config); + unset($this->manager); + + // cleanup some of the element definitions + foreach ($this->info as $k => $v) { + unset($this->info[$k]->content_model); + unset($this->info[$k]->content_model_type); + } + } + + /** + * Extract out the information from the manager + * @param HTMLPurifier_Config $config + */ + protected function processModules($config) + { + if ($this->_anonModule) { + // for user specific changes + // this is late-loaded so we don't have to deal with PHP4 + // reference wonky-ness + $this->manager->addModule($this->_anonModule); + unset($this->_anonModule); + } + + $this->manager->setup($config); + $this->doctype = $this->manager->doctype; + + foreach ($this->manager->modules as $module) { + foreach ($module->info_tag_transform as $k => $v) { + if ($v === false) { + unset($this->info_tag_transform[$k]); + } else { + $this->info_tag_transform[$k] = $v; + } + } + foreach ($module->info_attr_transform_pre as $k => $v) { + if ($v === false) { + unset($this->info_attr_transform_pre[$k]); + } else { + $this->info_attr_transform_pre[$k] = $v; + } + } + foreach ($module->info_attr_transform_post as $k => $v) { + if ($v === false) { + unset($this->info_attr_transform_post[$k]); + } else { + $this->info_attr_transform_post[$k] = $v; + } + } + foreach ($module->info_injector as $k => $v) { + if ($v === false) { + unset($this->info_injector[$k]); + } else { + $this->info_injector[$k] = $v; + } + } + } + $this->info = $this->manager->getElements(); + $this->info_content_sets = $this->manager->contentSets->lookup; + } + + /** + * Sets up stuff based on config. We need a better way of doing this. + * @param HTMLPurifier_Config $config + */ + protected function setupConfigStuff($config) + { + $block_wrapper = $config->get('HTML.BlockWrapper'); + if (isset($this->info_content_sets['Block'][$block_wrapper])) { + $this->info_block_wrapper = $block_wrapper; + } else { + trigger_error( + 'Cannot use non-block element as block wrapper', + E_USER_ERROR + ); + } + + $parent = $config->get('HTML.Parent'); + $def = $this->manager->getElement($parent, true); + if ($def) { + $this->info_parent = $parent; + $this->info_parent_def = $def; + } else { + trigger_error( + 'Cannot use unrecognized element as parent', + E_USER_ERROR + ); + $this->info_parent_def = $this->manager->getElement($this->info_parent, true); + } + + // support template text + $support = "(for information on implementing this, see the support forums) "; + + // setup allowed elements ----------------------------------------- + + $allowed_elements = $config->get('HTML.AllowedElements'); + $allowed_attributes = $config->get('HTML.AllowedAttributes'); // retrieve early + + if (!is_array($allowed_elements) && !is_array($allowed_attributes)) { + $allowed = $config->get('HTML.Allowed'); + if (is_string($allowed)) { + list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed); + } + } + + if (is_array($allowed_elements)) { + foreach ($this->info as $name => $d) { + if (!isset($allowed_elements[$name])) { + unset($this->info[$name]); + } + unset($allowed_elements[$name]); + } + // emit errors + foreach ($allowed_elements as $element => $d) { + $element = htmlspecialchars($element); // PHP doesn't escape errors, be careful! + trigger_error("Element '$element' is not supported $support", E_USER_WARNING); + } + } + + // setup allowed attributes --------------------------------------- + + $allowed_attributes_mutable = $allowed_attributes; // by copy! + if (is_array($allowed_attributes)) { + // This actually doesn't do anything, since we went away from + // global attributes. It's possible that userland code uses + // it, but HTMLModuleManager doesn't! + foreach ($this->info_global_attr as $attr => $x) { + $keys = array($attr, "*@$attr", "*.$attr"); + $delete = true; + foreach ($keys as $key) { + if ($delete && isset($allowed_attributes[$key])) { + $delete = false; + } + if (isset($allowed_attributes_mutable[$key])) { + unset($allowed_attributes_mutable[$key]); + } + } + if ($delete) { + unset($this->info_global_attr[$attr]); + } + } + + foreach ($this->info as $tag => $info) { + foreach ($info->attr as $attr => $x) { + $keys = array("$tag@$attr", $attr, "*@$attr", "$tag.$attr", "*.$attr"); + $delete = true; + foreach ($keys as $key) { + if ($delete && isset($allowed_attributes[$key])) { + $delete = false; + } + if (isset($allowed_attributes_mutable[$key])) { + unset($allowed_attributes_mutable[$key]); + } + } + if ($delete) { + if ($this->info[$tag]->attr[$attr]->required) { + trigger_error( + "Required attribute '$attr' in element '$tag' " . + "was not allowed, which means '$tag' will not be allowed either", + E_USER_WARNING + ); + } + unset($this->info[$tag]->attr[$attr]); + } + } + } + // emit errors + foreach ($allowed_attributes_mutable as $elattr => $d) { + $bits = preg_split('/[.@]/', $elattr, 2); + $c = count($bits); + switch ($c) { + case 2: + if ($bits[0] !== '*') { + $element = htmlspecialchars($bits[0]); + $attribute = htmlspecialchars($bits[1]); + if (!isset($this->info[$element])) { + trigger_error( + "Cannot allow attribute '$attribute' if element " . + "'$element' is not allowed/supported $support" + ); + } else { + trigger_error( + "Attribute '$attribute' in element '$element' not supported $support", + E_USER_WARNING + ); + } + break; + } + // otherwise fall through + case 1: + $attribute = htmlspecialchars($bits[0]); + trigger_error( + "Global attribute '$attribute' is not ". + "supported in any elements $support", + E_USER_WARNING + ); + break; + } + } + } + + // setup forbidden elements --------------------------------------- + + $forbidden_elements = $config->get('HTML.ForbiddenElements'); + $forbidden_attributes = $config->get('HTML.ForbiddenAttributes'); + + foreach ($this->info as $tag => $info) { + if (isset($forbidden_elements[$tag])) { + unset($this->info[$tag]); + continue; + } + foreach ($info->attr as $attr => $x) { + if (isset($forbidden_attributes["$tag@$attr"]) || + isset($forbidden_attributes["*@$attr"]) || + isset($forbidden_attributes[$attr]) + ) { + unset($this->info[$tag]->attr[$attr]); + continue; + } elseif (isset($forbidden_attributes["$tag.$attr"])) { // this segment might get removed eventually + // $tag.$attr are not user supplied, so no worries! + trigger_error( + "Error with $tag.$attr: tag.attr syntax not supported for " . + "HTML.ForbiddenAttributes; use tag@attr instead", + E_USER_WARNING + ); + } + } + } + foreach ($forbidden_attributes as $key => $v) { + if (strlen($key) < 2) { + continue; + } + if ($key[0] != '*') { + continue; + } + if ($key[1] == '.') { + trigger_error( + "Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead", + E_USER_WARNING + ); + } + } + + // setup injectors ----------------------------------------------------- + foreach ($this->info_injector as $i => $injector) { + if ($injector->checkNeeded($config) !== false) { + // remove injector that does not have it's required + // elements/attributes present, and is thus not needed. + unset($this->info_injector[$i]); + } + } + } + + /** + * Parses a TinyMCE-flavored Allowed Elements and Attributes list into + * separate lists for processing. Format is element[attr1|attr2],element2... + * @warning Although it's largely drawn from TinyMCE's implementation, + * it is different, and you'll probably have to modify your lists + * @param array $list String list to parse + * @return array + * @todo Give this its own class, probably static interface + */ + public function parseTinyMCEAllowedList($list) + { + $list = str_replace(array(' ', "\t"), '', $list); + + $elements = array(); + $attributes = array(); + + $chunks = preg_split('/(,|[\n\r]+)/', $list); + foreach ($chunks as $chunk) { + if (empty($chunk)) { + continue; + } + // remove TinyMCE element control characters + if (!strpos($chunk, '[')) { + $element = $chunk; + $attr = false; + } else { + list($element, $attr) = explode('[', $chunk); + } + if ($element !== '*') { + $elements[$element] = true; + } + if (!$attr) { + continue; + } + $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ] + $attr = explode('|', $attr); + foreach ($attr as $key) { + $attributes["$element.$key"] = true; + } + } + return array($elements, $attributes); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule.php new file mode 100644 index 00000000..9dbb9872 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule.php @@ -0,0 +1,285 @@ +info, since the object's data is only info, + * with extra behavior associated with it. + * @type array + */ + public $attr_collections = array(); + + /** + * Associative array of deprecated tag name to HTMLPurifier_TagTransform. + * @type array + */ + public $info_tag_transform = array(); + + /** + * List of HTMLPurifier_AttrTransform to be performed before validation. + * @type array + */ + public $info_attr_transform_pre = array(); + + /** + * List of HTMLPurifier_AttrTransform to be performed after validation. + * @type array + */ + public $info_attr_transform_post = array(); + + /** + * List of HTMLPurifier_Injector to be performed during well-formedness fixing. + * An injector will only be invoked if all of it's pre-requisites are met; + * if an injector fails setup, there will be no error; it will simply be + * silently disabled. + * @type array + */ + public $info_injector = array(); + + /** + * Boolean flag that indicates whether or not getChildDef is implemented. + * For optimization reasons: may save a call to a function. Be sure + * to set it if you do implement getChildDef(), otherwise it will have + * no effect! + * @type bool + */ + public $defines_child_def = false; + + /** + * Boolean flag whether or not this module is safe. If it is not safe, all + * of its members are unsafe. Modules are safe by default (this might be + * slightly dangerous, but it doesn't make much sense to force HTML Purifier, + * which is based off of safe HTML, to explicitly say, "This is safe," even + * though there are modules which are "unsafe") + * + * @type bool + * @note Previously, safety could be applied at an element level granularity. + * We've removed this ability, so in order to add "unsafe" elements + * or attributes, a dedicated module with this property set to false + * must be used. + */ + public $safe = true; + + /** + * Retrieves a proper HTMLPurifier_ChildDef subclass based on + * content_model and content_model_type member variables of + * the HTMLPurifier_ElementDef class. There is a similar function + * in HTMLPurifier_HTMLDefinition. + * @param HTMLPurifier_ElementDef $def + * @return HTMLPurifier_ChildDef subclass + */ + public function getChildDef($def) + { + return false; + } + + // -- Convenience ----------------------------------------------------- + + /** + * Convenience function that sets up a new element + * @param string $element Name of element to add + * @param string|bool $type What content set should element be registered to? + * Set as false to skip this step. + * @param string|HTMLPurifier_ChildDef $contents Allowed children in form of: + * "$content_model_type: $content_model" + * @param array|string $attr_includes What attribute collections to register to + * element? + * @param array $attr What unique attributes does the element define? + * @see HTMLPurifier_ElementDef:: for in-depth descriptions of these parameters. + * @return HTMLPurifier_ElementDef Created element definition object, so you + * can set advanced parameters + */ + public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array()) + { + $this->elements[] = $element; + // parse content_model + list($content_model_type, $content_model) = $this->parseContents($contents); + // merge in attribute inclusions + $this->mergeInAttrIncludes($attr, $attr_includes); + // add element to content sets + if ($type) { + $this->addElementToContentSet($element, $type); + } + // create element + $this->info[$element] = HTMLPurifier_ElementDef::create( + $content_model, + $content_model_type, + $attr + ); + // literal object $contents means direct child manipulation + if (!is_string($contents)) { + $this->info[$element]->child = $contents; + } + return $this->info[$element]; + } + + /** + * Convenience function that creates a totally blank, non-standalone + * element. + * @param string $element Name of element to create + * @return HTMLPurifier_ElementDef Created element + */ + public function addBlankElement($element) + { + if (!isset($this->info[$element])) { + $this->elements[] = $element; + $this->info[$element] = new HTMLPurifier_ElementDef(); + $this->info[$element]->standalone = false; + } else { + trigger_error("Definition for $element already exists in module, cannot redefine"); + } + return $this->info[$element]; + } + + /** + * Convenience function that registers an element to a content set + * @param string $element Element to register + * @param string $type Name content set (warning: case sensitive, usually upper-case + * first letter) + */ + public function addElementToContentSet($element, $type) + { + if (!isset($this->content_sets[$type])) { + $this->content_sets[$type] = ''; + } else { + $this->content_sets[$type] .= ' | '; + } + $this->content_sets[$type] .= $element; + } + + /** + * Convenience function that transforms single-string contents + * into separate content model and content model type + * @param string $contents Allowed children in form of: + * "$content_model_type: $content_model" + * @return array + * @note If contents is an object, an array of two nulls will be + * returned, and the callee needs to take the original $contents + * and use it directly. + */ + public function parseContents($contents) + { + if (!is_string($contents)) { + return array(null, null); + } // defer + switch ($contents) { + // check for shorthand content model forms + case 'Empty': + return array('empty', ''); + case 'Inline': + return array('optional', 'Inline | #PCDATA'); + case 'Flow': + return array('optional', 'Flow | #PCDATA'); + } + list($content_model_type, $content_model) = explode(':', $contents); + $content_model_type = strtolower(trim($content_model_type)); + $content_model = trim($content_model); + return array($content_model_type, $content_model); + } + + /** + * Convenience function that merges a list of attribute includes into + * an attribute array. + * @param array $attr Reference to attr array to modify + * @param array $attr_includes Array of includes / string include to merge in + */ + public function mergeInAttrIncludes(&$attr, $attr_includes) + { + if (!is_array($attr_includes)) { + if (empty($attr_includes)) { + $attr_includes = array(); + } else { + $attr_includes = array($attr_includes); + } + } + $attr[0] = $attr_includes; + } + + /** + * Convenience function that generates a lookup table with boolean + * true as value. + * @param string $list List of values to turn into a lookup + * @note You can also pass an arbitrary number of arguments in + * place of the regular argument + * @return array array equivalent of list + */ + public function makeLookup($list) + { + $args = func_get_args(); + if (is_string($list)) { + $list = $args; + } + $ret = array(); + foreach ($list as $value) { + if (is_null($value)) { + continue; + } + $ret[$value] = true; + } + return $ret; + } + + /** + * Lazy load construction of the module after determining whether + * or not it's needed, and also when a finalized configuration object + * is available. + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Bdo.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Bdo.php new file mode 100644 index 00000000..1e67c790 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Bdo.php @@ -0,0 +1,44 @@ + array('dir' => false) + ); + + /** + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + $bdo = $this->addElement( + 'bdo', + 'Inline', + 'Inline', + array('Core', 'Lang'), + array( + 'dir' => 'Enum#ltr,rtl', // required + // The Abstract Module specification has the attribute + // inclusions wrong for bdo: bdo allows Lang + ) + ); + $bdo->attr_transform_post[] = new HTMLPurifier_AttrTransform_BdoDir(); + + $this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl'; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/CommonAttributes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/CommonAttributes.php new file mode 100644 index 00000000..a96ab1be --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/CommonAttributes.php @@ -0,0 +1,31 @@ + array( + 0 => array('Style'), + // 'xml:space' => false, + 'class' => 'Class', + 'id' => 'ID', + 'title' => 'CDATA', + ), + 'Lang' => array(), + 'I18N' => array( + 0 => array('Lang'), // proprietary, for xml:lang/lang + ), + 'Common' => array( + 0 => array('Core', 'I18N') + ) + ); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Edit.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Edit.php new file mode 100644 index 00000000..a9042a35 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Edit.php @@ -0,0 +1,55 @@ + 'URI', + // 'datetime' => 'Datetime', // not implemented + ); + $this->addElement('del', 'Inline', $contents, 'Common', $attr); + $this->addElement('ins', 'Inline', $contents, 'Common', $attr); + } + + // HTML 4.01 specifies that ins/del must not contain block + // elements when used in an inline context, chameleon is + // a complicated workaround to acheive this effect + + // Inline context ! Block context (exclamation mark is + // separator, see getChildDef for parsing) + + /** + * @type bool + */ + public $defines_child_def = true; + + /** + * @param HTMLPurifier_ElementDef $def + * @return HTMLPurifier_ChildDef_Chameleon + */ + public function getChildDef($def) + { + if ($def->content_model_type != 'chameleon') { + return false; + } + $value = explode('!', $def->content_model); + return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Forms.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Forms.php new file mode 100644 index 00000000..eb0edcff --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Forms.php @@ -0,0 +1,194 @@ + 'Form', + 'Inline' => 'Formctrl', + ); + + /** + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + if ($config->get('HTML.Forms')) { + $this->safe = true; + } + + $form = $this->addElement( + 'form', + 'Form', + 'Required: Heading | List | Block | fieldset', + 'Common', + array( + 'accept' => 'ContentTypes', + 'accept-charset' => 'Charsets', + 'action*' => 'URI', + 'method' => 'Enum#get,post', + // really ContentType, but these two are the only ones used today + 'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data', + ) + ); + $form->excludes = array('form' => true); + + $input = $this->addElement( + 'input', + 'Formctrl', + 'Empty', + 'Common', + array( + 'accept' => 'ContentTypes', + 'accesskey' => 'Character', + 'alt' => 'Text', + 'checked' => 'Bool#checked', + 'disabled' => 'Bool#disabled', + 'maxlength' => 'Number', + 'name' => 'CDATA', + 'readonly' => 'Bool#readonly', + 'size' => 'Number', + 'src' => 'URI#embedded', + 'tabindex' => 'Number', + 'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image', + 'value' => 'CDATA', + ) + ); + $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input(); + + $this->addElement( + 'select', + 'Formctrl', + 'Required: optgroup | option', + 'Common', + array( + 'disabled' => 'Bool#disabled', + 'multiple' => 'Bool#multiple', + 'name' => 'CDATA', + 'size' => 'Number', + 'tabindex' => 'Number', + ) + ); + + $this->addElement( + 'option', + false, + 'Optional: #PCDATA', + 'Common', + array( + 'disabled' => 'Bool#disabled', + 'label' => 'Text', + 'selected' => 'Bool#selected', + 'value' => 'CDATA', + ) + ); + // It's illegal for there to be more than one selected, but not + // be multiple. Also, no selected means undefined behavior. This might + // be difficult to implement; perhaps an injector, or a context variable. + + $textarea = $this->addElement( + 'textarea', + 'Formctrl', + 'Optional: #PCDATA', + 'Common', + array( + 'accesskey' => 'Character', + 'cols*' => 'Number', + 'disabled' => 'Bool#disabled', + 'name' => 'CDATA', + 'readonly' => 'Bool#readonly', + 'rows*' => 'Number', + 'tabindex' => 'Number', + ) + ); + $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea(); + + $button = $this->addElement( + 'button', + 'Formctrl', + 'Optional: #PCDATA | Heading | List | Block | Inline', + 'Common', + array( + 'accesskey' => 'Character', + 'disabled' => 'Bool#disabled', + 'name' => 'CDATA', + 'tabindex' => 'Number', + 'type' => 'Enum#button,submit,reset', + 'value' => 'CDATA', + ) + ); + + // For exclusions, ideally we'd specify content sets, not literal elements + $button->excludes = $this->makeLookup( + 'form', + 'fieldset', // Form + 'input', + 'select', + 'textarea', + 'label', + 'button', // Formctrl + 'a', // as per HTML 4.01 spec, this is omitted by modularization + 'isindex', + 'iframe' // legacy items + ); + + // Extra exclusion: img usemap="" is not permitted within this element. + // We'll omit this for now, since we don't have any good way of + // indicating it yet. + + // This is HIGHLY user-unfriendly; we need a custom child-def for this + $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common'); + + $label = $this->addElement( + 'label', + 'Formctrl', + 'Optional: #PCDATA | Inline', + 'Common', + array( + 'accesskey' => 'Character', + // 'for' => 'IDREF', // IDREF not implemented, cannot allow + ) + ); + $label->excludes = array('label' => true); + + $this->addElement( + 'legend', + false, + 'Optional: #PCDATA | Inline', + 'Common', + array( + 'accesskey' => 'Character', + ) + ); + + $this->addElement( + 'optgroup', + false, + 'Required: option', + 'Common', + array( + 'disabled' => 'Bool#disabled', + 'label*' => 'Text', + ) + ); + // Don't forget an injector for . This one's a little complex + // because it maps to multiple elements. + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Hypertext.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Hypertext.php new file mode 100644 index 00000000..72d7a31e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Hypertext.php @@ -0,0 +1,40 @@ +addElement( + 'a', + 'Inline', + 'Inline', + 'Common', + array( + // 'accesskey' => 'Character', + // 'charset' => 'Charset', + 'href' => 'URI', + // 'hreflang' => 'LanguageCode', + 'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'), + 'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'), + // 'tabindex' => 'Number', + // 'type' => 'ContentType', + ) + ); + $a->formatting = true; + $a->excludes = array('a' => true); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Iframe.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Iframe.php new file mode 100644 index 00000000..f7e7c91c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Iframe.php @@ -0,0 +1,51 @@ +get('HTML.SafeIframe')) { + $this->safe = true; + } + $this->addElement( + 'iframe', + 'Inline', + 'Flow', + 'Common', + array( + 'src' => 'URI#embedded', + 'width' => 'Length', + 'height' => 'Length', + 'name' => 'ID', + 'scrolling' => 'Enum#yes,no,auto', + 'frameborder' => 'Enum#0,1', + 'longdesc' => 'URI', + 'marginheight' => 'Pixels', + 'marginwidth' => 'Pixels', + ) + ); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Image.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Image.php new file mode 100644 index 00000000..0f5fdb3b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Image.php @@ -0,0 +1,49 @@ +get('HTML.MaxImgLength'); + $img = $this->addElement( + 'img', + 'Inline', + 'Empty', + 'Common', + array( + 'alt*' => 'Text', + // According to the spec, it's Length, but percents can + // be abused, so we allow only Pixels. + 'height' => 'Pixels#' . $max, + 'width' => 'Pixels#' . $max, + 'longdesc' => 'URI', + 'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded + ) + ); + if ($max === null || $config->get('HTML.Trusted')) { + $img->attr['height'] = + $img->attr['width'] = 'Length'; + } + + // kind of strange, but splitting things up would be inefficient + $img->attr_transform_pre[] = + $img->attr_transform_post[] = + new HTMLPurifier_AttrTransform_ImgRequired(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Legacy.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Legacy.php new file mode 100644 index 00000000..86b52995 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Legacy.php @@ -0,0 +1,186 @@ +addElement( + 'basefont', + 'Inline', + 'Empty', + null, + array( + 'color' => 'Color', + 'face' => 'Text', // extremely broad, we should + 'size' => 'Text', // tighten it + 'id' => 'ID' + ) + ); + $this->addElement('center', 'Block', 'Flow', 'Common'); + $this->addElement( + 'dir', + 'Block', + 'Required: li', + 'Common', + array( + 'compact' => 'Bool#compact' + ) + ); + $this->addElement( + 'font', + 'Inline', + 'Inline', + array('Core', 'I18N'), + array( + 'color' => 'Color', + 'face' => 'Text', // extremely broad, we should + 'size' => 'Text', // tighten it + ) + ); + $this->addElement( + 'menu', + 'Block', + 'Required: li', + 'Common', + array( + 'compact' => 'Bool#compact' + ) + ); + + $s = $this->addElement('s', 'Inline', 'Inline', 'Common'); + $s->formatting = true; + + $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common'); + $strike->formatting = true; + + $u = $this->addElement('u', 'Inline', 'Inline', 'Common'); + $u->formatting = true; + + // setup modifications to old elements + + $align = 'Enum#left,right,center,justify'; + + $address = $this->addBlankElement('address'); + $address->content_model = 'Inline | #PCDATA | p'; + $address->content_model_type = 'optional'; + $address->child = false; + + $blockquote = $this->addBlankElement('blockquote'); + $blockquote->content_model = 'Flow | #PCDATA'; + $blockquote->content_model_type = 'optional'; + $blockquote->child = false; + + $br = $this->addBlankElement('br'); + $br->attr['clear'] = 'Enum#left,all,right,none'; + + $caption = $this->addBlankElement('caption'); + $caption->attr['align'] = 'Enum#top,bottom,left,right'; + + $div = $this->addBlankElement('div'); + $div->attr['align'] = $align; + + $dl = $this->addBlankElement('dl'); + $dl->attr['compact'] = 'Bool#compact'; + + for ($i = 1; $i <= 6; $i++) { + $h = $this->addBlankElement("h$i"); + $h->attr['align'] = $align; + } + + $hr = $this->addBlankElement('hr'); + $hr->attr['align'] = $align; + $hr->attr['noshade'] = 'Bool#noshade'; + $hr->attr['size'] = 'Pixels'; + $hr->attr['width'] = 'Length'; + + $img = $this->addBlankElement('img'); + $img->attr['align'] = 'IAlign'; + $img->attr['border'] = 'Pixels'; + $img->attr['hspace'] = 'Pixels'; + $img->attr['vspace'] = 'Pixels'; + + // figure out this integer business + + $li = $this->addBlankElement('li'); + $li->attr['value'] = new HTMLPurifier_AttrDef_Integer(); + $li->attr['type'] = 'Enum#s:1,i,I,a,A,disc,square,circle'; + + $ol = $this->addBlankElement('ol'); + $ol->attr['compact'] = 'Bool#compact'; + $ol->attr['start'] = new HTMLPurifier_AttrDef_Integer(); + $ol->attr['type'] = 'Enum#s:1,i,I,a,A'; + + $p = $this->addBlankElement('p'); + $p->attr['align'] = $align; + + $pre = $this->addBlankElement('pre'); + $pre->attr['width'] = 'Number'; + + // script omitted + + $table = $this->addBlankElement('table'); + $table->attr['align'] = 'Enum#left,center,right'; + $table->attr['bgcolor'] = 'Color'; + + $tr = $this->addBlankElement('tr'); + $tr->attr['bgcolor'] = 'Color'; + + $th = $this->addBlankElement('th'); + $th->attr['bgcolor'] = 'Color'; + $th->attr['height'] = 'Length'; + $th->attr['nowrap'] = 'Bool#nowrap'; + $th->attr['width'] = 'Length'; + + $td = $this->addBlankElement('td'); + $td->attr['bgcolor'] = 'Color'; + $td->attr['height'] = 'Length'; + $td->attr['nowrap'] = 'Bool#nowrap'; + $td->attr['width'] = 'Length'; + + $ul = $this->addBlankElement('ul'); + $ul->attr['compact'] = 'Bool#compact'; + $ul->attr['type'] = 'Enum#square,disc,circle'; + + // "safe" modifications to "unsafe" elements + // WARNING: If you want to add support for an unsafe, legacy + // attribute, make a new TrustedLegacy module with the trusted + // bit set appropriately + + $form = $this->addBlankElement('form'); + $form->content_model = 'Flow | #PCDATA'; + $form->content_model_type = 'optional'; + $form->attr['target'] = 'FrameTarget'; + + $input = $this->addBlankElement('input'); + $input->attr['align'] = 'IAlign'; + + $legend = $this->addBlankElement('legend'); + $legend->attr['align'] = 'LAlign'; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/List.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/List.php new file mode 100644 index 00000000..7a20ff70 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/List.php @@ -0,0 +1,51 @@ + 'List'); + + /** + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + $ol = $this->addElement('ol', 'List', new HTMLPurifier_ChildDef_List(), 'Common'); + $ul = $this->addElement('ul', 'List', new HTMLPurifier_ChildDef_List(), 'Common'); + // XXX The wrap attribute is handled by MakeWellFormed. This is all + // quite unsatisfactory, because we generated this + // *specifically* for lists, and now a big chunk of the handling + // is done properly by the List ChildDef. So actually, we just + // want enough information to make autoclosing work properly, + // and then hand off the tricky stuff to the ChildDef. + $ol->wrap = 'li'; + $ul->wrap = 'li'; + $this->addElement('dl', 'List', 'Required: dt | dd', 'Common'); + + $this->addElement('li', false, 'Flow', 'Common'); + + $this->addElement('dd', false, 'Flow', 'Common'); + $this->addElement('dt', false, 'Inline', 'Common'); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Name.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Name.php new file mode 100644 index 00000000..60c05451 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Name.php @@ -0,0 +1,26 @@ +addBlankElement($name); + $element->attr['name'] = 'CDATA'; + if (!$config->get('HTML.Attr.Name.UseCDATA')) { + $element->attr_transform_post[] = new HTMLPurifier_AttrTransform_NameSync(); + } + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Nofollow.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Nofollow.php new file mode 100644 index 00000000..dc9410a8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Nofollow.php @@ -0,0 +1,25 @@ +addBlankElement('a'); + $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_Nofollow(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php new file mode 100644 index 00000000..da722253 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/NonXMLCommonAttributes.php @@ -0,0 +1,20 @@ + array( + 'lang' => 'LanguageCode', + ) + ); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Object.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Object.php new file mode 100644 index 00000000..2f9efc5c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Object.php @@ -0,0 +1,62 @@ + to cater to legacy browsers: this + * module does not allow this sort of behavior + */ +class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule +{ + /** + * @type string + */ + public $name = 'Object'; + + /** + * @type bool + */ + public $safe = false; + + /** + * @param HTMLPurifier_Config $config + */ + public function setup($config) + { + $this->addElement( + 'object', + 'Inline', + 'Optional: #PCDATA | Flow | param', + 'Common', + array( + 'archive' => 'URI', + 'classid' => 'URI', + 'codebase' => 'URI', + 'codetype' => 'Text', + 'data' => 'URI', + 'declare' => 'Bool#declare', + 'height' => 'Length', + 'name' => 'CDATA', + 'standby' => 'Text', + 'tabindex' => 'Number', + 'type' => 'ContentType', + 'width' => 'Length' + ) + ); + + $this->addElement( + 'param', + false, + 'Empty', + null, + array( + 'id' => 'ID', + 'name*' => 'Text', + 'type' => 'Text', + 'value' => 'Text', + 'valuetype' => 'Enum#data,ref,object' + ) + ); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Presentation.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Presentation.php new file mode 100644 index 00000000..6458ce9d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Presentation.php @@ -0,0 +1,42 @@ +addElement('hr', 'Block', 'Empty', 'Common'); + $this->addElement('sub', 'Inline', 'Inline', 'Common'); + $this->addElement('sup', 'Inline', 'Inline', 'Common'); + $b = $this->addElement('b', 'Inline', 'Inline', 'Common'); + $b->formatting = true; + $big = $this->addElement('big', 'Inline', 'Inline', 'Common'); + $big->formatting = true; + $i = $this->addElement('i', 'Inline', 'Inline', 'Common'); + $i->formatting = true; + $small = $this->addElement('small', 'Inline', 'Inline', 'Common'); + $small->formatting = true; + $tt = $this->addElement('tt', 'Inline', 'Inline', 'Common'); + $tt->formatting = true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Proprietary.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Proprietary.php new file mode 100644 index 00000000..5ee3c8e6 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Proprietary.php @@ -0,0 +1,40 @@ +addElement( + 'marquee', + 'Inline', + 'Flow', + 'Common', + array( + 'direction' => 'Enum#left,right,up,down', + 'behavior' => 'Enum#alternate', + 'width' => 'Length', + 'height' => 'Length', + 'scrolldelay' => 'Number', + 'scrollamount' => 'Number', + 'loop' => 'Number', + 'bgcolor' => 'Color', + 'hspace' => 'Pixels', + 'vspace' => 'Pixels', + ) + ); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Ruby.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Ruby.php new file mode 100644 index 00000000..a0d48924 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Ruby.php @@ -0,0 +1,36 @@ +addElement( + 'ruby', + 'Inline', + 'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))', + 'Common' + ); + $this->addElement('rbc', false, 'Required: rb', 'Common'); + $this->addElement('rtc', false, 'Required: rt', 'Common'); + $rb = $this->addElement('rb', false, 'Inline', 'Common'); + $rb->excludes = array('ruby' => true); + $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number')); + $rt->excludes = array('ruby' => true); + $this->addElement('rp', false, 'Optional: #PCDATA', 'Common'); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeEmbed.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeEmbed.php new file mode 100644 index 00000000..04e6689e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeEmbed.php @@ -0,0 +1,40 @@ +get('HTML.MaxImgLength'); + $embed = $this->addElement( + 'embed', + 'Inline', + 'Empty', + 'Common', + array( + 'src*' => 'URI#embedded', + 'type' => 'Enum#application/x-shockwave-flash', + 'width' => 'Pixels#' . $max, + 'height' => 'Pixels#' . $max, + 'allowscriptaccess' => 'Enum#never', + 'allownetworking' => 'Enum#internal', + 'flashvars' => 'Text', + 'wmode' => 'Enum#window,transparent,opaque', + 'name' => 'ID', + ) + ); + $embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeObject.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeObject.php new file mode 100644 index 00000000..1297f80a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeObject.php @@ -0,0 +1,62 @@ +get('HTML.MaxImgLength'); + $object = $this->addElement( + 'object', + 'Inline', + 'Optional: param | Flow | #PCDATA', + 'Common', + array( + // While technically not required by the spec, we're forcing + // it to this value. + 'type' => 'Enum#application/x-shockwave-flash', + 'width' => 'Pixels#' . $max, + 'height' => 'Pixels#' . $max, + 'data' => 'URI#embedded', + 'codebase' => new HTMLPurifier_AttrDef_Enum( + array( + 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' + ) + ), + ) + ); + $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject(); + + $param = $this->addElement( + 'param', + false, + 'Empty', + false, + array( + 'id' => 'ID', + 'name*' => 'Text', + 'value' => 'Text' + ) + ); + $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam(); + $this->info_injector[] = 'SafeObject'; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeScripting.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeScripting.php new file mode 100644 index 00000000..aea7584c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/SafeScripting.php @@ -0,0 +1,40 @@ +get('HTML.SafeScripting'); + $script = $this->addElement( + 'script', + 'Inline', + 'Optional:', // Not `Empty` to not allow to autoclose the #i', '', $html); + } + + return $html; + } + + /** + * Takes a string of HTML (fragment or document) and returns the content + * @todo Consider making protected + */ + public function extractBody($html) + { + $matches = array(); + $result = preg_match('|(.*?)]*>(.*)|is', $html, $matches); + if ($result) { + // Make sure it's not in a comment + $comment_start = strrpos($matches[1], ''); + if ($comment_start === false || + ($comment_end !== false && $comment_end > $comment_start)) { + return $matches[2]; + } + } + return $html; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/DOMLex.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/DOMLex.php new file mode 100644 index 00000000..ca5f25b8 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/DOMLex.php @@ -0,0 +1,338 @@ +factory = new HTMLPurifier_TokenFactory(); + } + + /** + * @param string $html + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token[] + */ + public function tokenizeHTML($html, $config, $context) + { + $html = $this->normalize($html, $config, $context); + + // attempt to armor stray angled brackets that cannot possibly + // form tags and thus are probably being used as emoticons + if ($config->get('Core.AggressivelyFixLt')) { + $char = '[^a-z!\/]'; + $comment = "/|\z)/is"; + $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html); + do { + $old = $html; + $html = preg_replace("/<($char)/i", '<\\1', $html); + } while ($html !== $old); + $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments + } + + // preprocess html, essential for UTF-8 + $html = $this->wrapHTML($html, $config, $context); + + $doc = new DOMDocument(); + $doc->encoding = 'UTF-8'; // theoretically, the above has this covered + + $options = 0; + if ($config->get('Core.AllowParseManyTags') && defined('LIBXML_PARSEHUGE')) { + $options |= LIBXML_PARSEHUGE; + } + + set_error_handler(array($this, 'muteErrorHandler')); + // loadHTML() fails on PHP 5.3 when second parameter is given + if ($options) { + $doc->loadHTML($html, $options); + } else { + $doc->loadHTML($html); + } + restore_error_handler(); + + $body = $doc->getElementsByTagName('html')->item(0)-> // + getElementsByTagName('body')->item(0); // + + $div = $body->getElementsByTagName('div')->item(0); //
    + $tokens = array(); + $this->tokenizeDOM($div, $tokens, $config); + // If the div has a sibling, that means we tripped across + // a premature
    tag. So remove the div we parsed, + // and then tokenize the rest of body. We can't tokenize + // the sibling directly as we'll lose the tags in that case. + if ($div->nextSibling) { + $body->removeChild($div); + $this->tokenizeDOM($body, $tokens, $config); + } + return $tokens; + } + + /** + * Iterative function that tokenizes a node, putting it into an accumulator. + * To iterate is human, to recurse divine - L. Peter Deutsch + * @param DOMNode $node DOMNode to be tokenized. + * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens. + * @return HTMLPurifier_Token of node appended to previously passed tokens. + */ + protected function tokenizeDOM($node, &$tokens, $config) + { + $level = 0; + $nodes = array($level => new HTMLPurifier_Queue(array($node))); + $closingNodes = array(); + do { + while (!$nodes[$level]->isEmpty()) { + $node = $nodes[$level]->shift(); // FIFO + $collect = $level > 0 ? true : false; + $needEndingTag = $this->createStartNode($node, $tokens, $collect, $config); + if ($needEndingTag) { + $closingNodes[$level][] = $node; + } + if ($node->childNodes && $node->childNodes->length) { + $level++; + $nodes[$level] = new HTMLPurifier_Queue(); + foreach ($node->childNodes as $childNode) { + $nodes[$level]->push($childNode); + } + } + } + $level--; + if ($level && isset($closingNodes[$level])) { + while ($node = array_pop($closingNodes[$level])) { + $this->createEndNode($node, $tokens); + } + } + } while ($level > 0); + } + + /** + * Portably retrieve the tag name of a node; deals with older versions + * of libxml like 2.7.6 + * @param DOMNode $node + */ + protected function getTagName($node) + { + if (isset($node->tagName)) { + return $node->tagName; + } else if (isset($node->nodeName)) { + return $node->nodeName; + } else if (isset($node->localName)) { + return $node->localName; + } + return null; + } + + /** + * Portably retrieve the data of a node; deals with older versions + * of libxml like 2.7.6 + * @param DOMNode $node + */ + protected function getData($node) + { + if (isset($node->data)) { + return $node->data; + } else if (isset($node->nodeValue)) { + return $node->nodeValue; + } else if (isset($node->textContent)) { + return $node->textContent; + } + return null; + } + + + /** + * @param DOMNode $node DOMNode to be tokenized. + * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens. + * @param bool $collect Says whether or start and close are collected, set to + * false at first recursion because it's the implicit DIV + * tag you're dealing with. + * @return bool if the token needs an endtoken + * @todo data and tagName properties don't seem to exist in DOMNode? + */ + protected function createStartNode($node, &$tokens, $collect, $config) + { + // intercept non element nodes. WE MUST catch all of them, + // but we're not getting the character reference nodes because + // those should have been preprocessed + if ($node->nodeType === XML_TEXT_NODE) { + $data = $this->getData($node); // Handle variable data property + if ($data !== null) { + $tokens[] = $this->factory->createText($data); + } + return false; + } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) { + // undo libxml's special treatment of )#si', + array($this, 'scriptCallback'), + $html + ); + } + + $html = $this->normalize($html, $config, $context); + + $cursor = 0; // our location in the text + $inside_tag = false; // whether or not we're parsing the inside of a tag + $array = array(); // result array + + // This is also treated to mean maintain *column* numbers too + $maintain_line_numbers = $config->get('Core.MaintainLineNumbers'); + + if ($maintain_line_numbers === null) { + // automatically determine line numbering by checking + // if error collection is on + $maintain_line_numbers = $config->get('Core.CollectErrors'); + } + + if ($maintain_line_numbers) { + $current_line = 1; + $current_col = 0; + $length = strlen($html); + } else { + $current_line = false; + $current_col = false; + $length = false; + } + $context->register('CurrentLine', $current_line); + $context->register('CurrentCol', $current_col); + $nl = "\n"; + // how often to manually recalculate. This will ALWAYS be right, + // but it's pretty wasteful. Set to 0 to turn off + $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval'); + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + // for testing synchronization + $loops = 0; + + while (++$loops) { + // $cursor is either at the start of a token, or inside of + // a tag (i.e. there was a < immediately before it), as indicated + // by $inside_tag + + if ($maintain_line_numbers) { + // $rcursor, however, is always at the start of a token. + $rcursor = $cursor - (int)$inside_tag; + + // Column number is cheap, so we calculate it every round. + // We're interested at the *end* of the newline string, so + // we need to add strlen($nl) == 1 to $nl_pos before subtracting it + // from our "rcursor" position. + $nl_pos = strrpos($html, $nl, $rcursor - $length); + $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1); + + // recalculate lines + if ($synchronize_interval && // synchronization is on + $cursor > 0 && // cursor is further than zero + $loops % $synchronize_interval === 0) { // time to synchronize! + $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor); + } + } + + $position_next_lt = strpos($html, '<', $cursor); + $position_next_gt = strpos($html, '>', $cursor); + + // triggers on "asdf" but not "asdf " + // special case to set up context + if ($position_next_lt === $cursor) { + $inside_tag = true; + $cursor++; + } + + if (!$inside_tag && $position_next_lt !== false) { + // We are not inside tag and there still is another tag to parse + $token = new + HTMLPurifier_Token_Text( + $this->parseText( + substr( + $html, + $cursor, + $position_next_lt - $cursor + ), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor); + } + $array[] = $token; + $cursor = $position_next_lt + 1; + $inside_tag = true; + continue; + } elseif (!$inside_tag) { + // We are not inside tag but there are no more tags + // If we're already at the end, break + if ($cursor === strlen($html)) { + break; + } + // Create Text of rest of string + $token = new + HTMLPurifier_Token_Text( + $this->parseText( + substr( + $html, + $cursor + ), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + } + $array[] = $token; + break; + } elseif ($inside_tag && $position_next_gt !== false) { + // We are in tag and it is well formed + // Grab the internals of the tag + $strlen_segment = $position_next_gt - $cursor; + + if ($strlen_segment < 1) { + // there's nothing to process! + $token = new HTMLPurifier_Token_Text('<'); + $cursor++; + continue; + } + + $segment = substr($html, $cursor, $strlen_segment); + + if ($segment === false) { + // somehow, we attempted to access beyond the end of + // the string, defense-in-depth, reported by Nate Abele + break; + } + + // Check if it's a comment + if (substr($segment, 0, 3) === '!--') { + // re-determine segment length, looking for --> + $position_comment_end = strpos($html, '-->', $cursor); + if ($position_comment_end === false) { + // uh oh, we have a comment that extends to + // infinity. Can't be helped: set comment + // end position to end of string + if ($e) { + $e->send(E_WARNING, 'Lexer: Unclosed comment'); + } + $position_comment_end = strlen($html); + $end = true; + } else { + $end = false; + } + $strlen_segment = $position_comment_end - $cursor; + $segment = substr($html, $cursor, $strlen_segment); + $token = new + HTMLPurifier_Token_Comment( + substr( + $segment, + 3, + $strlen_segment - 3 + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment); + } + $array[] = $token; + $cursor = $end ? $position_comment_end : $position_comment_end + 3; + $inside_tag = false; + continue; + } + + // Check if it's an end tag + $is_end_tag = (strpos($segment, '/') === 0); + if ($is_end_tag) { + $type = substr($segment, 1); + $token = new HTMLPurifier_Token_End($type); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + $cursor = $position_next_gt + 1; + continue; + } + + // Check leading character is alnum, if not, we may + // have accidently grabbed an emoticon. Translate into + // text and go our merry way + if (!ctype_alpha($segment[0])) { + // XML: $segment[0] !== '_' && $segment[0] !== ':' + if ($e) { + $e->send(E_NOTICE, 'Lexer: Unescaped lt'); + } + $token = new HTMLPurifier_Token_Text('<'); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + continue; + } + + // Check if it is explicitly self closing, if so, remove + // trailing slash. Remember, we could have a tag like
    , so + // any later token processing scripts must convert improperly + // classified EmptyTags from StartTags. + $is_self_closing = (strrpos($segment, '/') === $strlen_segment - 1); + if ($is_self_closing) { + $strlen_segment--; + $segment = substr($segment, 0, $strlen_segment); + } + + // Check if there are any attributes + $position_first_space = strcspn($segment, $this->_whitespace); + + if ($position_first_space >= $strlen_segment) { + if ($is_self_closing) { + $token = new HTMLPurifier_Token_Empty($segment); + } else { + $token = new HTMLPurifier_Token_Start($segment); + } + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $inside_tag = false; + $cursor = $position_next_gt + 1; + continue; + } + + // Grab out all the data + $type = substr($segment, 0, $position_first_space); + $attribute_string = + trim( + substr( + $segment, + $position_first_space + ) + ); + if ($attribute_string) { + $attr = $this->parseAttributeString( + $attribute_string, + $config, + $context + ); + } else { + $attr = array(); + } + + if ($is_self_closing) { + $token = new HTMLPurifier_Token_Empty($type, $attr); + } else { + $token = new HTMLPurifier_Token_Start($type, $attr); + } + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor); + } + $array[] = $token; + $cursor = $position_next_gt + 1; + $inside_tag = false; + continue; + } else { + // inside tag, but there's no ending > sign + if ($e) { + $e->send(E_WARNING, 'Lexer: Missing gt'); + } + $token = new + HTMLPurifier_Token_Text( + '<' . + $this->parseText( + substr($html, $cursor), $config + ) + ); + if ($maintain_line_numbers) { + $token->rawPosition($current_line, $current_col); + } + // no cursor scroll? Hmm... + $array[] = $token; + break; + } + break; + } + + $context->destroy('CurrentLine'); + $context->destroy('CurrentCol'); + return $array; + } + + /** + * PHP 5.0.x compatible substr_count that implements offset and length + * @param string $haystack + * @param string $needle + * @param int $offset + * @param int $length + * @return int + */ + protected function substrCount($haystack, $needle, $offset, $length) + { + static $oldVersion; + if ($oldVersion === null) { + $oldVersion = version_compare(PHP_VERSION, '5.1', '<'); + } + if ($oldVersion) { + $haystack = substr($haystack, $offset, $length); + return substr_count($haystack, $needle); + } else { + return substr_count($haystack, $needle, $offset, $length); + } + } + + /** + * Takes the inside of an HTML tag and makes an assoc array of attributes. + * + * @param string $string Inside of tag excluding name. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return array Assoc array of attributes. + */ + public function parseAttributeString($string, $config, $context) + { + $string = (string)$string; // quick typecast + + if ($string == '') { + return array(); + } // no attributes + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + // let's see if we can abort as quickly as possible + // one equal sign, no spaces => one attribute + $num_equal = substr_count($string, '='); + $has_space = strpos($string, ' '); + if ($num_equal === 0 && !$has_space) { + // bool attribute + return array($string => $string); + } elseif ($num_equal === 1 && !$has_space) { + // only one attribute + list($key, $quoted_value) = explode('=', $string); + $quoted_value = trim($quoted_value); + if (!$key) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + return array(); + } + if (!$quoted_value) { + return array($key => ''); + } + $first_char = @$quoted_value[0]; + $last_char = @$quoted_value[strlen($quoted_value) - 1]; + + $same_quote = ($first_char == $last_char); + $open_quote = ($first_char == '"' || $first_char == "'"); + + if ($same_quote && $open_quote) { + // well behaved + $value = substr($quoted_value, 1, strlen($quoted_value) - 2); + } else { + // not well behaved + if ($open_quote) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing end quote'); + } + $value = substr($quoted_value, 1); + } else { + $value = $quoted_value; + } + } + if ($value === false) { + $value = ''; + } + return array($key => $this->parseAttr($value, $config)); + } + + // setup loop environment + $array = array(); // return assoc array of attributes + $cursor = 0; // current position in string (moves forward) + $size = strlen($string); // size of the string (stays the same) + + // if we have unquoted attributes, the parser expects a terminating + // space, so let's guarantee that there's always a terminating space. + $string .= ' '; + + $old_cursor = -1; + while ($cursor < $size) { + if ($old_cursor >= $cursor) { + throw new Exception("Infinite loop detected"); + } + $old_cursor = $cursor; + + $cursor += ($value = strspn($string, $this->_whitespace, $cursor)); + // grab the key + + $key_begin = $cursor; //we're currently at the start of the key + + // scroll past all characters that are the key (not whitespace or =) + $cursor += strcspn($string, $this->_whitespace . '=', $cursor); + + $key_end = $cursor; // now at the end of the key + + $key = substr($string, $key_begin, $key_end - $key_begin); + + if (!$key) { + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + $cursor += 1 + strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop + continue; // empty key + } + + // scroll past all whitespace + $cursor += strspn($string, $this->_whitespace, $cursor); + + if ($cursor >= $size) { + $array[$key] = $key; + break; + } + + // if the next character is an equal sign, we've got a regular + // pair, otherwise, it's a bool attribute + $first_char = @$string[$cursor]; + + if ($first_char == '=') { + // key="value" + + $cursor++; + $cursor += strspn($string, $this->_whitespace, $cursor); + + if ($cursor === false) { + $array[$key] = ''; + break; + } + + // we might be in front of a quote right now + + $char = @$string[$cursor]; + + if ($char == '"' || $char == "'") { + // it's quoted, end bound is $char + $cursor++; + $value_begin = $cursor; + $cursor = strpos($string, $char, $cursor); + $value_end = $cursor; + } else { + // it's not quoted, end bound is whitespace + $value_begin = $cursor; + $cursor += strcspn($string, $this->_whitespace, $cursor); + $value_end = $cursor; + } + + // we reached a premature end + if ($cursor === false) { + $cursor = $size; + $value_end = $cursor; + } + + $value = substr($string, $value_begin, $value_end - $value_begin); + if ($value === false) { + $value = ''; + } + $array[$key] = $this->parseAttr($value, $config); + $cursor++; + } else { + // boolattr + if ($key !== '') { + $array[$key] = $key; + } else { + // purely theoretical + if ($e) { + $e->send(E_ERROR, 'Lexer: Missing attribute key'); + } + } + } + } + return $array; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/PH5P.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/PH5P.php new file mode 100644 index 00000000..72476ddf --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Lexer/PH5P.php @@ -0,0 +1,4788 @@ +normalize($html, $config, $context); + $new_html = $this->wrapHTML($new_html, $config, $context, false /* no div */); + try { + $parser = new HTML5($new_html); + $doc = $parser->save(); + } catch (DOMException $e) { + // Uh oh, it failed. Punt to DirectLex. + $lexer = new HTMLPurifier_Lexer_DirectLex(); + $context->register('PH5PError', $e); // save the error, so we can detect it + return $lexer->tokenizeHTML($html, $config, $context); // use original HTML + } + $tokens = array(); + $this->tokenizeDOM( + $doc->getElementsByTagName('html')->item(0)-> // + getElementsByTagName('body')->item(0) // + , + $tokens, $config + ); + return $tokens; + } +} + +/* + +Copyright 2007 Jeroen van der Meer + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +class HTML5 +{ + private $data; + private $char; + private $EOF; + private $state; + private $tree; + private $token; + private $content_model; + private $escape = false; + private $entities = array( + 'AElig;', + 'AElig', + 'AMP;', + 'AMP', + 'Aacute;', + 'Aacute', + 'Acirc;', + 'Acirc', + 'Agrave;', + 'Agrave', + 'Alpha;', + 'Aring;', + 'Aring', + 'Atilde;', + 'Atilde', + 'Auml;', + 'Auml', + 'Beta;', + 'COPY;', + 'COPY', + 'Ccedil;', + 'Ccedil', + 'Chi;', + 'Dagger;', + 'Delta;', + 'ETH;', + 'ETH', + 'Eacute;', + 'Eacute', + 'Ecirc;', + 'Ecirc', + 'Egrave;', + 'Egrave', + 'Epsilon;', + 'Eta;', + 'Euml;', + 'Euml', + 'GT;', + 'GT', + 'Gamma;', + 'Iacute;', + 'Iacute', + 'Icirc;', + 'Icirc', + 'Igrave;', + 'Igrave', + 'Iota;', + 'Iuml;', + 'Iuml', + 'Kappa;', + 'LT;', + 'LT', + 'Lambda;', + 'Mu;', + 'Ntilde;', + 'Ntilde', + 'Nu;', + 'OElig;', + 'Oacute;', + 'Oacute', + 'Ocirc;', + 'Ocirc', + 'Ograve;', + 'Ograve', + 'Omega;', + 'Omicron;', + 'Oslash;', + 'Oslash', + 'Otilde;', + 'Otilde', + 'Ouml;', + 'Ouml', + 'Phi;', + 'Pi;', + 'Prime;', + 'Psi;', + 'QUOT;', + 'QUOT', + 'REG;', + 'REG', + 'Rho;', + 'Scaron;', + 'Sigma;', + 'THORN;', + 'THORN', + 'TRADE;', + 'Tau;', + 'Theta;', + 'Uacute;', + 'Uacute', + 'Ucirc;', + 'Ucirc', + 'Ugrave;', + 'Ugrave', + 'Upsilon;', + 'Uuml;', + 'Uuml', + 'Xi;', + 'Yacute;', + 'Yacute', + 'Yuml;', + 'Zeta;', + 'aacute;', + 'aacute', + 'acirc;', + 'acirc', + 'acute;', + 'acute', + 'aelig;', + 'aelig', + 'agrave;', + 'agrave', + 'alefsym;', + 'alpha;', + 'amp;', + 'amp', + 'and;', + 'ang;', + 'apos;', + 'aring;', + 'aring', + 'asymp;', + 'atilde;', + 'atilde', + 'auml;', + 'auml', + 'bdquo;', + 'beta;', + 'brvbar;', + 'brvbar', + 'bull;', + 'cap;', + 'ccedil;', + 'ccedil', + 'cedil;', + 'cedil', + 'cent;', + 'cent', + 'chi;', + 'circ;', + 'clubs;', + 'cong;', + 'copy;', + 'copy', + 'crarr;', + 'cup;', + 'curren;', + 'curren', + 'dArr;', + 'dagger;', + 'darr;', + 'deg;', + 'deg', + 'delta;', + 'diams;', + 'divide;', + 'divide', + 'eacute;', + 'eacute', + 'ecirc;', + 'ecirc', + 'egrave;', + 'egrave', + 'empty;', + 'emsp;', + 'ensp;', + 'epsilon;', + 'equiv;', + 'eta;', + 'eth;', + 'eth', + 'euml;', + 'euml', + 'euro;', + 'exist;', + 'fnof;', + 'forall;', + 'frac12;', + 'frac12', + 'frac14;', + 'frac14', + 'frac34;', + 'frac34', + 'frasl;', + 'gamma;', + 'ge;', + 'gt;', + 'gt', + 'hArr;', + 'harr;', + 'hearts;', + 'hellip;', + 'iacute;', + 'iacute', + 'icirc;', + 'icirc', + 'iexcl;', + 'iexcl', + 'igrave;', + 'igrave', + 'image;', + 'infin;', + 'int;', + 'iota;', + 'iquest;', + 'iquest', + 'isin;', + 'iuml;', + 'iuml', + 'kappa;', + 'lArr;', + 'lambda;', + 'lang;', + 'laquo;', + 'laquo', + 'larr;', + 'lceil;', + 'ldquo;', + 'le;', + 'lfloor;', + 'lowast;', + 'loz;', + 'lrm;', + 'lsaquo;', + 'lsquo;', + 'lt;', + 'lt', + 'macr;', + 'macr', + 'mdash;', + 'micro;', + 'micro', + 'middot;', + 'middot', + 'minus;', + 'mu;', + 'nabla;', + 'nbsp;', + 'nbsp', + 'ndash;', + 'ne;', + 'ni;', + 'not;', + 'not', + 'notin;', + 'nsub;', + 'ntilde;', + 'ntilde', + 'nu;', + 'oacute;', + 'oacute', + 'ocirc;', + 'ocirc', + 'oelig;', + 'ograve;', + 'ograve', + 'oline;', + 'omega;', + 'omicron;', + 'oplus;', + 'or;', + 'ordf;', + 'ordf', + 'ordm;', + 'ordm', + 'oslash;', + 'oslash', + 'otilde;', + 'otilde', + 'otimes;', + 'ouml;', + 'ouml', + 'para;', + 'para', + 'part;', + 'permil;', + 'perp;', + 'phi;', + 'pi;', + 'piv;', + 'plusmn;', + 'plusmn', + 'pound;', + 'pound', + 'prime;', + 'prod;', + 'prop;', + 'psi;', + 'quot;', + 'quot', + 'rArr;', + 'radic;', + 'rang;', + 'raquo;', + 'raquo', + 'rarr;', + 'rceil;', + 'rdquo;', + 'real;', + 'reg;', + 'reg', + 'rfloor;', + 'rho;', + 'rlm;', + 'rsaquo;', + 'rsquo;', + 'sbquo;', + 'scaron;', + 'sdot;', + 'sect;', + 'sect', + 'shy;', + 'shy', + 'sigma;', + 'sigmaf;', + 'sim;', + 'spades;', + 'sub;', + 'sube;', + 'sum;', + 'sup1;', + 'sup1', + 'sup2;', + 'sup2', + 'sup3;', + 'sup3', + 'sup;', + 'supe;', + 'szlig;', + 'szlig', + 'tau;', + 'there4;', + 'theta;', + 'thetasym;', + 'thinsp;', + 'thorn;', + 'thorn', + 'tilde;', + 'times;', + 'times', + 'trade;', + 'uArr;', + 'uacute;', + 'uacute', + 'uarr;', + 'ucirc;', + 'ucirc', + 'ugrave;', + 'ugrave', + 'uml;', + 'uml', + 'upsih;', + 'upsilon;', + 'uuml;', + 'uuml', + 'weierp;', + 'xi;', + 'yacute;', + 'yacute', + 'yen;', + 'yen', + 'yuml;', + 'yuml', + 'zeta;', + 'zwj;', + 'zwnj;' + ); + + const PCDATA = 0; + const RCDATA = 1; + const CDATA = 2; + const PLAINTEXT = 3; + + const DOCTYPE = 0; + const STARTTAG = 1; + const ENDTAG = 2; + const COMMENT = 3; + const CHARACTR = 4; + const EOF = 5; + + public function __construct($data) + { + $this->data = $data; + $this->char = -1; + $this->EOF = strlen($data); + $this->tree = new HTML5TreeConstructer; + $this->content_model = self::PCDATA; + + $this->state = 'data'; + + while ($this->state !== null) { + $this->{$this->state . 'State'}(); + } + } + + public function save() + { + return $this->tree->save(); + } + + private function char() + { + return ($this->char < $this->EOF) + ? $this->data[$this->char] + : false; + } + + private function character($s, $l = 0) + { + if ($s + $l < $this->EOF) { + if ($l === 0) { + return $this->data[$s]; + } else { + return substr($this->data, $s, $l); + } + } + } + + private function characters($char_class, $start) + { + return preg_replace('#^([' . $char_class . ']+).*#s', '\\1', substr($this->data, $start)); + } + + private function dataState() + { + // Consume the next input character + $this->char++; + $char = $this->char(); + + if ($char === '&' && ($this->content_model === self::PCDATA || $this->content_model === self::RCDATA)) { + /* U+0026 AMPERSAND (&) + When the content model flag is set to one of the PCDATA or RCDATA + states: switch to the entity data state. Otherwise: treat it as per + the "anything else" entry below. */ + $this->state = 'entityData'; + + } elseif ($char === '-') { + /* If the content model flag is set to either the RCDATA state or + the CDATA state, and the escape flag is false, and there are at + least three characters before this one in the input stream, and the + last four characters in the input stream, including this one, are + U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, + and U+002D HYPHEN-MINUS (""), + set the escape flag to false. */ + if (($this->content_model === self::RCDATA || + $this->content_model === self::CDATA) && $this->escape === true && + $this->character($this->char, 3) === '-->' + ) { + $this->escape = false; + } + + /* In any case, emit the input character as a character token. + Stay in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + } elseif ($this->char === $this->EOF) { + /* EOF + Emit an end-of-file token. */ + $this->EOF(); + + } elseif ($this->content_model === self::PLAINTEXT) { + /* When the content model flag is set to the PLAINTEXT state + THIS DIFFERS GREATLY FROM THE SPEC: Get the remaining characters of + the text and emit it as a character token. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => substr($this->data, $this->char) + ) + ); + + $this->EOF(); + + } else { + /* Anything else + THIS DIFFERS GREATLY FROM THE SPEC: Get as many character that + otherwise would also be treated as a character token and emit it + as a single character token. Stay in the data state. */ + $len = strcspn($this->data, '<&', $this->char); + $char = substr($this->data, $this->char, $len); + $this->char += $len - 1; + + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + $this->state = 'data'; + } + } + + private function entityDataState() + { + // Attempt to consume an entity. + $entity = $this->entity(); + + // If nothing is returned, emit a U+0026 AMPERSAND character token. + // Otherwise, emit the character token that was returned. + $char = (!$entity) ? '&' : $entity; + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => $char + ) + ); + + // Finally, switch to the data state. + $this->state = 'data'; + } + + private function tagOpenState() + { + switch ($this->content_model) { + case self::RCDATA: + case self::CDATA: + /* If the next input character is a U+002F SOLIDUS (/) character, + consume it and switch to the close tag open state. If the next + input character is not a U+002F SOLIDUS (/) character, emit a + U+003C LESS-THAN SIGN character token and switch to the data + state to process the next input character. */ + if ($this->character($this->char + 1) === '/') { + $this->char++; + $this->state = 'closeTagOpen'; + + } else { + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<' + ) + ); + + $this->state = 'data'; + } + break; + + case self::PCDATA: + // If the content model flag is set to the PCDATA state + // Consume the next input character: + $this->char++; + $char = $this->char(); + + if ($char === '!') { + /* U+0021 EXCLAMATION MARK (!) + Switch to the markup declaration open state. */ + $this->state = 'markupDeclarationOpen'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Switch to the close tag open state. */ + $this->state = 'closeTagOpen'; + + } elseif (preg_match('/^[A-Za-z]$/', $char)) { + /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z + Create a new start tag token, set its tag name to the lowercase + version of the input character (add 0x0020 to the character's code + point), then switch to the tag name state. (Don't emit the token + yet; further details will be filled in before it is emitted.) */ + $this->token = array( + 'name' => strtolower($char), + 'type' => self::STARTTAG, + 'attr' => array() + ); + + $this->state = 'tagName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Parse error. Emit a U+003C LESS-THAN SIGN character token and a + U+003E GREATER-THAN SIGN character token. Switch to the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<>' + ) + ); + + $this->state = 'data'; + + } elseif ($char === '?') { + /* U+003F QUESTION MARK (?) + Parse error. Switch to the bogus comment state. */ + $this->state = 'bogusComment'; + + } else { + /* Anything else + Parse error. Emit a U+003C LESS-THAN SIGN character token and + reconsume the current input character in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => '<' + ) + ); + + $this->char--; + $this->state = 'data'; + } + break; + } + } + + private function closeTagOpenState() + { + $next_node = strtolower($this->characters('A-Za-z', $this->char + 1)); + $the_same = count($this->tree->stack) > 0 && $next_node === end($this->tree->stack)->nodeName; + + if (($this->content_model === self::RCDATA || $this->content_model === self::CDATA) && + (!$the_same || ($the_same && (!preg_match( + '/[\t\n\x0b\x0c >\/]/', + $this->character($this->char + 1 + strlen($next_node)) + ) || $this->EOF === $this->char))) + ) { + /* If the content model flag is set to the RCDATA or CDATA states then + examine the next few characters. If they do not match the tag name of + the last start tag token emitted (case insensitively), or if they do but + they are not immediately followed by one of the following characters: + * U+0009 CHARACTER TABULATION + * U+000A LINE FEED (LF) + * U+000B LINE TABULATION + * U+000C FORM FEED (FF) + * U+0020 SPACE + * U+003E GREATER-THAN SIGN (>) + * U+002F SOLIDUS (/) + * EOF + ...then there is a parse error. Emit a U+003C LESS-THAN SIGN character + token, a U+002F SOLIDUS character token, and switch to the data state + to process the next input character. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => 'state = 'data'; + + } else { + /* Otherwise, if the content model flag is set to the PCDATA state, + or if the next few characters do match that tag name, consume the + next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[A-Za-z]$/', $char)) { + /* U+0041 LATIN LETTER A through to U+005A LATIN LETTER Z + Create a new end tag token, set its tag name to the lowercase version + of the input character (add 0x0020 to the character's code point), then + switch to the tag name state. (Don't emit the token yet; further details + will be filled in before it is emitted.) */ + $this->token = array( + 'name' => strtolower($char), + 'type' => self::ENDTAG + ); + + $this->state = 'tagName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Parse error. Switch to the data state. */ + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit a U+003C LESS-THAN SIGN character token and a U+002F + SOLIDUS character token. Reconsume the EOF character in the data state. */ + $this->emitToken( + array( + 'type' => self::CHARACTR, + 'data' => 'char--; + $this->state = 'data'; + + } else { + /* Parse error. Switch to the bogus comment state. */ + $this->state = 'bogusComment'; + } + } + } + + private function tagNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } else { + /* Anything else + Append the current input character to the current tag token's tag name. + Stay in the tag name state. */ + $this->token['name'] .= strtolower($char); + $this->state = 'tagName'; + } + } + + private function beforeAttributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Stay in the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Start a new attribute in the current tag token. Set that attribute's + name to the current input character, and its value to the empty string. + Switch to the attribute name state. */ + $this->token['attr'][] = array( + 'name' => strtolower($char), + 'value' => null + ); + + $this->state = 'attributeName'; + } + } + + private function attributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute name state. */ + $this->state = 'afterAttributeName'; + + } elseif ($char === '=') { + /* U+003D EQUALS SIGN (=) + Switch to the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/' && $this->character($this->char + 1) !== '>') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the before + attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's name. + Stay in the attribute name state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['name'] .= strtolower($char); + + $this->state = 'attributeName'; + } + } + + private function afterAttributeNameState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the after attribute name state. */ + $this->state = 'afterAttributeName'; + + } elseif ($char === '=') { + /* U+003D EQUALS SIGN (=) + Switch to the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '/' && $this->character($this->char + 1) !== '>') { + /* U+002F SOLIDUS (/) + Parse error unless this is a permitted slash. Switch to the + before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the EOF + character in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Start a new attribute in the current tag token. Set that attribute's + name to the current input character, and its value to the empty string. + Switch to the attribute name state. */ + $this->token['attr'][] = array( + 'name' => strtolower($char), + 'value' => null + ); + + $this->state = 'attributeName'; + } + } + + private function beforeAttributeValueState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Stay in the before attribute value state. */ + $this->state = 'beforeAttributeValue'; + + } elseif ($char === '"') { + /* U+0022 QUOTATION MARK (") + Switch to the attribute value (double-quoted) state. */ + $this->state = 'attributeValueDoubleQuoted'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the attribute value (unquoted) state and reconsume + this input character. */ + $this->char--; + $this->state = 'attributeValueUnquoted'; + + } elseif ($char === '\'') { + /* U+0027 APOSTROPHE (') + Switch to the attribute value (single-quoted) state. */ + $this->state = 'attributeValueSingleQuoted'; + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Switch to the attribute value (unquoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueUnquoted'; + } + } + + private function attributeValueDoubleQuotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if ($char === '"') { + /* U+0022 QUOTATION MARK (") + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState('double'); + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the character + in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (double-quoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueDoubleQuoted'; + } + } + + private function attributeValueSingleQuotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if ($char === '\'') { + /* U+0022 QUOTATION MARK (') + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState('single'); + + } elseif ($this->char === $this->EOF) { + /* EOF + Parse error. Emit the current tag token. Reconsume the character + in the data state. */ + $this->emitToken($this->token); + + $this->char--; + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (single-quoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueSingleQuoted'; + } + } + + private function attributeValueUnquotedState() + { + // Consume the next input character: + $this->char++; + $char = $this->character($this->char); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + /* U+0009 CHARACTER TABULATION + U+000A LINE FEED (LF) + U+000B LINE TABULATION + U+000C FORM FEED (FF) + U+0020 SPACE + Switch to the before attribute name state. */ + $this->state = 'beforeAttributeName'; + + } elseif ($char === '&') { + /* U+0026 AMPERSAND (&) + Switch to the entity in attribute value state. */ + $this->entityInAttributeValueState(); + + } elseif ($char === '>') { + /* U+003E GREATER-THAN SIGN (>) + Emit the current tag token. Switch to the data state. */ + $this->emitToken($this->token); + $this->state = 'data'; + + } else { + /* Anything else + Append the current input character to the current attribute's value. + Stay in the attribute value (unquoted) state. */ + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + + $this->state = 'attributeValueUnquoted'; + } + } + + private function entityInAttributeValueState() + { + // Attempt to consume an entity. + $entity = $this->entity(); + + // If nothing is returned, append a U+0026 AMPERSAND character to the + // current attribute's value. Otherwise, emit the character token that + // was returned. + $char = (!$entity) + ? '&' + : $entity; + + $last = count($this->token['attr']) - 1; + $this->token['attr'][$last]['value'] .= $char; + } + + private function bogusCommentState() + { + /* Consume every character up to the first U+003E GREATER-THAN SIGN + character (>) or the end of the file (EOF), whichever comes first. Emit + a comment token whose data is the concatenation of all the characters + starting from and including the character that caused the state machine + to switch into the bogus comment state, up to and including the last + consumed character before the U+003E character, if any, or up to the + end of the file otherwise. (If the comment was started by the end of + the file (EOF), the token is empty.) */ + $data = $this->characters('^>', $this->char); + $this->emitToken( + array( + 'data' => $data, + 'type' => self::COMMENT + ) + ); + + $this->char += strlen($data); + + /* Switch to the data state. */ + $this->state = 'data'; + + /* If the end of the file was reached, reconsume the EOF character. */ + if ($this->char === $this->EOF) { + $this->char = $this->EOF - 1; + } + } + + private function markupDeclarationOpenState() + { + /* If the next two characters are both U+002D HYPHEN-MINUS (-) + characters, consume those two characters, create a comment token whose + data is the empty string, and switch to the comment state. */ + if ($this->character($this->char + 1, 2) === '--') { + $this->char += 2; + $this->state = 'comment'; + $this->token = array( + 'data' => null, + 'type' => self::COMMENT + ); + + /* Otherwise if the next seven chacacters are a case-insensitive match + for the word "DOCTYPE", then consume those characters and switch to the + DOCTYPE state. */ + } elseif (strtolower($this->character($this->char + 1, 7)) === 'doctype') { + $this->char += 7; + $this->state = 'doctype'; + + /* Otherwise, is is a parse error. Switch to the bogus comment state. + The next character that is consumed, if any, is the first character + that will be in the comment. */ + } else { + $this->char++; + $this->state = 'bogusComment'; + } + } + + private function commentState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + /* U+002D HYPHEN-MINUS (-) */ + if ($char === '-') { + /* Switch to the comment dash state */ + $this->state = 'commentDash'; + + /* EOF */ + } elseif ($this->char === $this->EOF) { + /* Parse error. Emit the comment token. Reconsume the EOF character + in the data state. */ + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + /* Anything else */ + } else { + /* Append the input character to the comment token's data. Stay in + the comment state. */ + $this->token['data'] .= $char; + } + } + + private function commentDashState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + /* U+002D HYPHEN-MINUS (-) */ + if ($char === '-') { + /* Switch to the comment end state */ + $this->state = 'commentEnd'; + + /* EOF */ + } elseif ($this->char === $this->EOF) { + /* Parse error. Emit the comment token. Reconsume the EOF character + in the data state. */ + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + /* Anything else */ + } else { + /* Append a U+002D HYPHEN-MINUS (-) character and the input + character to the comment token's data. Switch to the comment state. */ + $this->token['data'] .= '-' . $char; + $this->state = 'comment'; + } + } + + private function commentEndState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($char === '-') { + $this->token['data'] .= '-'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['data'] .= '--' . $char; + $this->state = 'comment'; + } + } + + private function doctypeState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + $this->state = 'beforeDoctypeName'; + + } else { + $this->char--; + $this->state = 'beforeDoctypeName'; + } + } + + private function beforeDoctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + // Stay in the before DOCTYPE name state. + + } elseif (preg_match('/^[a-z]$/', $char)) { + $this->token = array( + 'name' => strtoupper($char), + 'type' => self::DOCTYPE, + 'error' => true + ); + + $this->state = 'doctypeName'; + + } elseif ($char === '>') { + $this->emitToken( + array( + 'name' => null, + 'type' => self::DOCTYPE, + 'error' => true + ) + ); + + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken( + array( + 'name' => null, + 'type' => self::DOCTYPE, + 'error' => true + ) + ); + + $this->char--; + $this->state = 'data'; + + } else { + $this->token = array( + 'name' => $char, + 'type' => self::DOCTYPE, + 'error' => true + ); + + $this->state = 'doctypeName'; + } + } + + private function doctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + $this->state = 'AfterDoctypeName'; + + } elseif ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif (preg_match('/^[a-z]$/', $char)) { + $this->token['name'] .= strtoupper($char); + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['name'] .= $char; + } + + $this->token['error'] = ($this->token['name'] === 'HTML') + ? false + : true; + } + + private function afterDoctypeNameState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if (preg_match('/^[\t\n\x0b\x0c ]$/', $char)) { + // Stay in the DOCTYPE name state. + + } elseif ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + $this->token['error'] = true; + $this->state = 'bogusDoctype'; + } + } + + private function bogusDoctypeState() + { + /* Consume the next input character: */ + $this->char++; + $char = $this->char(); + + if ($char === '>') { + $this->emitToken($this->token); + $this->state = 'data'; + + } elseif ($this->char === $this->EOF) { + $this->emitToken($this->token); + $this->char--; + $this->state = 'data'; + + } else { + // Stay in the bogus DOCTYPE state. + } + } + + private function entity() + { + $start = $this->char; + + // This section defines how to consume an entity. This definition is + // used when parsing entities in text and in attributes. + + // The behaviour depends on the identity of the next character (the + // one immediately after the U+0026 AMPERSAND character): + + switch ($this->character($this->char + 1)) { + // U+0023 NUMBER SIGN (#) + case '#': + + // The behaviour further depends on the character after the + // U+0023 NUMBER SIGN: + switch ($this->character($this->char + 1)) { + // U+0078 LATIN SMALL LETTER X + // U+0058 LATIN CAPITAL LETTER X + case 'x': + case 'X': + // Follow the steps below, but using the range of + // characters U+0030 DIGIT ZERO through to U+0039 DIGIT + // NINE, U+0061 LATIN SMALL LETTER A through to U+0066 + // LATIN SMALL LETTER F, and U+0041 LATIN CAPITAL LETTER + // A, through to U+0046 LATIN CAPITAL LETTER F (in other + // words, 0-9, A-F, a-f). + $char = 1; + $char_class = '0-9A-Fa-f'; + break; + + // Anything else + default: + // Follow the steps below, but using the range of + // characters U+0030 DIGIT ZERO through to U+0039 DIGIT + // NINE (i.e. just 0-9). + $char = 0; + $char_class = '0-9'; + break; + } + + // Consume as many characters as match the range of characters + // given above. + $this->char++; + $e_name = $this->characters($char_class, $this->char + $char + 1); + $entity = $this->character($start, $this->char); + $cond = strlen($e_name) > 0; + + // The rest of the parsing happens below. + break; + + // Anything else + default: + // Consume the maximum number of characters possible, with the + // consumed characters case-sensitively matching one of the + // identifiers in the first column of the entities table. + + $e_name = $this->characters('0-9A-Za-z;', $this->char + 1); + $len = strlen($e_name); + + for ($c = 1; $c <= $len; $c++) { + $id = substr($e_name, 0, $c); + $this->char++; + + if (in_array($id, $this->entities)) { + if ($e_name[$c - 1] !== ';') { + if ($c < $len && $e_name[$c] == ';') { + $this->char++; // consume extra semicolon + } + } + $entity = $id; + break; + } + } + + $cond = isset($entity); + // The rest of the parsing happens below. + break; + } + + if (!$cond) { + // If no match can be made, then this is a parse error. No + // characters are consumed, and nothing is returned. + $this->char = $start; + return false; + } + + // Return a character token for the character corresponding to the + // entity name (as given by the second column of the entities table). + return html_entity_decode('&' . rtrim($entity, ';') . ';', ENT_QUOTES, 'UTF-8'); + } + + private function emitToken($token) + { + $emit = $this->tree->emitToken($token); + + if (is_int($emit)) { + $this->content_model = $emit; + + } elseif ($token['type'] === self::ENDTAG) { + $this->content_model = self::PCDATA; + } + } + + private function EOF() + { + $this->state = null; + $this->tree->emitToken( + array( + 'type' => self::EOF + ) + ); + } +} + +class HTML5TreeConstructer +{ + public $stack = array(); + + private $phase; + private $mode; + private $dom; + private $foster_parent = null; + private $a_formatting = array(); + + private $head_pointer = null; + private $form_pointer = null; + + private $scoping = array('button', 'caption', 'html', 'marquee', 'object', 'table', 'td', 'th'); + private $formatting = array( + 'a', + 'b', + 'big', + 'em', + 'font', + 'i', + 'nobr', + 's', + 'small', + 'strike', + 'strong', + 'tt', + 'u' + ); + private $special = array( + 'address', + 'area', + 'base', + 'basefont', + 'bgsound', + 'blockquote', + 'body', + 'br', + 'center', + 'col', + 'colgroup', + 'dd', + 'dir', + 'div', + 'dl', + 'dt', + 'embed', + 'fieldset', + 'form', + 'frame', + 'frameset', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'head', + 'hr', + 'iframe', + 'image', + 'img', + 'input', + 'isindex', + 'li', + 'link', + 'listing', + 'menu', + 'meta', + 'noembed', + 'noframes', + 'noscript', + 'ol', + 'optgroup', + 'option', + 'p', + 'param', + 'plaintext', + 'pre', + 'script', + 'select', + 'spacer', + 'style', + 'tbody', + 'textarea', + 'tfoot', + 'thead', + 'title', + 'tr', + 'ul', + 'wbr' + ); + + // The different phases. + const INIT_PHASE = 0; + const ROOT_PHASE = 1; + const MAIN_PHASE = 2; + const END_PHASE = 3; + + // The different insertion modes for the main phase. + const BEFOR_HEAD = 0; + const IN_HEAD = 1; + const AFTER_HEAD = 2; + const IN_BODY = 3; + const IN_TABLE = 4; + const IN_CAPTION = 5; + const IN_CGROUP = 6; + const IN_TBODY = 7; + const IN_ROW = 8; + const IN_CELL = 9; + const IN_SELECT = 10; + const AFTER_BODY = 11; + const IN_FRAME = 12; + const AFTR_FRAME = 13; + + // The different types of elements. + const SPECIAL = 0; + const SCOPING = 1; + const FORMATTING = 2; + const PHRASING = 3; + + const MARKER = 0; + + public function __construct() + { + $this->phase = self::INIT_PHASE; + $this->mode = self::BEFOR_HEAD; + $this->dom = new DOMDocument; + + $this->dom->encoding = 'UTF-8'; + $this->dom->preserveWhiteSpace = true; + $this->dom->substituteEntities = true; + $this->dom->strictErrorChecking = false; + } + + // Process tag tokens + public function emitToken($token) + { + switch ($this->phase) { + case self::INIT_PHASE: + return $this->initPhase($token); + break; + case self::ROOT_PHASE: + return $this->rootElementPhase($token); + break; + case self::MAIN_PHASE: + return $this->mainPhase($token); + break; + case self::END_PHASE : + return $this->trailingEndPhase($token); + break; + } + } + + private function initPhase($token) + { + /* Initially, the tree construction stage must handle each token + emitted from the tokenisation stage as follows: */ + + /* A DOCTYPE token that is marked as being in error + A comment token + A start tag token + An end tag token + A character token that is not one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE + An end-of-file token */ + if ((isset($token['error']) && $token['error']) || + $token['type'] === HTML5::COMMENT || + $token['type'] === HTML5::STARTTAG || + $token['type'] === HTML5::ENDTAG || + $token['type'] === HTML5::EOF || + ($token['type'] === HTML5::CHARACTR && isset($token['data']) && + !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) + ) { + /* This specification does not define how to handle this case. In + particular, user agents may ignore the entirety of this specification + altogether for such documents, and instead invoke special parse modes + with a greater emphasis on backwards compatibility. */ + + $this->phase = self::ROOT_PHASE; + return $this->rootElementPhase($token); + + /* A DOCTYPE token marked as being correct */ + } elseif (isset($token['error']) && !$token['error']) { + /* Append a DocumentType node to the Document node, with the name + attribute set to the name given in the DOCTYPE token (which will be + "HTML"), and the other attributes specific to DocumentType objects + set to null, empty lists, or the empty string as appropriate. */ + $doctype = new DOMDocumentType(null, null, 'HTML'); + + /* Then, switch to the root element phase of the tree construction + stage. */ + $this->phase = self::ROOT_PHASE; + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif (isset($token['data']) && preg_match( + '/^[\t\n\x0b\x0c ]+$/', + $token['data'] + ) + ) { + /* Append that character to the Document node. */ + $text = $this->dom->createTextNode($token['data']); + $this->dom->appendChild($text); + } + } + + private function rootElementPhase($token) + { + /* After the initial phase, as each token is emitted from the tokenisation + stage, it must be processed as described in this section. */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the Document object with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->dom->appendChild($comment); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append that character to the Document node. */ + $text = $this->dom->createTextNode($token['data']); + $this->dom->appendChild($text); + + /* A character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED + (FF), or U+0020 SPACE + A start tag token + An end tag token + An end-of-file token */ + } elseif (($token['type'] === HTML5::CHARACTR && + !preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || + $token['type'] === HTML5::STARTTAG || + $token['type'] === HTML5::ENDTAG || + $token['type'] === HTML5::EOF + ) { + /* Create an HTMLElement node with the tag name html, in the HTML + namespace. Append it to the Document object. Switch to the main + phase and reprocess the current token. */ + $html = $this->dom->createElement('html'); + $this->dom->appendChild($html); + $this->stack[] = $html; + + $this->phase = self::MAIN_PHASE; + return $this->mainPhase($token); + } + } + + private function mainPhase($token) + { + /* Tokens in the main phase must be handled as follows: */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A start tag token with the tag name "html" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'html') { + /* If this start tag token was not the first start tag token, then + it is a parse error. */ + + /* For each attribute on the token, check to see if the attribute + is already present on the top element of the stack of open elements. + If it is not, add the attribute and its corresponding value to that + element. */ + foreach ($token['attr'] as $attr) { + if (!$this->stack[0]->hasAttribute($attr['name'])) { + $this->stack[0]->setAttribute($attr['name'], $attr['value']); + } + } + + /* An end-of-file token */ + } elseif ($token['type'] === HTML5::EOF) { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Anything else. */ + } else { + /* Depends on the insertion mode: */ + switch ($this->mode) { + case self::BEFOR_HEAD: + return $this->beforeHead($token); + break; + case self::IN_HEAD: + return $this->inHead($token); + break; + case self::AFTER_HEAD: + return $this->afterHead($token); + break; + case self::IN_BODY: + return $this->inBody($token); + break; + case self::IN_TABLE: + return $this->inTable($token); + break; + case self::IN_CAPTION: + return $this->inCaption($token); + break; + case self::IN_CGROUP: + return $this->inColumnGroup($token); + break; + case self::IN_TBODY: + return $this->inTableBody($token); + break; + case self::IN_ROW: + return $this->inRow($token); + break; + case self::IN_CELL: + return $this->inCell($token); + break; + case self::IN_SELECT: + return $this->inSelect($token); + break; + case self::AFTER_BODY: + return $this->afterBody($token); + break; + case self::IN_FRAME: + return $this->inFrameset($token); + break; + case self::AFTR_FRAME: + return $this->afterFrameset($token); + break; + case self::END_PHASE: + return $this->trailingEndPhase($token); + break; + } + } + } + + private function beforeHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token with the tag name "head" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') { + /* Create an element for the token, append the new element to the + current node and push it onto the stack of open elements. */ + $element = $this->insertElement($token); + + /* Set the head element pointer to this new element node. */ + $this->head_pointer = $element; + + /* Change the insertion mode to "in head". */ + $this->mode = self::IN_HEAD; + + /* A start tag token whose tag name is one of: "base", "link", "meta", + "script", "style", "title". Or an end tag with the tag name "html". + Or a character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. Or any other start tag token */ + } elseif ($token['type'] === HTML5::STARTTAG || + ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') || + ($token['type'] === HTML5::CHARACTR && !preg_match( + '/^[\t\n\x0b\x0c ]$/', + $token['data'] + )) + ) { + /* Act as if a start tag token with the tag name "head" and no + attributes had been seen, then reprocess the current token. */ + $this->beforeHead( + array( + 'name' => 'head', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inHead($token); + + /* Any other end tag */ + } elseif ($token['type'] === HTML5::ENDTAG) { + /* Parse error. Ignore the token. */ + } + } + + private function inHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. + + THIS DIFFERS FROM THE SPEC: If the current node is either a title, style + or script element, append the character to the current node regardless + of its content. */ + if (($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || ( + $token['type'] === HTML5::CHARACTR && in_array( + end($this->stack)->nodeName, + array('title', 'style', 'script') + )) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('title', 'style', 'script')) + ) { + array_pop($this->stack); + return HTML5::PCDATA; + + /* A start tag with the tag name "title" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'title') { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + } else { + $element = $this->insertElement($token); + } + + /* Switch the tokeniser's content model flag to the RCDATA state. */ + return HTML5::RCDATA; + + /* A start tag with the tag name "style" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'style') { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + } else { + $this->insertElement($token); + } + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + + /* A start tag with the tag name "script" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'script') { + /* Create an element for the token. */ + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + + /* A start tag with the tag name "base", "link", or "meta" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('base', 'link', 'meta') + ) + ) { + /* Create an element for the token and append the new element to the + node pointed to by the head element pointer, or, if that is null + (innerHTML case), to the current node. */ + if ($this->head_pointer !== null) { + $element = $this->insertElement($token, false); + $this->head_pointer->appendChild($element); + array_pop($this->stack); + + } else { + $this->insertElement($token); + } + + /* An end tag with the tag name "head" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'head') { + /* If the current node is a head element, pop the current node off + the stack of open elements. */ + if ($this->head_pointer->isSameNode(end($this->stack))) { + array_pop($this->stack); + + /* Otherwise, this is a parse error. */ + } else { + // k + } + + /* Change the insertion mode to "after head". */ + $this->mode = self::AFTER_HEAD; + + /* A start tag with the tag name "head" or an end tag except "html". */ + } elseif (($token['type'] === HTML5::STARTTAG && $token['name'] === 'head') || + ($token['type'] === HTML5::ENDTAG && $token['name'] !== 'html') + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* If the current node is a head element, act as if an end tag + token with the tag name "head" had been seen. */ + if ($this->head_pointer->isSameNode(end($this->stack))) { + $this->inHead( + array( + 'name' => 'head', + 'type' => HTML5::ENDTAG + ) + ); + + /* Otherwise, change the insertion mode to "after head". */ + } else { + $this->mode = self::AFTER_HEAD; + } + + /* Then, reprocess the current token. */ + return $this->afterHead($token); + } + } + + private function afterHead($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data attribute + set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token with the tag name "body" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'body') { + /* Insert a body element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in body". */ + $this->mode = self::IN_BODY; + + /* A start tag token with the tag name "frameset" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'frameset') { + /* Insert a frameset element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in frameset". */ + $this->mode = self::IN_FRAME; + + /* A start tag token whose tag name is one of: "base", "link", "meta", + "script", "style", "title" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('base', 'link', 'meta', 'script', 'style', 'title') + ) + ) { + /* Parse error. Switch the insertion mode back to "in head" and + reprocess the token. */ + $this->mode = self::IN_HEAD; + return $this->inHead($token); + + /* Anything else */ + } else { + /* Act as if a start tag token with the tag name "body" and no + attributes had been seen, and then reprocess the current token. */ + $this->afterHead( + array( + 'name' => 'body', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inBody($token); + } + } + + private function inBody($token) + { + /* Handle the token as follows: */ + + switch ($token['type']) { + /* A character token */ + case HTML5::CHARACTR: + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Append the token's character to the current node. */ + $this->insertText($token['data']); + break; + + /* A comment token */ + case HTML5::COMMENT: + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + break; + + case HTML5::STARTTAG: + switch ($token['name']) { + /* A start tag token whose tag name is one of: "script", + "style" */ + case 'script': + case 'style': + /* Process the token as if the insertion mode had been "in + head". */ + return $this->inHead($token); + break; + + /* A start tag token whose tag name is one of: "base", "link", + "meta", "title" */ + case 'base': + case 'link': + case 'meta': + case 'title': + /* Parse error. Process the token as if the insertion mode + had been "in head". */ + return $this->inHead($token); + break; + + /* A start tag token with the tag name "body" */ + case 'body': + /* Parse error. If the second element on the stack of open + elements is not a body element, or, if the stack of open + elements has only one node on it, then ignore the token. + (innerHTML case) */ + if (count($this->stack) === 1 || $this->stack[1]->nodeName !== 'body') { + // Ignore + + /* Otherwise, for each attribute on the token, check to see + if the attribute is already present on the body element (the + second element) on the stack of open elements. If it is not, + add the attribute and its corresponding value to that + element. */ + } else { + foreach ($token['attr'] as $attr) { + if (!$this->stack[1]->hasAttribute($attr['name'])) { + $this->stack[1]->setAttribute($attr['name'], $attr['value']); + } + } + } + break; + + /* A start tag whose tag name is one of: "address", + "blockquote", "center", "dir", "div", "dl", "fieldset", + "listing", "menu", "ol", "p", "ul" */ + case 'address': + case 'blockquote': + case 'center': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'listing': + case 'menu': + case 'ol': + case 'p': + case 'ul': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + break; + + /* A start tag whose tag name is "form" */ + case 'form': + /* If the form element pointer is not null, ignore the + token with a parse error. */ + if ($this->form_pointer !== null) { + // Ignore. + + /* Otherwise: */ + } else { + /* If the stack of open elements has a p element in + scope, then act as if an end tag with the tag name p + had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token, and set the + form element pointer to point to the element created. */ + $element = $this->insertElement($token); + $this->form_pointer = $element; + } + break; + + /* A start tag whose tag name is "li", "dd" or "dt" */ + case 'li': + case 'dd': + case 'dt': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + $stack_length = count($this->stack) - 1; + + for ($n = $stack_length; 0 <= $n; $n--) { + /* 1. Initialise node to be the current node (the + bottommost node of the stack). */ + $stop = false; + $node = $this->stack[$n]; + $cat = $this->getElementCategory($node->tagName); + + /* 2. If node is an li, dd or dt element, then pop all + the nodes from the current node up to node, including + node, then stop this algorithm. */ + if ($token['name'] === $node->tagName || ($token['name'] !== 'li' + && ($node->tagName === 'dd' || $node->tagName === 'dt')) + ) { + for ($x = $stack_length; $x >= $n; $x--) { + array_pop($this->stack); + } + + break; + } + + /* 3. If node is not in the formatting category, and is + not in the phrasing category, and is not an address or + div element, then stop this algorithm. */ + if ($cat !== self::FORMATTING && $cat !== self::PHRASING && + $node->tagName !== 'address' && $node->tagName !== 'div' + ) { + break; + } + } + + /* Finally, insert an HTML element with the same tag + name as the token's. */ + $this->insertElement($token); + break; + + /* A start tag token whose tag name is "plaintext" */ + case 'plaintext': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been + seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + return HTML5::PLAINTEXT; + break; + + /* A start tag whose tag name is one of: "h1", "h2", "h3", "h4", + "h5", "h6" */ + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the stack of open elements has in scope an element whose + tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then + this is a parse error; pop elements from the stack until an + element with one of those tag names has been popped from the + stack. */ + while ($this->elementInScope(array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))) { + array_pop($this->stack); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + break; + + /* A start tag whose tag name is "a" */ + case 'a': + /* If the list of active formatting elements contains + an element whose tag name is "a" between the end of the + list and the last marker on the list (or the start of + the list if there is no marker on the list), then this + is a parse error; act as if an end tag with the tag name + "a" had been seen, then remove that element from the list + of active formatting elements and the stack of open + elements if the end tag didn't already remove it (it + might not have if the element is not in table scope). */ + $leng = count($this->a_formatting); + + for ($n = $leng - 1; $n >= 0; $n--) { + if ($this->a_formatting[$n] === self::MARKER) { + break; + + } elseif ($this->a_formatting[$n]->nodeName === 'a') { + $this->emitToken( + array( + 'name' => 'a', + 'type' => HTML5::ENDTAG + ) + ); + break; + } + } + + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $el = $this->insertElement($token); + + /* Add that element to the list of active formatting + elements. */ + $this->a_formatting[] = $el; + break; + + /* A start tag whose tag name is one of: "b", "big", "em", "font", + "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */ + case 'b': + case 'big': + case 'em': + case 'font': + case 'i': + case 'nobr': + case 's': + case 'small': + case 'strike': + case 'strong': + case 'tt': + case 'u': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $el = $this->insertElement($token); + + /* Add that element to the list of active formatting + elements. */ + $this->a_formatting[] = $el; + break; + + /* A start tag token whose tag name is "button" */ + case 'button': + /* If the stack of open elements has a button element in scope, + then this is a parse error; act as if an end tag with the tag + name "button" had been seen, then reprocess the token. (We don't + do that. Unnecessary.) */ + if ($this->elementInScope('button')) { + $this->inBody( + array( + 'name' => 'button', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + break; + + /* A start tag token whose tag name is one of: "marquee", "object" */ + case 'marquee': + case 'object': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + break; + + /* A start tag token whose tag name is "xmp" */ + case 'xmp': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Switch the content model flag to the CDATA state. */ + return HTML5::CDATA; + break; + + /* A start tag whose tag name is "table" */ + case 'table': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in table". */ + $this->mode = self::IN_TABLE; + break; + + /* A start tag whose tag name is one of: "area", "basefont", + "bgsound", "br", "embed", "img", "param", "spacer", "wbr" */ + case 'area': + case 'basefont': + case 'bgsound': + case 'br': + case 'embed': + case 'img': + case 'param': + case 'spacer': + case 'wbr': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "hr" */ + case 'hr': + /* If the stack of open elements has a p element in scope, + then act as if an end tag with the tag name p had been seen. */ + if ($this->elementInScope('p')) { + $this->emitToken( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "image" */ + case 'image': + /* Parse error. Change the token's tag name to "img" and + reprocess it. (Don't ask.) */ + $token['name'] = 'img'; + return $this->inBody($token); + break; + + /* A start tag whose tag name is "input" */ + case 'input': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an input element for the token. */ + $element = $this->insertElement($token, false); + + /* If the form element pointer is not null, then associate the + input element with the form element pointed to by the form + element pointer. */ + $this->form_pointer !== null + ? $this->form_pointer->appendChild($element) + : end($this->stack)->appendChild($element); + + /* Pop that input element off the stack of open elements. */ + array_pop($this->stack); + break; + + /* A start tag whose tag name is "isindex" */ + case 'isindex': + /* Parse error. */ + // w/e + + /* If the form element pointer is not null, + then ignore the token. */ + if ($this->form_pointer === null) { + /* Act as if a start tag token with the tag name "form" had + been seen. */ + $this->inBody( + array( + 'name' => 'body', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "hr" had + been seen. */ + $this->inBody( + array( + 'name' => 'hr', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "p" had + been seen. */ + $this->inBody( + array( + 'name' => 'p', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a start tag token with the tag name "label" + had been seen. */ + $this->inBody( + array( + 'name' => 'label', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + /* Act as if a stream of character tokens had been seen. */ + $this->insertText( + 'This is a searchable index. ' . + 'Insert your search keywords here: ' + ); + + /* Act as if a start tag token with the tag name "input" + had been seen, with all the attributes from the "isindex" + token, except with the "name" attribute set to the value + "isindex" (ignoring any explicit "name" attribute). */ + $attr = $token['attr']; + $attr[] = array('name' => 'name', 'value' => 'isindex'); + + $this->inBody( + array( + 'name' => 'input', + 'type' => HTML5::STARTTAG, + 'attr' => $attr + ) + ); + + /* Act as if a stream of character tokens had been seen + (see below for what they should say). */ + $this->insertText( + 'This is a searchable index. ' . + 'Insert your search keywords here: ' + ); + + /* Act as if an end tag token with the tag name "label" + had been seen. */ + $this->inBody( + array( + 'name' => 'label', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if an end tag token with the tag name "p" had + been seen. */ + $this->inBody( + array( + 'name' => 'p', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if a start tag token with the tag name "hr" had + been seen. */ + $this->inBody( + array( + 'name' => 'hr', + 'type' => HTML5::ENDTAG + ) + ); + + /* Act as if an end tag token with the tag name "form" had + been seen. */ + $this->inBody( + array( + 'name' => 'form', + 'type' => HTML5::ENDTAG + ) + ); + } + break; + + /* A start tag whose tag name is "textarea" */ + case 'textarea': + $this->insertElement($token); + + /* Switch the tokeniser's content model flag to the + RCDATA state. */ + return HTML5::RCDATA; + break; + + /* A start tag whose tag name is one of: "iframe", "noembed", + "noframes" */ + case 'iframe': + case 'noembed': + case 'noframes': + $this->insertElement($token); + + /* Switch the tokeniser's content model flag to the CDATA state. */ + return HTML5::CDATA; + break; + + /* A start tag whose tag name is "select" */ + case 'select': + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Change the insertion mode to "in select". */ + $this->mode = self::IN_SELECT; + break; + + /* A start or end tag whose tag name is one of: "caption", "col", + "colgroup", "frame", "frameset", "head", "option", "optgroup", + "tbody", "td", "tfoot", "th", "thead", "tr". */ + case 'caption': + case 'col': + case 'colgroup': + case 'frame': + case 'frameset': + case 'head': + case 'option': + case 'optgroup': + case 'tbody': + case 'td': + case 'tfoot': + case 'th': + case 'thead': + case 'tr': + // Parse error. Ignore the token. + break; + + /* A start or end tag whose tag name is one of: "event-source", + "section", "nav", "article", "aside", "header", "footer", + "datagrid", "command" */ + case 'event-source': + case 'section': + case 'nav': + case 'article': + case 'aside': + case 'header': + case 'footer': + case 'datagrid': + case 'command': + // Work in progress! + break; + + /* A start tag token not covered by the previous entries */ + default: + /* Reconstruct the active formatting elements, if any. */ + $this->reconstructActiveFormattingElements(); + + $this->insertElement($token, true, true); + break; + } + break; + + case HTML5::ENDTAG: + switch ($token['name']) { + /* An end tag with the tag name "body" */ + case 'body': + /* If the second element in the stack of open elements is + not a body element, this is a parse error. Ignore the token. + (innerHTML case) */ + if (count($this->stack) < 2 || $this->stack[1]->nodeName !== 'body') { + // Ignore. + + /* If the current node is not the body element, then this + is a parse error. */ + } elseif (end($this->stack)->nodeName !== 'body') { + // Parse error. + } + + /* Change the insertion mode to "after body". */ + $this->mode = self::AFTER_BODY; + break; + + /* An end tag with the tag name "html" */ + case 'html': + /* Act as if an end tag with tag name "body" had been seen, + then, if that token wasn't ignored, reprocess the current + token. */ + $this->inBody( + array( + 'name' => 'body', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->afterBody($token); + break; + + /* An end tag whose tag name is one of: "address", "blockquote", + "center", "dir", "div", "dl", "fieldset", "listing", "menu", + "ol", "pre", "ul" */ + case 'address': + case 'blockquote': + case 'center': + case 'dir': + case 'div': + case 'dl': + case 'fieldset': + case 'listing': + case 'menu': + case 'ol': + case 'pre': + case 'ul': + /* If the stack of open elements has an element in scope + with the same tag name as that of the token, then generate + implied end tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with + the same tag name as that of the token, then this + is a parse error. */ + // w/e + + /* If the stack of open elements has an element in + scope with the same tag name as that of the token, + then pop elements from this stack until an element + with that tag name has been popped from the stack. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is "form" */ + case 'form': + /* If the stack of open elements has an element in scope + with the same tag name as that of the token, then generate + implied end tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + } + + if (end($this->stack)->nodeName !== $token['name']) { + /* Now, if the current node is not an element with the + same tag name as that of the token, then this is a parse + error. */ + // w/e + + } else { + /* Otherwise, if the current node is an element with + the same tag name as that of the token pop that element + from the stack. */ + array_pop($this->stack); + } + + /* In any case, set the form element pointer to null. */ + $this->form_pointer = null; + break; + + /* An end tag whose tag name is "p" */ + case 'p': + /* If the stack of open elements has a p element in scope, + then generate implied end tags, except for p elements. */ + if ($this->elementInScope('p')) { + $this->generateImpliedEndTags(array('p')); + + /* If the current node is not a p element, then this is + a parse error. */ + // k + + /* If the stack of open elements has a p element in + scope, then pop elements from this stack until the stack + no longer has a p element in scope. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->elementInScope('p')) { + array_pop($this->stack); + + } else { + break; + } + } + } + break; + + /* An end tag whose tag name is "dd", "dt", or "li" */ + case 'dd': + case 'dt': + case 'li': + /* If the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then + generate implied end tags, except for elements with the + same tag name as the token. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(array($token['name'])); + + /* If the current node is not an element with the same + tag name as the token, then this is a parse error. */ + // w/e + + /* If the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then + pop elements from this stack until an element with that + tag name has been popped from the stack. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is one of: "h1", "h2", "h3", "h4", + "h5", "h6" */ + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + $elements = array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'); + + /* If the stack of open elements has in scope an element whose + tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then + generate implied end tags. */ + if ($this->elementInScope($elements)) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with the same + tag name as that of the token, then this is a parse error. */ + // w/e + + /* If the stack of open elements has in scope an element + whose tag name is one of "h1", "h2", "h3", "h4", "h5", or + "h6", then pop elements from the stack until an element + with one of those tag names has been popped from the stack. */ + while ($this->elementInScope($elements)) { + array_pop($this->stack); + } + } + break; + + /* An end tag whose tag name is one of: "a", "b", "big", "em", + "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" */ + case 'a': + case 'b': + case 'big': + case 'em': + case 'font': + case 'i': + case 'nobr': + case 's': + case 'small': + case 'strike': + case 'strong': + case 'tt': + case 'u': + /* 1. Let the formatting element be the last element in + the list of active formatting elements that: + * is between the end of the list and the last scope + marker in the list, if any, or the start of the list + otherwise, and + * has the same tag name as the token. + */ + while (true) { + for ($a = count($this->a_formatting) - 1; $a >= 0; $a--) { + if ($this->a_formatting[$a] === self::MARKER) { + break; + + } elseif ($this->a_formatting[$a]->tagName === $token['name']) { + $formatting_element = $this->a_formatting[$a]; + $in_stack = in_array($formatting_element, $this->stack, true); + $fe_af_pos = $a; + break; + } + } + + /* If there is no such node, or, if that node is + also in the stack of open elements but the element + is not in scope, then this is a parse error. Abort + these steps. The token is ignored. */ + if (!isset($formatting_element) || ($in_stack && + !$this->elementInScope($token['name'])) + ) { + break; + + /* Otherwise, if there is such a node, but that node + is not in the stack of open elements, then this is a + parse error; remove the element from the list, and + abort these steps. */ + } elseif (isset($formatting_element) && !$in_stack) { + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + break; + } + + /* 2. Let the furthest block be the topmost node in the + stack of open elements that is lower in the stack + than the formatting element, and is not an element in + the phrasing or formatting categories. There might + not be one. */ + $fe_s_pos = array_search($formatting_element, $this->stack, true); + $length = count($this->stack); + + for ($s = $fe_s_pos + 1; $s < $length; $s++) { + $category = $this->getElementCategory($this->stack[$s]->nodeName); + + if ($category !== self::PHRASING && $category !== self::FORMATTING) { + $furthest_block = $this->stack[$s]; + } + } + + /* 3. If there is no furthest block, then the UA must + skip the subsequent steps and instead just pop all + the nodes from the bottom of the stack of open + elements, from the current node up to the formatting + element, and remove the formatting element from the + list of active formatting elements. */ + if (!isset($furthest_block)) { + for ($n = $length - 1; $n >= $fe_s_pos; $n--) { + array_pop($this->stack); + } + + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + break; + } + + /* 4. Let the common ancestor be the element + immediately above the formatting element in the stack + of open elements. */ + $common_ancestor = $this->stack[$fe_s_pos - 1]; + + /* 5. If the furthest block has a parent node, then + remove the furthest block from its parent node. */ + if ($furthest_block->parentNode !== null) { + $furthest_block->parentNode->removeChild($furthest_block); + } + + /* 6. Let a bookmark note the position of the + formatting element in the list of active formatting + elements relative to the elements on either side + of it in the list. */ + $bookmark = $fe_af_pos; + + /* 7. Let node and last node be the furthest block. + Follow these steps: */ + $node = $furthest_block; + $last_node = $furthest_block; + + while (true) { + for ($n = array_search($node, $this->stack, true) - 1; $n >= 0; $n--) { + /* 7.1 Let node be the element immediately + prior to node in the stack of open elements. */ + $node = $this->stack[$n]; + + /* 7.2 If node is not in the list of active + formatting elements, then remove node from + the stack of open elements and then go back + to step 1. */ + if (!in_array($node, $this->a_formatting, true)) { + unset($this->stack[$n]); + $this->stack = array_merge($this->stack); + + } else { + break; + } + } + + /* 7.3 Otherwise, if node is the formatting + element, then go to the next step in the overall + algorithm. */ + if ($node === $formatting_element) { + break; + + /* 7.4 Otherwise, if last node is the furthest + block, then move the aforementioned bookmark to + be immediately after the node in the list of + active formatting elements. */ + } elseif ($last_node === $furthest_block) { + $bookmark = array_search($node, $this->a_formatting, true) + 1; + } + + /* 7.5 If node has any children, perform a + shallow clone of node, replace the entry for + node in the list of active formatting elements + with an entry for the clone, replace the entry + for node in the stack of open elements with an + entry for the clone, and let node be the clone. */ + if ($node->hasChildNodes()) { + $clone = $node->cloneNode(); + $s_pos = array_search($node, $this->stack, true); + $a_pos = array_search($node, $this->a_formatting, true); + + $this->stack[$s_pos] = $clone; + $this->a_formatting[$a_pos] = $clone; + $node = $clone; + } + + /* 7.6 Insert last node into node, first removing + it from its previous parent node if any. */ + if ($last_node->parentNode !== null) { + $last_node->parentNode->removeChild($last_node); + } + + $node->appendChild($last_node); + + /* 7.7 Let last node be node. */ + $last_node = $node; + } + + /* 8. Insert whatever last node ended up being in + the previous step into the common ancestor node, + first removing it from its previous parent node if + any. */ + if ($last_node->parentNode !== null) { + $last_node->parentNode->removeChild($last_node); + } + + $common_ancestor->appendChild($last_node); + + /* 9. Perform a shallow clone of the formatting + element. */ + $clone = $formatting_element->cloneNode(); + + /* 10. Take all of the child nodes of the furthest + block and append them to the clone created in the + last step. */ + while ($furthest_block->hasChildNodes()) { + $child = $furthest_block->firstChild; + $furthest_block->removeChild($child); + $clone->appendChild($child); + } + + /* 11. Append that clone to the furthest block. */ + $furthest_block->appendChild($clone); + + /* 12. Remove the formatting element from the list + of active formatting elements, and insert the clone + into the list of active formatting elements at the + position of the aforementioned bookmark. */ + $fe_af_pos = array_search($formatting_element, $this->a_formatting, true); + unset($this->a_formatting[$fe_af_pos]); + $this->a_formatting = array_merge($this->a_formatting); + + $af_part1 = array_slice($this->a_formatting, 0, $bookmark - 1); + $af_part2 = array_slice($this->a_formatting, $bookmark, count($this->a_formatting)); + $this->a_formatting = array_merge($af_part1, array($clone), $af_part2); + + /* 13. Remove the formatting element from the stack + of open elements, and insert the clone into the stack + of open elements immediately after (i.e. in a more + deeply nested position than) the position of the + furthest block in that stack. */ + $fe_s_pos = array_search($formatting_element, $this->stack, true); + $fb_s_pos = array_search($furthest_block, $this->stack, true); + unset($this->stack[$fe_s_pos]); + + $s_part1 = array_slice($this->stack, 0, $fb_s_pos); + $s_part2 = array_slice($this->stack, $fb_s_pos + 1, count($this->stack)); + $this->stack = array_merge($s_part1, array($clone), $s_part2); + + /* 14. Jump back to step 1 in this series of steps. */ + unset($formatting_element, $fe_af_pos, $fe_s_pos, $furthest_block); + } + break; + + /* An end tag token whose tag name is one of: "button", + "marquee", "object" */ + case 'button': + case 'marquee': + case 'object': + /* If the stack of open elements has an element in scope whose + tag name matches the tag name of the token, then generate implied + tags. */ + if ($this->elementInScope($token['name'])) { + $this->generateImpliedEndTags(); + + /* Now, if the current node is not an element with the same + tag name as the token, then this is a parse error. */ + // k + + /* Now, if the stack of open elements has an element in scope + whose tag name matches the tag name of the token, then pop + elements from the stack until that element has been popped from + the stack, and clear the list of active formatting elements up + to the last marker. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === $token['name']) { + $n = -1; + } + + array_pop($this->stack); + } + + $marker = end(array_keys($this->a_formatting, self::MARKER, true)); + + for ($n = count($this->a_formatting) - 1; $n > $marker; $n--) { + array_pop($this->a_formatting); + } + } + break; + + /* Or an end tag whose tag name is one of: "area", "basefont", + "bgsound", "br", "embed", "hr", "iframe", "image", "img", + "input", "isindex", "noembed", "noframes", "param", "select", + "spacer", "table", "textarea", "wbr" */ + case 'area': + case 'basefont': + case 'bgsound': + case 'br': + case 'embed': + case 'hr': + case 'iframe': + case 'image': + case 'img': + case 'input': + case 'isindex': + case 'noembed': + case 'noframes': + case 'param': + case 'select': + case 'spacer': + case 'table': + case 'textarea': + case 'wbr': + // Parse error. Ignore the token. + break; + + /* An end tag token not covered by the previous entries */ + default: + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + /* Initialise node to be the current node (the bottommost + node of the stack). */ + $node = end($this->stack); + + /* If node has the same tag name as the end tag token, + then: */ + if ($token['name'] === $node->nodeName) { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* If the tag name of the end tag token does not + match the tag name of the current node, this is a + parse error. */ + // k + + /* Pop all the nodes from the current node up to + node, including node, then stop this algorithm. */ + for ($x = count($this->stack) - $n; $x >= $n; $x--) { + array_pop($this->stack); + } + + } else { + $category = $this->getElementCategory($node); + + if ($category !== self::SPECIAL && $category !== self::SCOPING) { + /* Otherwise, if node is in neither the formatting + category nor the phrasing category, then this is a + parse error. Stop this algorithm. The end tag token + is ignored. */ + return false; + } + } + } + break; + } + break; + } + } + + private function inTable($token) + { + $clear = array('html', 'table'); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $text = $this->dom->createTextNode($token['data']); + end($this->stack)->appendChild($text); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + end($this->stack)->appendChild($comment); + + /* A start tag whose tag name is "caption" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'caption' + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert a marker at the end of the list of active + formatting elements. */ + $this->a_formatting[] = self::MARKER; + + /* Insert an HTML element for the token, then switch the + insertion mode to "in caption". */ + $this->insertElement($token); + $this->mode = self::IN_CAPTION; + + /* A start tag whose tag name is "colgroup" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'colgroup' + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the + insertion mode to "in column group". */ + $this->insertElement($token); + $this->mode = self::IN_CGROUP; + + /* A start tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'col' + ) { + $this->inTable( + array( + 'name' => 'colgroup', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + $this->inColumnGroup($token); + + /* A start tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('tbody', 'tfoot', 'thead') + ) + ) { + /* Clear the stack back to a table context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the insertion + mode to "in table body". */ + $this->insertElement($token); + $this->mode = self::IN_TBODY; + + /* A start tag whose tag name is one of: "td", "th", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && + in_array($token['name'], array('td', 'th', 'tr')) + ) { + /* Act as if a start tag token with the tag name "tbody" had been + seen, then reprocess the current token. */ + $this->inTable( + array( + 'name' => 'tbody', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inTableBody($token); + + /* A start tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'table' + ) { + /* Parse error. Act as if an end tag token with the tag name "table" + had been seen, then, if that token wasn't ignored, reprocess the + current token. */ + $this->inTable( + array( + 'name' => 'table', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->mainPhase($token); + + /* An end tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'table' + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + return false; + + /* Otherwise: */ + } else { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Now, if the current node is not a table element, then this + is a parse error. */ + // w/e + + /* Pop elements from this stack until a table element has been + popped from the stack. */ + while (true) { + $current = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($current === 'table') { + break; + } + } + + /* Reset the insertion mode appropriately. */ + $this->resetInsertionMode(); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array( + 'body', + 'caption', + 'col', + 'colgroup', + 'html', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* Parse error. Process the token as if the insertion mode was "in + body", with the following exception: */ + + /* If the current node is a table, tbody, tfoot, thead, or tr + element, then, whenever a node would be inserted into the current + node, it must instead be inserted into the foster parent element. */ + if (in_array( + end($this->stack)->nodeName, + array('table', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* The foster parent element is the parent element of the last + table element in the stack of open elements, if there is a + table element and it has such a parent element. If there is no + table element in the stack of open elements (innerHTML case), + then the foster parent element is the first element in the + stack of open elements (the html element). Otherwise, if there + is a table element in the stack of open elements, but the last + table element in the stack of open elements has no parent, or + its parent node is not an element, then the foster parent + element is the element before the last table element in the + stack of open elements. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === 'table') { + $table = $this->stack[$n]; + break; + } + } + + if (isset($table) && $table->parentNode !== null) { + $this->foster_parent = $table->parentNode; + + } elseif (!isset($table)) { + $this->foster_parent = $this->stack[0]; + + } elseif (isset($table) && ($table->parentNode === null || + $table->parentNode->nodeType !== XML_ELEMENT_NODE) + ) { + $this->foster_parent = $this->stack[$n - 1]; + } + } + + $this->inBody($token); + } + } + + private function inCaption($token) + { + /* An end tag whose tag name is "caption" */ + if ($token['type'] === HTML5::ENDTAG && $token['name'] === 'caption') { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore + + /* Otherwise: */ + } else { + /* Generate implied end tags. */ + $this->generateImpliedEndTags(); + + /* Now, if the current node is not a caption element, then this + is a parse error. */ + // w/e + + /* Pop elements from this stack until a caption element has + been popped from the stack. */ + while (true) { + $node = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($node === 'caption') { + break; + } + } + + /* Clear the list of active formatting elements up to the last + marker. */ + $this->clearTheActiveFormattingElementsUpToTheLastMarker(); + + /* Switch the insertion mode to "in table". */ + $this->mode = self::IN_TABLE; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr", or an end tag whose tag + name is "table" */ + } elseif (($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + )) || ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'table') + ) { + /* Parse error. Act as if an end tag with the tag name "caption" + had been seen, then, if that token wasn't ignored, reprocess the + current token. */ + $this->inCaption( + array( + 'name' => 'caption', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inTable($token); + + /* An end tag whose tag name is one of: "body", "col", "colgroup", + "html", "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array( + 'body', + 'col', + 'colgroup', + 'html', + 'tbody', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + // Parse error. Ignore the token. + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in body". */ + $this->inBody($token); + } + } + + private function inColumnGroup($token) + { + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $text = $this->dom->createTextNode($token['data']); + end($this->stack)->appendChild($text); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + end($this->stack)->appendChild($comment); + + /* A start tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::STARTTAG && $token['name'] === 'col') { + /* Insert a col element for the token. Immediately pop the current + node off the stack of open elements. */ + $this->insertElement($token); + array_pop($this->stack); + + /* An end tag whose tag name is "colgroup" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'colgroup' + ) { + /* If the current node is the root html element, then this is a + parse error, ignore the token. (innerHTML case) */ + if (end($this->stack)->nodeName === 'html') { + // Ignore + + /* Otherwise, pop the current node (which will be a colgroup + element) from the stack of open elements. Switch the insertion + mode to "in table". */ + } else { + array_pop($this->stack); + $this->mode = self::IN_TABLE; + } + + /* An end tag whose tag name is "col" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'col') { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Act as if an end tag with the tag name "colgroup" had been seen, + and then, if that token wasn't ignored, reprocess the current token. */ + $this->inColumnGroup( + array( + 'name' => 'colgroup', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inTable($token); + } + } + + private function inTableBody($token) + { + $clear = array('tbody', 'tfoot', 'thead', 'html'); + + /* A start tag whose tag name is "tr" */ + if ($token['type'] === HTML5::STARTTAG && $token['name'] === 'tr') { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Insert a tr element for the token, then switch the insertion + mode to "in row". */ + $this->insertElement($token); + $this->mode = self::IN_ROW; + + /* A start tag whose tag name is one of: "th", "td" */ + } elseif ($token['type'] === HTML5::STARTTAG && + ($token['name'] === 'th' || $token['name'] === 'td') + ) { + /* Parse error. Act as if a start tag with the tag name "tr" had + been seen, then reprocess the current token. */ + $this->inTableBody( + array( + 'name' => 'tr', + 'type' => HTML5::STARTTAG, + 'attr' => array() + ) + ); + + return $this->inRow($token); + + /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('tbody', 'tfoot', 'thead')) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore + + /* Otherwise: */ + } else { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Pop the current node from the stack of open elements. Switch + the insertion mode to "in table". */ + array_pop($this->stack); + $this->mode = self::IN_TABLE; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "tfoot", "thead", or an end tag whose tag name is "table" */ + } elseif (($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('caption', 'col', 'colgroup', 'tbody', 'tfoor', 'thead') + )) || + ($token['type'] === HTML5::STARTTAG && $token['name'] === 'table') + ) { + /* If the stack of open elements does not have a tbody, thead, or + tfoot element in table scope, this is a parse error. Ignore the + token. (innerHTML case) */ + if (!$this->elementInScope(array('tbody', 'thead', 'tfoot'), true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Clear the stack back to a table body context. */ + $this->clearStackToTableContext($clear); + + /* Act as if an end tag with the same tag name as the current + node ("tbody", "tfoot", or "thead") had been seen, then + reprocess the current token. */ + $this->inTableBody( + array( + 'name' => end($this->stack)->nodeName, + 'type' => HTML5::ENDTAG + ) + ); + + return $this->mainPhase($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "td", "th", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr') + ) + ) { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in table". */ + $this->inTable($token); + } + } + + private function inRow($token) + { + $clear = array('tr', 'html'); + + /* A start tag whose tag name is one of: "th", "td" */ + if ($token['type'] === HTML5::STARTTAG && + ($token['name'] === 'th' || $token['name'] === 'td') + ) { + /* Clear the stack back to a table row context. */ + $this->clearStackToTableContext($clear); + + /* Insert an HTML element for the token, then switch the insertion + mode to "in cell". */ + $this->insertElement($token); + $this->mode = self::IN_CELL; + + /* Insert a marker at the end of the list of active formatting + elements. */ + $this->a_formatting[] = self::MARKER; + + /* An end tag whose tag name is "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'tr') { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Clear the stack back to a table row context. */ + $this->clearStackToTableContext($clear); + + /* Pop the current node (which will be a tr element) from the + stack of open elements. Switch the insertion mode to "in table + body". */ + array_pop($this->stack); + $this->mode = self::IN_TBODY; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "tfoot", "thead", "tr" or an end tag whose tag name is "table" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array('caption', 'col', 'colgroup', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* Act as if an end tag with the tag name "tr" had been seen, then, + if that token wasn't ignored, reprocess the current token. */ + $this->inRow( + array( + 'name' => 'tr', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inCell($token); + + /* An end tag whose tag name is one of: "tbody", "tfoot", "thead" */ + } elseif ($token['type'] === HTML5::ENDTAG && + in_array($token['name'], array('tbody', 'tfoot', 'thead')) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Otherwise, act as if an end tag with the tag name "tr" had + been seen, then reprocess the current token. */ + $this->inRow( + array( + 'name' => 'tr', + 'type' => HTML5::ENDTAG + ) + ); + + return $this->inCell($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html", "td", "th" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html', 'td', 'th', 'tr') + ) + ) { + /* Parse error. Ignore the token. */ + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in table". */ + $this->inTable($token); + } + } + + private function inCell($token) + { + /* An end tag whose tag name is one of: "td", "th" */ + if ($token['type'] === HTML5::ENDTAG && + ($token['name'] === 'td' || $token['name'] === 'th') + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as that of the token, then this is a + parse error and the token must be ignored. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise: */ + } else { + /* Generate implied end tags, except for elements with the same + tag name as the token. */ + $this->generateImpliedEndTags(array($token['name'])); + + /* Now, if the current node is not an element with the same tag + name as the token, then this is a parse error. */ + // k + + /* Pop elements from this stack until an element with the same + tag name as the token has been popped from the stack. */ + while (true) { + $node = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($node === $token['name']) { + break; + } + } + + /* Clear the list of active formatting elements up to the last + marker. */ + $this->clearTheActiveFormattingElementsUpToTheLastMarker(); + + /* Switch the insertion mode to "in row". (The current node + will be a tr element at this point.) */ + $this->mode = self::IN_ROW; + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + /* If the stack of open elements does not have a td or th element + in table scope, then this is a parse error; ignore the token. + (innerHTML case) */ + if (!$this->elementInScope(array('td', 'th'), true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* A start tag whose tag name is one of: "caption", "col", "colgroup", + "tbody", "td", "tfoot", "th", "thead", "tr" */ + } elseif ($token['type'] === HTML5::STARTTAG && in_array( + $token['name'], + array( + 'caption', + 'col', + 'colgroup', + 'tbody', + 'td', + 'tfoot', + 'th', + 'thead', + 'tr' + ) + ) + ) { + /* If the stack of open elements does not have a td or th element + in table scope, then this is a parse error; ignore the token. + (innerHTML case) */ + if (!$this->elementInScope(array('td', 'th'), true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* An end tag whose tag name is one of: "body", "caption", "col", + "colgroup", "html" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('body', 'caption', 'col', 'colgroup', 'html') + ) + ) { + /* Parse error. Ignore the token. */ + + /* An end tag whose tag name is one of: "table", "tbody", "tfoot", + "thead", "tr" */ + } elseif ($token['type'] === HTML5::ENDTAG && in_array( + $token['name'], + array('table', 'tbody', 'tfoot', 'thead', 'tr') + ) + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as that of the token (which can only + happen for "tbody", "tfoot" and "thead", or, in the innerHTML case), + then this is a parse error and the token must be ignored. */ + if (!$this->elementInScope($token['name'], true)) { + // Ignore. + + /* Otherwise, close the cell (see below) and reprocess the current + token. */ + } else { + $this->closeCell(); + return $this->inRow($token); + } + + /* Anything else */ + } else { + /* Process the token as if the insertion mode was "in body". */ + $this->inBody($token); + } + } + + private function inSelect($token) + { + /* Handle the token as follows: */ + + /* A character token */ + if ($token['type'] === HTML5::CHARACTR) { + /* Append the token's character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag token whose tag name is "option" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'option' + ) { + /* If the current node is an option element, act as if an end tag + with the tag name "option" had been seen. */ + if (end($this->stack)->nodeName === 'option') { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* A start tag token whose tag name is "optgroup" */ + } elseif ($token['type'] === HTML5::STARTTAG && + $token['name'] === 'optgroup' + ) { + /* If the current node is an option element, act as if an end tag + with the tag name "option" had been seen. */ + if (end($this->stack)->nodeName === 'option') { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the current node is an optgroup element, act as if an end tag + with the tag name "optgroup" had been seen. */ + if (end($this->stack)->nodeName === 'optgroup') { + $this->inSelect( + array( + 'name' => 'optgroup', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* An end tag token whose tag name is "optgroup" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'optgroup' + ) { + /* First, if the current node is an option element, and the node + immediately before it in the stack of open elements is an optgroup + element, then act as if an end tag with the tag name "option" had + been seen. */ + $elements_in_stack = count($this->stack); + + if ($this->stack[$elements_in_stack - 1]->nodeName === 'option' && + $this->stack[$elements_in_stack - 2]->nodeName === 'optgroup' + ) { + $this->inSelect( + array( + 'name' => 'option', + 'type' => HTML5::ENDTAG + ) + ); + } + + /* If the current node is an optgroup element, then pop that node + from the stack of open elements. Otherwise, this is a parse error, + ignore the token. */ + if ($this->stack[$elements_in_stack - 1] === 'optgroup') { + array_pop($this->stack); + } + + /* An end tag token whose tag name is "option" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'option' + ) { + /* If the current node is an option element, then pop that node + from the stack of open elements. Otherwise, this is a parse error, + ignore the token. */ + if (end($this->stack)->nodeName === 'option') { + array_pop($this->stack); + } + + /* An end tag whose tag name is "select" */ + } elseif ($token['type'] === HTML5::ENDTAG && + $token['name'] === 'select' + ) { + /* If the stack of open elements does not have an element in table + scope with the same tag name as the token, this is a parse error. + Ignore the token. (innerHTML case) */ + if (!$this->elementInScope($token['name'], true)) { + // w/e + + /* Otherwise: */ + } else { + /* Pop elements from the stack of open elements until a select + element has been popped from the stack. */ + while (true) { + $current = end($this->stack)->nodeName; + array_pop($this->stack); + + if ($current === 'select') { + break; + } + } + + /* Reset the insertion mode appropriately. */ + $this->resetInsertionMode(); + } + + /* A start tag whose tag name is "select" */ + } elseif ($token['name'] === 'select' && + $token['type'] === HTML5::STARTTAG + ) { + /* Parse error. Act as if the token had been an end tag with the + tag name "select" instead. */ + $this->inSelect( + array( + 'name' => 'select', + 'type' => HTML5::ENDTAG + ) + ); + + /* An end tag whose tag name is one of: "caption", "table", "tbody", + "tfoot", "thead", "tr", "td", "th" */ + } elseif (in_array( + $token['name'], + array( + 'caption', + 'table', + 'tbody', + 'tfoot', + 'thead', + 'tr', + 'td', + 'th' + ) + ) && $token['type'] === HTML5::ENDTAG + ) { + /* Parse error. */ + // w/e + + /* If the stack of open elements has an element in table scope with + the same tag name as that of the token, then act as if an end tag + with the tag name "select" had been seen, and reprocess the token. + Otherwise, ignore the token. */ + if ($this->elementInScope($token['name'], true)) { + $this->inSelect( + array( + 'name' => 'select', + 'type' => HTML5::ENDTAG + ) + ); + + $this->mainPhase($token); + } + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function afterBody($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Process the token as it would be processed if the insertion mode + was "in body". */ + $this->inBody($token); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the first element in the stack of open + elements (the html element), with the data attribute set to the + data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->stack[0]->appendChild($comment); + + /* An end tag with the tag name "html" */ + } elseif ($token['type'] === HTML5::ENDTAG && $token['name'] === 'html') { + /* If the parser was originally created in order to handle the + setting of an element's innerHTML attribute, this is a parse error; + ignore the token. (The element will be an html element in this + case.) (innerHTML case) */ + + /* Otherwise, switch to the trailing end phase. */ + $this->phase = self::END_PHASE; + + /* Anything else */ + } else { + /* Parse error. Set the insertion mode to "in body" and reprocess + the token. */ + $this->mode = self::IN_BODY; + return $this->inBody($token); + } + } + + private function inFrameset($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* A start tag with the tag name "frameset" */ + } elseif ($token['name'] === 'frameset' && + $token['type'] === HTML5::STARTTAG + ) { + $this->insertElement($token); + + /* An end tag with the tag name "frameset" */ + } elseif ($token['name'] === 'frameset' && + $token['type'] === HTML5::ENDTAG + ) { + /* If the current node is the root html element, then this is a + parse error; ignore the token. (innerHTML case) */ + if (end($this->stack)->nodeName === 'html') { + // Ignore + + } else { + /* Otherwise, pop the current node from the stack of open + elements. */ + array_pop($this->stack); + + /* If the parser was not originally created in order to handle + the setting of an element's innerHTML attribute (innerHTML case), + and the current node is no longer a frameset element, then change + the insertion mode to "after frameset". */ + $this->mode = self::AFTR_FRAME; + } + + /* A start tag with the tag name "frame" */ + } elseif ($token['name'] === 'frame' && + $token['type'] === HTML5::STARTTAG + ) { + /* Insert an HTML element for the token. */ + $this->insertElement($token); + + /* Immediately pop the current node off the stack of open elements. */ + array_pop($this->stack); + + /* A start tag with the tag name "noframes" */ + } elseif ($token['name'] === 'noframes' && + $token['type'] === HTML5::STARTTAG + ) { + /* Process the token as if the insertion mode had been "in body". */ + $this->inBody($token); + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function afterFrameset($token) + { + /* Handle the token as follows: */ + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + U+000D CARRIAGE RETURN (CR), or U+0020 SPACE */ + if ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Append the character to the current node. */ + $this->insertText($token['data']); + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the current node with the data + attribute set to the data given in the comment token. */ + $this->insertComment($token['data']); + + /* An end tag with the tag name "html" */ + } elseif ($token['name'] === 'html' && + $token['type'] === HTML5::ENDTAG + ) { + /* Switch to the trailing end phase. */ + $this->phase = self::END_PHASE; + + /* A start tag with the tag name "noframes" */ + } elseif ($token['name'] === 'noframes' && + $token['type'] === HTML5::STARTTAG + ) { + /* Process the token as if the insertion mode had been "in body". */ + $this->inBody($token); + + /* Anything else */ + } else { + /* Parse error. Ignore the token. */ + } + } + + private function trailingEndPhase($token) + { + /* After the main phase, as each token is emitted from the tokenisation + stage, it must be processed as described in this section. */ + + /* A DOCTYPE token */ + if ($token['type'] === HTML5::DOCTYPE) { + // Parse error. Ignore the token. + + /* A comment token */ + } elseif ($token['type'] === HTML5::COMMENT) { + /* Append a Comment node to the Document object with the data + attribute set to the data given in the comment token. */ + $comment = $this->dom->createComment($token['data']); + $this->dom->appendChild($comment); + + /* A character token that is one of one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE */ + } elseif ($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data']) + ) { + /* Process the token as it would be processed in the main phase. */ + $this->mainPhase($token); + + /* A character token that is not one of U+0009 CHARACTER TABULATION, + U+000A LINE FEED (LF), U+000B LINE TABULATION, U+000C FORM FEED (FF), + or U+0020 SPACE. Or a start tag token. Or an end tag token. */ + } elseif (($token['type'] === HTML5::CHARACTR && + preg_match('/^[\t\n\x0b\x0c ]+$/', $token['data'])) || + $token['type'] === HTML5::STARTTAG || $token['type'] === HTML5::ENDTAG + ) { + /* Parse error. Switch back to the main phase and reprocess the + token. */ + $this->phase = self::MAIN_PHASE; + return $this->mainPhase($token); + + /* An end-of-file token */ + } elseif ($token['type'] === HTML5::EOF) { + /* OMG DONE!! */ + } + } + + private function insertElement($token, $append = true, $check = false) + { + // Proprietary workaround for libxml2's limitations with tag names + if ($check) { + // Slightly modified HTML5 tag-name modification, + // removing anything that's not an ASCII letter, digit, or hyphen + $token['name'] = preg_replace('/[^a-z0-9-]/i', '', $token['name']); + // Remove leading hyphens and numbers + $token['name'] = ltrim($token['name'], '-0..9'); + // In theory, this should ever be needed, but just in case + if ($token['name'] === '') { + $token['name'] = 'span'; + } // arbitrary generic choice + } + + $el = $this->dom->createElement($token['name']); + + foreach ($token['attr'] as $attr) { + if (!$el->hasAttribute($attr['name'])) { + $el->setAttribute($attr['name'], $attr['value']); + } + } + + $this->appendToRealParent($el); + $this->stack[] = $el; + + return $el; + } + + private function insertText($data) + { + $text = $this->dom->createTextNode($data); + $this->appendToRealParent($text); + } + + private function insertComment($data) + { + $comment = $this->dom->createComment($data); + $this->appendToRealParent($comment); + } + + private function appendToRealParent($node) + { + if ($this->foster_parent === null) { + end($this->stack)->appendChild($node); + + } elseif ($this->foster_parent !== null) { + /* If the foster parent element is the parent element of the + last table element in the stack of open elements, then the new + node must be inserted immediately before the last table element + in the stack of open elements in the foster parent element; + otherwise, the new node must be appended to the foster parent + element. */ + for ($n = count($this->stack) - 1; $n >= 0; $n--) { + if ($this->stack[$n]->nodeName === 'table' && + $this->stack[$n]->parentNode !== null + ) { + $table = $this->stack[$n]; + break; + } + } + + if (isset($table) && $this->foster_parent->isSameNode($table->parentNode)) { + $this->foster_parent->insertBefore($node, $table); + } else { + $this->foster_parent->appendChild($node); + } + + $this->foster_parent = null; + } + } + + private function elementInScope($el, $table = false) + { + if (is_array($el)) { + foreach ($el as $element) { + if ($this->elementInScope($element, $table)) { + return true; + } + } + + return false; + } + + $leng = count($this->stack); + + for ($n = 0; $n < $leng; $n++) { + /* 1. Initialise node to be the current node (the bottommost node of + the stack). */ + $node = $this->stack[$leng - 1 - $n]; + + if ($node->tagName === $el) { + /* 2. If node is the target node, terminate in a match state. */ + return true; + + } elseif ($node->tagName === 'table') { + /* 3. Otherwise, if node is a table element, terminate in a failure + state. */ + return false; + + } elseif ($table === true && in_array( + $node->tagName, + array( + 'caption', + 'td', + 'th', + 'button', + 'marquee', + 'object' + ) + ) + ) { + /* 4. Otherwise, if the algorithm is the "has an element in scope" + variant (rather than the "has an element in table scope" variant), + and node is one of the following, terminate in a failure state. */ + return false; + + } elseif ($node === $node->ownerDocument->documentElement) { + /* 5. Otherwise, if node is an html element (root element), terminate + in a failure state. (This can only happen if the node is the topmost + node of the stack of open elements, and prevents the next step from + being invoked if there are no more elements in the stack.) */ + return false; + } + + /* Otherwise, set node to the previous entry in the stack of open + elements and return to step 2. (This will never fail, since the loop + will always terminate in the previous step if the top of the stack + is reached.) */ + } + } + + private function reconstructActiveFormattingElements() + { + /* 1. If there are no entries in the list of active formatting elements, + then there is nothing to reconstruct; stop this algorithm. */ + $formatting_elements = count($this->a_formatting); + + if ($formatting_elements === 0) { + return false; + } + + /* 3. Let entry be the last (most recently added) element in the list + of active formatting elements. */ + $entry = end($this->a_formatting); + + /* 2. If the last (most recently added) entry in the list of active + formatting elements is a marker, or if it is an element that is in the + stack of open elements, then there is nothing to reconstruct; stop this + algorithm. */ + if ($entry === self::MARKER || in_array($entry, $this->stack, true)) { + return false; + } + + for ($a = $formatting_elements - 1; $a >= 0; true) { + /* 4. If there are no entries before entry in the list of active + formatting elements, then jump to step 8. */ + if ($a === 0) { + $step_seven = false; + break; + } + + /* 5. Let entry be the entry one earlier than entry in the list of + active formatting elements. */ + $a--; + $entry = $this->a_formatting[$a]; + + /* 6. If entry is neither a marker nor an element that is also in + thetack of open elements, go to step 4. */ + if ($entry === self::MARKER || in_array($entry, $this->stack, true)) { + break; + } + } + + while (true) { + /* 7. Let entry be the element one later than entry in the list of + active formatting elements. */ + if (isset($step_seven) && $step_seven === true) { + $a++; + $entry = $this->a_formatting[$a]; + } + + /* 8. Perform a shallow clone of the element entry to obtain clone. */ + $clone = $entry->cloneNode(); + + /* 9. Append clone to the current node and push it onto the stack + of open elements so that it is the new current node. */ + end($this->stack)->appendChild($clone); + $this->stack[] = $clone; + + /* 10. Replace the entry for entry in the list with an entry for + clone. */ + $this->a_formatting[$a] = $clone; + + /* 11. If the entry for clone in the list of active formatting + elements is not the last entry in the list, return to step 7. */ + if (end($this->a_formatting) !== $clone) { + $step_seven = true; + } else { + break; + } + } + } + + private function clearTheActiveFormattingElementsUpToTheLastMarker() + { + /* When the steps below require the UA to clear the list of active + formatting elements up to the last marker, the UA must perform the + following steps: */ + + while (true) { + /* 1. Let entry be the last (most recently added) entry in the list + of active formatting elements. */ + $entry = end($this->a_formatting); + + /* 2. Remove entry from the list of active formatting elements. */ + array_pop($this->a_formatting); + + /* 3. If entry was a marker, then stop the algorithm at this point. + The list has been cleared up to the last marker. */ + if ($entry === self::MARKER) { + break; + } + } + } + + private function generateImpliedEndTags($exclude = array()) + { + /* When the steps below require the UA to generate implied end tags, + then, if the current node is a dd element, a dt element, an li element, + a p element, a td element, a th element, or a tr element, the UA must + act as if an end tag with the respective tag name had been seen and + then generate implied end tags again. */ + $node = end($this->stack); + $elements = array_diff(array('dd', 'dt', 'li', 'p', 'td', 'th', 'tr'), $exclude); + + while (in_array(end($this->stack)->nodeName, $elements)) { + array_pop($this->stack); + } + } + + private function getElementCategory($node) + { + $name = $node->tagName; + if (in_array($name, $this->special)) { + return self::SPECIAL; + } elseif (in_array($name, $this->scoping)) { + return self::SCOPING; + } elseif (in_array($name, $this->formatting)) { + return self::FORMATTING; + } else { + return self::PHRASING; + } + } + + private function clearStackToTableContext($elements) + { + /* When the steps above require the UA to clear the stack back to a + table context, it means that the UA must, while the current node is not + a table element or an html element, pop elements from the stack of open + elements. If this causes any elements to be popped from the stack, then + this is a parse error. */ + while (true) { + $node = end($this->stack)->nodeName; + + if (in_array($node, $elements)) { + break; + } else { + array_pop($this->stack); + } + } + } + + private function resetInsertionMode() + { + /* 1. Let last be false. */ + $last = false; + $leng = count($this->stack); + + for ($n = $leng - 1; $n >= 0; $n--) { + /* 2. Let node be the last node in the stack of open elements. */ + $node = $this->stack[$n]; + + /* 3. If node is the first node in the stack of open elements, then + set last to true. If the element whose innerHTML attribute is being + set is neither a td element nor a th element, then set node to the + element whose innerHTML attribute is being set. (innerHTML case) */ + if ($this->stack[0]->isSameNode($node)) { + $last = true; + } + + /* 4. If node is a select element, then switch the insertion mode to + "in select" and abort these steps. (innerHTML case) */ + if ($node->nodeName === 'select') { + $this->mode = self::IN_SELECT; + break; + + /* 5. If node is a td or th element, then switch the insertion mode + to "in cell" and abort these steps. */ + } elseif ($node->nodeName === 'td' || $node->nodeName === 'th') { + $this->mode = self::IN_CELL; + break; + + /* 6. If node is a tr element, then switch the insertion mode to + "in row" and abort these steps. */ + } elseif ($node->nodeName === 'tr') { + $this->mode = self::IN_ROW; + break; + + /* 7. If node is a tbody, thead, or tfoot element, then switch the + insertion mode to "in table body" and abort these steps. */ + } elseif (in_array($node->nodeName, array('tbody', 'thead', 'tfoot'))) { + $this->mode = self::IN_TBODY; + break; + + /* 8. If node is a caption element, then switch the insertion mode + to "in caption" and abort these steps. */ + } elseif ($node->nodeName === 'caption') { + $this->mode = self::IN_CAPTION; + break; + + /* 9. If node is a colgroup element, then switch the insertion mode + to "in column group" and abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'colgroup') { + $this->mode = self::IN_CGROUP; + break; + + /* 10. If node is a table element, then switch the insertion mode + to "in table" and abort these steps. */ + } elseif ($node->nodeName === 'table') { + $this->mode = self::IN_TABLE; + break; + + /* 11. If node is a head element, then switch the insertion mode + to "in body" ("in body"! not "in head"!) and abort these steps. + (innerHTML case) */ + } elseif ($node->nodeName === 'head') { + $this->mode = self::IN_BODY; + break; + + /* 12. If node is a body element, then switch the insertion mode to + "in body" and abort these steps. */ + } elseif ($node->nodeName === 'body') { + $this->mode = self::IN_BODY; + break; + + /* 13. If node is a frameset element, then switch the insertion + mode to "in frameset" and abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'frameset') { + $this->mode = self::IN_FRAME; + break; + + /* 14. If node is an html element, then: if the head element + pointer is null, switch the insertion mode to "before head", + otherwise, switch the insertion mode to "after head". In either + case, abort these steps. (innerHTML case) */ + } elseif ($node->nodeName === 'html') { + $this->mode = ($this->head_pointer === null) + ? self::BEFOR_HEAD + : self::AFTER_HEAD; + + break; + + /* 15. If last is true, then set the insertion mode to "in body" + and abort these steps. (innerHTML case) */ + } elseif ($last) { + $this->mode = self::IN_BODY; + break; + } + } + } + + private function closeCell() + { + /* If the stack of open elements has a td or th element in table scope, + then act as if an end tag token with that tag name had been seen. */ + foreach (array('td', 'th') as $cell) { + if ($this->elementInScope($cell, true)) { + $this->inCell( + array( + 'name' => $cell, + 'type' => HTML5::ENDTAG + ) + ); + + break; + } + } + } + + public function save() + { + return $this->dom; + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node.php new file mode 100644 index 00000000..3995fec9 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node.php @@ -0,0 +1,49 @@ +data = $data; + $this->line = $line; + $this->col = $col; + } + + public function toTokenPair() { + return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null); + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Element.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Element.php new file mode 100644 index 00000000..6cbf56da --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Element.php @@ -0,0 +1,59 @@ + form or the form, i.e. + * is it a pair of start/end tokens or an empty token. + * @bool + */ + public $empty = false; + + public $endCol = null, $endLine = null, $endArmor = array(); + + public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) { + $this->name = $name; + $this->attr = $attr; + $this->line = $line; + $this->col = $col; + $this->armor = $armor; + } + + public function toTokenPair() { + // XXX inefficiency here, normalization is not necessary + if ($this->empty) { + return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null); + } else { + $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor); + $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor); + //$end->start = $start; + return array($start, $end); + } + } +} + diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Text.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Text.php new file mode 100644 index 00000000..aec91664 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Node/Text.php @@ -0,0 +1,54 @@ +data = $data; + $this->is_whitespace = $is_whitespace; + $this->line = $line; + $this->col = $col; + } + + public function toTokenPair() { + return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/PercentEncoder.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PercentEncoder.php new file mode 100644 index 00000000..18c8bbb0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PercentEncoder.php @@ -0,0 +1,111 @@ +preserve[$i] = true; + } + for ($i = 65; $i <= 90; $i++) { // upper-case + $this->preserve[$i] = true; + } + for ($i = 97; $i <= 122; $i++) { // lower-case + $this->preserve[$i] = true; + } + $this->preserve[45] = true; // Dash - + $this->preserve[46] = true; // Period . + $this->preserve[95] = true; // Underscore _ + $this->preserve[126]= true; // Tilde ~ + + // extra letters not to escape + if ($preserve !== false) { + for ($i = 0, $c = strlen($preserve); $i < $c; $i++) { + $this->preserve[ord($preserve[$i])] = true; + } + } + } + + /** + * Our replacement for urlencode, it encodes all non-reserved characters, + * as well as any extra characters that were instructed to be preserved. + * @note + * Assumes that the string has already been normalized, making any + * and all percent escape sequences valid. Percents will not be + * re-escaped, regardless of their status in $preserve + * @param string $string String to be encoded + * @return string Encoded string. + */ + public function encode($string) + { + $ret = ''; + for ($i = 0, $c = strlen($string); $i < $c; $i++) { + if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])])) { + $ret .= '%' . sprintf('%02X', $int); + } else { + $ret .= $string[$i]; + } + } + return $ret; + } + + /** + * Fix up percent-encoding by decoding unreserved characters and normalizing. + * @warning This function is affected by $preserve, even though the + * usual desired behavior is for this not to preserve those + * characters. Be careful when reusing instances of PercentEncoder! + * @param string $string String to normalize + * @return string + */ + public function normalize($string) + { + if ($string == '') { + return ''; + } + $parts = explode('%', $string); + $ret = array_shift($parts); + foreach ($parts as $part) { + $length = strlen($part); + if ($length < 2) { + $ret .= '%25' . $part; + continue; + } + $encoding = substr($part, 0, 2); + $text = substr($part, 2); + if (!ctype_xdigit($encoding)) { + $ret .= '%25' . $part; + continue; + } + $int = hexdec($encoding); + if (isset($this->preserve[$int])) { + $ret .= chr($int) . $text; + continue; + } + $encoding = strtoupper($encoding); + $ret .= '%' . $encoding . $text; + } + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer.php new file mode 100644 index 00000000..549e4cea --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer.php @@ -0,0 +1,218 @@ +getAll(); + $context = new HTMLPurifier_Context(); + $this->generator = new HTMLPurifier_Generator($config, $context); + } + + /** + * Main function that renders object or aspect of that object + * @note Parameters vary depending on printer + */ + // function render() {} + + /** + * Returns a start tag + * @param string $tag Tag name + * @param array $attr Attribute array + * @return string + */ + protected function start($tag, $attr = array()) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Start($tag, $attr ? $attr : array()) + ); + } + + /** + * Returns an end tag + * @param string $tag Tag name + * @return string + */ + protected function end($tag) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_End($tag) + ); + } + + /** + * Prints a complete element with content inside + * @param string $tag Tag name + * @param string $contents Element contents + * @param array $attr Tag attributes + * @param bool $escape whether or not to escape contents + * @return string + */ + protected function element($tag, $contents, $attr = array(), $escape = true) + { + return $this->start($tag, $attr) . + ($escape ? $this->escape($contents) : $contents) . + $this->end($tag); + } + + /** + * @param string $tag + * @param array $attr + * @return string + */ + protected function elementEmpty($tag, $attr = array()) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Empty($tag, $attr) + ); + } + + /** + * @param string $text + * @return string + */ + protected function text($text) + { + return $this->generator->generateFromToken( + new HTMLPurifier_Token_Text($text) + ); + } + + /** + * Prints a simple key/value row in a table. + * @param string $name Key + * @param mixed $value Value + * @return string + */ + protected function row($name, $value) + { + if (is_bool($value)) { + $value = $value ? 'On' : 'Off'; + } + return + $this->start('tr') . "\n" . + $this->element('th', $name) . "\n" . + $this->element('td', $value) . "\n" . + $this->end('tr'); + } + + /** + * Escapes a string for HTML output. + * @param string $string String to escape + * @return string + */ + protected function escape($string) + { + $string = HTMLPurifier_Encoder::cleanUTF8($string); + $string = htmlspecialchars($string, ENT_COMPAT, 'UTF-8'); + return $string; + } + + /** + * Takes a list of strings and turns them into a single list + * @param string[] $array List of strings + * @param bool $polite Bool whether or not to add an end before the last + * @return string + */ + protected function listify($array, $polite = false) + { + if (empty($array)) { + return 'None'; + } + $ret = ''; + $i = count($array); + foreach ($array as $value) { + $i--; + $ret .= $value; + if ($i > 0 && !($polite && $i == 1)) { + $ret .= ', '; + } + if ($polite && $i == 1) { + $ret .= 'and '; + } + } + return $ret; + } + + /** + * Retrieves the class of an object without prefixes, as well as metadata + * @param object $obj Object to determine class of + * @param string $sec_prefix Further prefix to remove + * @return string + */ + protected function getClass($obj, $sec_prefix = '') + { + static $five = null; + if ($five === null) { + $five = version_compare(PHP_VERSION, '5', '>='); + } + $prefix = 'HTMLPurifier_' . $sec_prefix; + if (!$five) { + $prefix = strtolower($prefix); + } + $class = str_replace($prefix, '', get_class($obj)); + $lclass = strtolower($class); + $class .= '('; + switch ($lclass) { + case 'enum': + $values = array(); + foreach ($obj->valid_values as $value => $bool) { + $values[] = $value; + } + $class .= implode(', ', $values); + break; + case 'css_composite': + $values = array(); + foreach ($obj->defs as $def) { + $values[] = $this->getClass($def, $sec_prefix); + } + $class .= implode(', ', $values); + break; + case 'css_multiple': + $class .= $this->getClass($obj->single, $sec_prefix) . ', '; + $class .= $obj->max; + break; + case 'css_denyelementdecorator': + $class .= $this->getClass($obj->def, $sec_prefix) . ', '; + $class .= $obj->element; + break; + case 'css_importantdecorator': + $class .= $this->getClass($obj->def, $sec_prefix); + if ($obj->allow) { + $class .= ', !important'; + } + break; + } + $class .= ')'; + return $class; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/CSSDefinition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/CSSDefinition.php new file mode 100644 index 00000000..29505fe1 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/CSSDefinition.php @@ -0,0 +1,44 @@ +def = $config->getCSSDefinition(); + $ret = ''; + + $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer')); + $ret .= $this->start('table'); + + $ret .= $this->element('caption', 'Properties ($info)'); + + $ret .= $this->start('thead'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Property', array('class' => 'heavy')); + $ret .= $this->element('th', 'Definition', array('class' => 'heavy', 'style' => 'width:auto;')); + $ret .= $this->end('tr'); + $ret .= $this->end('thead'); + + ksort($this->def->info); + foreach ($this->def->info as $property => $obj) { + $name = $this->getClass($obj, 'AttrDef_'); + $ret .= $this->row($property, $name); + } + + $ret .= $this->end('table'); + $ret .= $this->end('div'); + + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.css b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.css new file mode 100644 index 00000000..3ff1a88a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.css @@ -0,0 +1,10 @@ + +.hp-config {} + +.hp-config tbody th {text-align:right; padding-right:0.5em;} +.hp-config thead, .hp-config .namespace {background:#3C578C; color:#FFF;} +.hp-config .namespace th {text-align:center;} +.hp-config .verbose {display:none;} +.hp-config .controls {text-align:center;} + +/* vim: et sw=4 sts=4 */ diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.js b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.js new file mode 100644 index 00000000..cba00c9b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.js @@ -0,0 +1,5 @@ +function toggleWriteability(id_of_patient, checked) { + document.getElementById(id_of_patient).disabled = checked; +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.php new file mode 100644 index 00000000..33ae1139 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/ConfigForm.php @@ -0,0 +1,451 @@ +docURL = $doc_url; + $this->name = $name; + $this->compress = $compress; + // initialize sub-printers + $this->fields[0] = new HTMLPurifier_Printer_ConfigForm_default(); + $this->fields[HTMLPurifier_VarParser::C_BOOL] = new HTMLPurifier_Printer_ConfigForm_bool(); + } + + /** + * Sets default column and row size for textareas in sub-printers + * @param $cols Integer columns of textarea, null to use default + * @param $rows Integer rows of textarea, null to use default + */ + public function setTextareaDimensions($cols = null, $rows = null) + { + if ($cols) { + $this->fields['default']->cols = $cols; + } + if ($rows) { + $this->fields['default']->rows = $rows; + } + } + + /** + * Retrieves styling, in case it is not accessible by webserver + */ + public static function getCSS() + { + return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.css'); + } + + /** + * Retrieves JavaScript, in case it is not accessible by webserver + */ + public static function getJavaScript() + { + return file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/Printer/ConfigForm.js'); + } + + /** + * Returns HTML output for a configuration form + * @param HTMLPurifier_Config|array $config Configuration object of current form state, or an array + * where [0] has an HTML namespace and [1] is being rendered. + * @param array|bool $allowed Optional namespace(s) and directives to restrict form to. + * @param bool $render_controls + * @return string + */ + public function render($config, $allowed = true, $render_controls = true) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + + $this->config = $config; + $this->genConfig = $gen_config; + $this->prepareGenerator($gen_config); + + $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $config->def); + $all = array(); + foreach ($allowed as $key) { + list($ns, $directive) = $key; + $all[$ns][$directive] = $config->get($ns . '.' . $directive); + } + + $ret = ''; + $ret .= $this->start('table', array('class' => 'hp-config')); + $ret .= $this->start('thead'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Directive', array('class' => 'hp-directive')); + $ret .= $this->element('th', 'Value', array('class' => 'hp-value')); + $ret .= $this->end('tr'); + $ret .= $this->end('thead'); + foreach ($all as $ns => $directives) { + $ret .= $this->renderNamespace($ns, $directives); + } + if ($render_controls) { + $ret .= $this->start('tbody'); + $ret .= $this->start('tr'); + $ret .= $this->start('td', array('colspan' => 2, 'class' => 'controls')); + $ret .= $this->elementEmpty('input', array('type' => 'submit', 'value' => 'Submit')); + $ret .= '[Reset]'; + $ret .= $this->end('td'); + $ret .= $this->end('tr'); + $ret .= $this->end('tbody'); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders a single namespace + * @param $ns String namespace name + * @param array $directives array of directives to values + * @return string + */ + protected function renderNamespace($ns, $directives) + { + $ret = ''; + $ret .= $this->start('tbody', array('class' => 'namespace')); + $ret .= $this->start('tr'); + $ret .= $this->element('th', $ns, array('colspan' => 2)); + $ret .= $this->end('tr'); + $ret .= $this->end('tbody'); + $ret .= $this->start('tbody'); + foreach ($directives as $directive => $value) { + $ret .= $this->start('tr'); + $ret .= $this->start('th'); + if ($this->docURL) { + $url = str_replace('%s', urlencode("$ns.$directive"), $this->docURL); + $ret .= $this->start('a', array('href' => $url)); + } + $attr = array('for' => "{$this->name}:$ns.$directive"); + + // crop directive name if it's too long + if (!$this->compress || (strlen($directive) < $this->compress)) { + $directive_disp = $directive; + } else { + $directive_disp = substr($directive, 0, $this->compress - 2) . '...'; + $attr['title'] = $directive; + } + + $ret .= $this->element( + 'label', + $directive_disp, + // component printers must create an element with this id + $attr + ); + if ($this->docURL) { + $ret .= $this->end('a'); + } + $ret .= $this->end('th'); + + $ret .= $this->start('td'); + $def = $this->config->def->info["$ns.$directive"]; + if (is_int($def)) { + $allow_null = $def < 0; + $type = abs($def); + } else { + $type = $def->type; + $allow_null = isset($def->allow_null); + } + if (!isset($this->fields[$type])) { + $type = 0; + } // default + $type_obj = $this->fields[$type]; + if ($allow_null) { + $type_obj = new HTMLPurifier_Printer_ConfigForm_NullDecorator($type_obj); + } + $ret .= $type_obj->render($ns, $directive, $value, $this->name, array($this->genConfig, $this->config)); + $ret .= $this->end('td'); + $ret .= $this->end('tr'); + } + $ret .= $this->end('tbody'); + return $ret; + } + +} + +/** + * Printer decorator for directives that accept null + */ +class HTMLPurifier_Printer_ConfigForm_NullDecorator extends HTMLPurifier_Printer +{ + /** + * Printer being decorated + * @type HTMLPurifier_Printer + */ + protected $obj; + + /** + * @param HTMLPurifier_Printer $obj Printer to decorate + */ + public function __construct($obj) + { + parent::__construct(); + $this->obj = $obj; + } + + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + + $ret = ''; + $ret .= $this->start('label', array('for' => "$name:Null_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' Null/Disabled'); + $ret .= $this->end('label'); + $attr = array( + 'type' => 'checkbox', + 'value' => '1', + 'class' => 'null-toggle', + 'name' => "$name" . "[Null_$ns.$directive]", + 'id' => "$name:Null_$ns.$directive", + 'onclick' => "toggleWriteability('$name:$ns.$directive',checked)" // INLINE JAVASCRIPT!!!! + ); + if ($this->obj instanceof HTMLPurifier_Printer_ConfigForm_bool) { + // modify inline javascript slightly + $attr['onclick'] = + "toggleWriteability('$name:Yes_$ns.$directive',checked);" . + "toggleWriteability('$name:No_$ns.$directive',checked)"; + } + if ($value === null) { + $attr['checked'] = 'checked'; + } + $ret .= $this->elementEmpty('input', $attr); + $ret .= $this->text(' or '); + $ret .= $this->elementEmpty('br'); + $ret .= $this->obj->render($ns, $directive, $value, $name, array($gen_config, $config)); + return $ret; + } +} + +/** + * Swiss-army knife configuration form field printer + */ +class HTMLPurifier_Printer_ConfigForm_default extends HTMLPurifier_Printer +{ + /** + * @type int + */ + public $cols = 18; + + /** + * @type int + */ + public $rows = 5; + + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + // this should probably be split up a little + $ret = ''; + $def = $config->def->info["$ns.$directive"]; + if (is_int($def)) { + $type = abs($def); + } else { + $type = $def->type; + } + if (is_array($value)) { + switch ($type) { + case HTMLPurifier_VarParser::LOOKUP: + $array = $value; + $value = array(); + foreach ($array as $val => $b) { + $value[] = $val; + } + //TODO does this need a break? + case HTMLPurifier_VarParser::ALIST: + $value = implode(PHP_EOL, $value); + break; + case HTMLPurifier_VarParser::HASH: + $nvalue = ''; + foreach ($value as $i => $v) { + if (is_array($v)) { + // HACK + $v = implode(";", $v); + } + $nvalue .= "$i:$v" . PHP_EOL; + } + $value = $nvalue; + break; + default: + $value = ''; + } + } + if ($type === HTMLPurifier_VarParser::C_MIXED) { + return 'Not supported'; + $value = serialize($value); + } + $attr = array( + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:$ns.$directive" + ); + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + if (isset($def->allowed)) { + $ret .= $this->start('select', $attr); + foreach ($def->allowed as $val => $b) { + $attr = array(); + if ($value == $val) { + $attr['selected'] = 'selected'; + } + $ret .= $this->element('option', $val, $attr); + } + $ret .= $this->end('select'); + } elseif ($type === HTMLPurifier_VarParser::TEXT || + $type === HTMLPurifier_VarParser::ITEXT || + $type === HTMLPurifier_VarParser::ALIST || + $type === HTMLPurifier_VarParser::HASH || + $type === HTMLPurifier_VarParser::LOOKUP) { + $attr['cols'] = $this->cols; + $attr['rows'] = $this->rows; + $ret .= $this->start('textarea', $attr); + $ret .= $this->text($value); + $ret .= $this->end('textarea'); + } else { + $attr['value'] = $value; + $attr['type'] = 'text'; + $ret .= $this->elementEmpty('input', $attr); + } + return $ret; + } +} + +/** + * Bool form field printer + */ +class HTMLPurifier_Printer_ConfigForm_bool extends HTMLPurifier_Printer +{ + /** + * @param string $ns + * @param string $directive + * @param string $value + * @param string $name + * @param HTMLPurifier_Config|array $config + * @return string + */ + public function render($ns, $directive, $value, $name, $config) + { + if (is_array($config) && isset($config[0])) { + $gen_config = $config[0]; + $config = $config[1]; + } else { + $gen_config = $config; + } + $this->prepareGenerator($gen_config); + $ret = ''; + $ret .= $this->start('div', array('id' => "$name:$ns.$directive")); + + $ret .= $this->start('label', array('for' => "$name:Yes_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' Yes'); + $ret .= $this->end('label'); + + $attr = array( + 'type' => 'radio', + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:Yes_$ns.$directive", + 'value' => '1' + ); + if ($value === true) { + $attr['checked'] = 'checked'; + } + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + $ret .= $this->elementEmpty('input', $attr); + + $ret .= $this->start('label', array('for' => "$name:No_$ns.$directive")); + $ret .= $this->element('span', "$ns.$directive:", array('class' => 'verbose')); + $ret .= $this->text(' No'); + $ret .= $this->end('label'); + + $attr = array( + 'type' => 'radio', + 'name' => "$name" . "[$ns.$directive]", + 'id' => "$name:No_$ns.$directive", + 'value' => '0' + ); + if ($value === false) { + $attr['checked'] = 'checked'; + } + if ($value === null) { + $attr['disabled'] = 'disabled'; + } + $ret .= $this->elementEmpty('input', $attr); + + $ret .= $this->end('div'); + + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/HTMLDefinition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/HTMLDefinition.php new file mode 100644 index 00000000..ae863917 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Printer/HTMLDefinition.php @@ -0,0 +1,324 @@ +config =& $config; + + $this->def = $config->getHTMLDefinition(); + + $ret .= $this->start('div', array('class' => 'HTMLPurifier_Printer')); + + $ret .= $this->renderDoctype(); + $ret .= $this->renderEnvironment(); + $ret .= $this->renderContentSets(); + $ret .= $this->renderInfo(); + + $ret .= $this->end('div'); + + return $ret; + } + + /** + * Renders the Doctype table + * @return string + */ + protected function renderDoctype() + { + $doctype = $this->def->doctype; + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Doctype'); + $ret .= $this->row('Name', $doctype->name); + $ret .= $this->row('XML', $doctype->xml ? 'Yes' : 'No'); + $ret .= $this->row('Default Modules', implode(', ', $doctype->modules)); + $ret .= $this->row('Default Tidy Modules', implode(', ', $doctype->tidyModules)); + $ret .= $this->end('table'); + return $ret; + } + + + /** + * Renders environment table, which is miscellaneous info + * @return string + */ + protected function renderEnvironment() + { + $def = $this->def; + + $ret = ''; + + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Environment'); + + $ret .= $this->row('Parent of fragment', $def->info_parent); + $ret .= $this->renderChildren($def->info_parent_def->child); + $ret .= $this->row('Block wrap name', $def->info_block_wrapper); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Global attributes'); + $ret .= $this->element('td', $this->listifyAttr($def->info_global_attr), null, 0); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Tag transforms'); + $list = array(); + foreach ($def->info_tag_transform as $old => $new) { + $new = $this->getClass($new, 'TagTransform_'); + $list[] = "<$old> with $new"; + } + $ret .= $this->element('td', $this->listify($list)); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Pre-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_pre)); + $ret .= $this->end('tr'); + + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Post-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->info_attr_transform_post)); + $ret .= $this->end('tr'); + + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders the Content Sets table + * @return string + */ + protected function renderContentSets() + { + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Content Sets'); + foreach ($this->def->info_content_sets as $name => $lookup) { + $ret .= $this->heavyHeader($name); + $ret .= $this->start('tr'); + $ret .= $this->element('td', $this->listifyTagLookup($lookup)); + $ret .= $this->end('tr'); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders the Elements ($info) table + * @return string + */ + protected function renderInfo() + { + $ret = ''; + $ret .= $this->start('table'); + $ret .= $this->element('caption', 'Elements ($info)'); + ksort($this->def->info); + $ret .= $this->heavyHeader('Allowed tags', 2); + $ret .= $this->start('tr'); + $ret .= $this->element('td', $this->listifyTagLookup($this->def->info), array('colspan' => 2)); + $ret .= $this->end('tr'); + foreach ($this->def->info as $name => $def) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', "<$name>", array('class' => 'heavy', 'colspan' => 2)); + $ret .= $this->end('tr'); + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Inline content'); + $ret .= $this->element('td', $def->descendants_are_inline ? 'Yes' : 'No'); + $ret .= $this->end('tr'); + if (!empty($def->excludes)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Excludes'); + $ret .= $this->element('td', $this->listifyTagLookup($def->excludes)); + $ret .= $this->end('tr'); + } + if (!empty($def->attr_transform_pre)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Pre-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_pre)); + $ret .= $this->end('tr'); + } + if (!empty($def->attr_transform_post)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Post-AttrTransform'); + $ret .= $this->element('td', $this->listifyObjectList($def->attr_transform_post)); + $ret .= $this->end('tr'); + } + if (!empty($def->auto_close)) { + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Auto closed by'); + $ret .= $this->element('td', $this->listifyTagLookup($def->auto_close)); + $ret .= $this->end('tr'); + } + $ret .= $this->start('tr'); + $ret .= $this->element('th', 'Allowed attributes'); + $ret .= $this->element('td', $this->listifyAttr($def->attr), array(), 0); + $ret .= $this->end('tr'); + + if (!empty($def->required_attr)) { + $ret .= $this->row('Required attributes', $this->listify($def->required_attr)); + } + + $ret .= $this->renderChildren($def->child); + } + $ret .= $this->end('table'); + return $ret; + } + + /** + * Renders a row describing the allowed children of an element + * @param HTMLPurifier_ChildDef $def HTMLPurifier_ChildDef of pertinent element + * @return string + */ + protected function renderChildren($def) + { + $context = new HTMLPurifier_Context(); + $ret = ''; + $ret .= $this->start('tr'); + $elements = array(); + $attr = array(); + if (isset($def->elements)) { + if ($def->type == 'strictblockquote') { + $def->validateChildren(array(), $this->config, $context); + } + $elements = $def->elements; + } + if ($def->type == 'chameleon') { + $attr['rowspan'] = 2; + } elseif ($def->type == 'empty') { + $elements = array(); + } elseif ($def->type == 'table') { + $elements = array_flip( + array( + 'col', + 'caption', + 'colgroup', + 'thead', + 'tfoot', + 'tbody', + 'tr' + ) + ); + } + $ret .= $this->element('th', 'Allowed children', $attr); + + if ($def->type == 'chameleon') { + + $ret .= $this->element( + 'td', + 'Block: ' . + $this->escape($this->listifyTagLookup($def->block->elements)), + null, + 0 + ); + $ret .= $this->end('tr'); + $ret .= $this->start('tr'); + $ret .= $this->element( + 'td', + 'Inline: ' . + $this->escape($this->listifyTagLookup($def->inline->elements)), + null, + 0 + ); + + } elseif ($def->type == 'custom') { + + $ret .= $this->element( + 'td', + '' . ucfirst($def->type) . ': ' . + $def->dtd_regex + ); + + } else { + $ret .= $this->element( + 'td', + '' . ucfirst($def->type) . ': ' . + $this->escape($this->listifyTagLookup($elements)), + null, + 0 + ); + } + $ret .= $this->end('tr'); + return $ret; + } + + /** + * Listifies a tag lookup table. + * @param array $array Tag lookup array in form of array('tagname' => true) + * @return string + */ + protected function listifyTagLookup($array) + { + ksort($array); + $list = array(); + foreach ($array as $name => $discard) { + if ($name !== '#PCDATA' && !isset($this->def->info[$name])) { + continue; + } + $list[] = $name; + } + return $this->listify($list); + } + + /** + * Listifies a list of objects by retrieving class names and internal state + * @param array $array List of objects + * @return string + * @todo Also add information about internal state + */ + protected function listifyObjectList($array) + { + ksort($array); + $list = array(); + foreach ($array as $obj) { + $list[] = $this->getClass($obj, 'AttrTransform_'); + } + return $this->listify($list); + } + + /** + * Listifies a hash of attributes to AttrDef classes + * @param array $array Array hash in form of array('attrname' => HTMLPurifier_AttrDef) + * @return string + */ + protected function listifyAttr($array) + { + ksort($array); + $list = array(); + foreach ($array as $name => $obj) { + if ($obj === false) { + continue; + } + $list[] = "$name = " . $this->getClass($obj, 'AttrDef_') . ''; + } + return $this->listify($list); + } + + /** + * Creates a heavy header row + * @param string $text + * @param int $num + * @return string + */ + protected function heavyHeader($text, $num = 1) + { + $ret = ''; + $ret .= $this->start('tr'); + $ret .= $this->element('th', $text, array('colspan' => $num, 'class' => 'heavy')); + $ret .= $this->end('tr'); + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyList.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyList.php new file mode 100644 index 00000000..189348fd --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyList.php @@ -0,0 +1,122 @@ +parent = $parent; + } + + /** + * Recursively retrieves the value for a key + * @param string $name + * @throws HTMLPurifier_Exception + */ + public function get($name) + { + if ($this->has($name)) { + return $this->data[$name]; + } + // possible performance bottleneck, convert to iterative if necessary + if ($this->parent) { + return $this->parent->get($name); + } + throw new HTMLPurifier_Exception("Key '$name' not found"); + } + + /** + * Sets the value of a key, for this plist + * @param string $name + * @param mixed $value + */ + public function set($name, $value) + { + $this->data[$name] = $value; + } + + /** + * Returns true if a given key exists + * @param string $name + * @return bool + */ + public function has($name) + { + return array_key_exists($name, $this->data); + } + + /** + * Resets a value to the value of it's parent, usually the default. If + * no value is specified, the entire plist is reset. + * @param string $name + */ + public function reset($name = null) + { + if ($name == null) { + $this->data = array(); + } else { + unset($this->data[$name]); + } + } + + /** + * Squashes this property list and all of its property lists into a single + * array, and returns the array. This value is cached by default. + * @param bool $force If true, ignores the cache and regenerates the array. + * @return array + */ + public function squash($force = false) + { + if ($this->cache !== null && !$force) { + return $this->cache; + } + if ($this->parent) { + return $this->cache = array_merge($this->parent->squash($force), $this->data); + } else { + return $this->cache = $this->data; + } + } + + /** + * Returns the parent plist. + * @return HTMLPurifier_PropertyList + */ + public function getParent() + { + return $this->parent; + } + + /** + * Sets the parent plist. + * @param HTMLPurifier_PropertyList $plist Parent plist + */ + public function setParent($plist) + { + $this->parent = $plist; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyListIterator.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyListIterator.php new file mode 100644 index 00000000..15b330ea --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/PropertyListIterator.php @@ -0,0 +1,42 @@ +l = strlen($filter); + $this->filter = $filter; + } + + /** + * @return bool + */ + public function accept() + { + $key = $this->getInnerIterator()->key(); + if (strncmp($key, $this->filter, $this->l) !== 0) { + return false; + } + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Queue.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Queue.php new file mode 100644 index 00000000..f58db904 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Queue.php @@ -0,0 +1,56 @@ +input = $input; + $this->output = array(); + } + + /** + * Shifts an element off the front of the queue. + */ + public function shift() { + if (empty($this->output)) { + $this->output = array_reverse($this->input); + $this->input = array(); + } + if (empty($this->output)) { + return NULL; + } + return array_pop($this->output); + } + + /** + * Pushes an element onto the front of the queue. + */ + public function push($x) { + array_push($this->input, $x); + } + + /** + * Checks if it's empty. + */ + public function isEmpty() { + return empty($this->input) && empty($this->output); + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy.php new file mode 100644 index 00000000..e1ff3b72 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy.php @@ -0,0 +1,26 @@ +strategies as $strategy) { + $tokens = $strategy->execute($tokens, $config, $context); + } + return $tokens; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/Core.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/Core.php new file mode 100644 index 00000000..4414c17d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/Core.php @@ -0,0 +1,17 @@ +strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements(); + $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed(); + $this->strategies[] = new HTMLPurifier_Strategy_FixNesting(); + $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/FixNesting.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/FixNesting.php new file mode 100644 index 00000000..6fa673db --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/FixNesting.php @@ -0,0 +1,181 @@ +getHTMLDefinition(); + + $excludes_enabled = !$config->get('Core.DisableExcludes'); + + // setup the context variable 'IsInline', for chameleon processing + // is 'false' when we are not inline, 'true' when it must always + // be inline, and an integer when it is inline for a certain + // branch of the document tree + $is_inline = $definition->info_parent_def->descendants_are_inline; + $context->register('IsInline', $is_inline); + + // setup error collector + $e =& $context->get('ErrorCollector', true); + + //####################################################################// + // Loop initialization + + // stack that contains all elements that are excluded + // it is organized by parent elements, similar to $stack, + // but it is only populated when an element with exclusions is + // processed, i.e. there won't be empty exclusions. + $exclude_stack = array($definition->info_parent_def->excludes); + + // variable that contains the start token while we are processing + // nodes. This enables error reporting to do its job + $node = $top_node; + // dummy token + list($token, $d) = $node->toTokenPair(); + $context->register('CurrentNode', $node); + $context->register('CurrentToken', $token); + + //####################################################################// + // Loop + + // We need to implement a post-order traversal iteratively, to + // avoid running into stack space limits. This is pretty tricky + // to reason about, so we just manually stack-ify the recursive + // variant: + // + // function f($node) { + // foreach ($node->children as $child) { + // f($child); + // } + // validate($node); + // } + // + // Thus, we will represent a stack frame as array($node, + // $is_inline, stack of children) + // e.g. array_reverse($node->children) - already processed + // children. + + $parent_def = $definition->info_parent_def; + $stack = array( + array($top_node, + $parent_def->descendants_are_inline, + $parent_def->excludes, // exclusions + 0) + ); + + while (!empty($stack)) { + list($node, $is_inline, $excludes, $ix) = array_pop($stack); + // recursive call + $go = false; + $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name]; + while (isset($node->children[$ix])) { + $child = $node->children[$ix++]; + if ($child instanceof HTMLPurifier_Node_Element) { + $go = true; + $stack[] = array($node, $is_inline, $excludes, $ix); + $stack[] = array($child, + // ToDo: I don't think it matters if it's def or + // child_def, but double check this... + $is_inline || $def->descendants_are_inline, + empty($def->excludes) ? $excludes + : array_merge($excludes, $def->excludes), + 0); + break; + } + }; + if ($go) continue; + list($token, $d) = $node->toTokenPair(); + // base case + if ($excludes_enabled && isset($excludes[$node->name])) { + $node->dead = true; + if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded'); + } else { + // XXX I suppose it would be slightly more efficient to + // avoid the allocation here and have children + // strategies handle it + $children = array(); + foreach ($node->children as $child) { + if (!$child->dead) $children[] = $child; + } + $result = $def->child->validateChildren($children, $config, $context); + if ($result === true) { + // nop + $node->children = $children; + } elseif ($result === false) { + $node->dead = true; + if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed'); + } else { + $node->children = $result; + if ($e) { + // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators + if (empty($result) && !empty($children)) { + $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed'); + } else if ($result != $children) { + $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized'); + } + } + } + } + } + + //####################################################################// + // Post-processing + + // remove context variables + $context->destroy('IsInline'); + $context->destroy('CurrentNode'); + $context->destroy('CurrentToken'); + + //####################################################################// + // Return + + return HTMLPurifier_Arborize::flatten($node, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/MakeWellFormed.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/MakeWellFormed.php new file mode 100644 index 00000000..a6eb09e4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/MakeWellFormed.php @@ -0,0 +1,659 @@ +getHTMLDefinition(); + + // local variables + $generator = new HTMLPurifier_Generator($config, $context); + $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); + // used for autoclose early abortion + $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config); + $e = $context->get('ErrorCollector', true); + $i = false; // injector index + list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens); + if ($token === NULL) { + return array(); + } + $reprocess = false; // whether or not to reprocess the same token + $stack = array(); + + // member variables + $this->stack =& $stack; + $this->tokens =& $tokens; + $this->token =& $token; + $this->zipper =& $zipper; + $this->config = $config; + $this->context = $context; + + // context variables + $context->register('CurrentNesting', $stack); + $context->register('InputZipper', $zipper); + $context->register('CurrentToken', $token); + + // -- begin INJECTOR -- + + $this->injectors = array(); + + $injectors = $config->getBatch('AutoFormat'); + $def_injectors = $definition->info_injector; + $custom_injectors = $injectors['Custom']; + unset($injectors['Custom']); // special case + foreach ($injectors as $injector => $b) { + // XXX: Fix with a legitimate lookup table of enabled filters + if (strpos($injector, '.') !== false) { + continue; + } + $injector = "HTMLPurifier_Injector_$injector"; + if (!$b) { + continue; + } + $this->injectors[] = new $injector; + } + foreach ($def_injectors as $injector) { + // assumed to be objects + $this->injectors[] = $injector; + } + foreach ($custom_injectors as $injector) { + if (!$injector) { + continue; + } + if (is_string($injector)) { + $injector = "HTMLPurifier_Injector_$injector"; + $injector = new $injector; + } + $this->injectors[] = $injector; + } + + // give the injectors references to the definition and context + // variables for performance reasons + foreach ($this->injectors as $ix => $injector) { + $error = $injector->prepare($config, $context); + if (!$error) { + continue; + } + array_splice($this->injectors, $ix, 1); // rm the injector + trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING); + } + + // -- end INJECTOR -- + + // a note on reprocessing: + // In order to reduce code duplication, whenever some code needs + // to make HTML changes in order to make things "correct", the + // new HTML gets sent through the purifier, regardless of its + // status. This means that if we add a start token, because it + // was totally necessary, we don't have to update nesting; we just + // punt ($reprocess = true; continue;) and it does that for us. + + // isset is in loop because $tokens size changes during loop exec + for (;; + // only increment if we don't need to reprocess + $reprocess ? $reprocess = false : $token = $zipper->next($token)) { + + // check for a rewind + if (is_int($i)) { + // possibility: disable rewinding if the current token has a + // rewind set on it already. This would offer protection from + // infinite loop, but might hinder some advanced rewinding. + $rewind_offset = $this->injectors[$i]->getRewindOffset(); + if (is_int($rewind_offset)) { + for ($j = 0; $j < $rewind_offset; $j++) { + if (empty($zipper->front)) break; + $token = $zipper->prev($token); + // indicate that other injectors should not process this token, + // but we need to reprocess it. See Note [Injector skips] + unset($token->skip[$i]); + $token->rewind = $i; + if ($token instanceof HTMLPurifier_Token_Start) { + array_pop($this->stack); + } elseif ($token instanceof HTMLPurifier_Token_End) { + $this->stack[] = $token->start; + } + } + } + $i = false; + } + + // handle case of document end + if ($token === NULL) { + // kill processing if stack is empty + if (empty($this->stack)) { + break; + } + + // peek + $top_nesting = array_pop($this->stack); + $this->stack[] = $top_nesting; + + // send error [TagClosedSuppress] + if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting); + } + + // append, don't splice, since this is the end + $token = new HTMLPurifier_Token_End($top_nesting->name); + + // punt! + $reprocess = true; + continue; + } + + //echo '
    '; printZipper($zipper, $token);//printTokens($this->stack); + //flush(); + + // quick-check: if it's not a tag, no need to process + if (empty($token->is_tag)) { + if ($token instanceof HTMLPurifier_Token_Text) { + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + // XXX fuckup + $r = $token; + $injector->handleText($r); + $token = $this->processToken($r, $i); + $reprocess = true; + break; + } + } + // another possibility is a comment + continue; + } + + if (isset($definition->info[$token->name])) { + $type = $definition->info[$token->name]->child->type; + } else { + $type = false; // Type is unknown, treat accordingly + } + + // quick tag checks: anything that's *not* an end tag + $ok = false; + if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) { + // claims to be a start tag but is empty + $token = new HTMLPurifier_Token_Empty( + $token->name, + $token->attr, + $token->line, + $token->col, + $token->armor + ); + $ok = true; + } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) { + // claims to be empty but really is a start tag + // NB: this assignment is required + $old_token = $token; + $token = new HTMLPurifier_Token_End($token->name); + $token = $this->insertBefore( + new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor) + ); + // punt (since we had to modify the input stream in a non-trivial way) + $reprocess = true; + continue; + } elseif ($token instanceof HTMLPurifier_Token_Empty) { + // real empty token + $ok = true; + } elseif ($token instanceof HTMLPurifier_Token_Start) { + // start tag + + // ...unless they also have to close their parent + if (!empty($this->stack)) { + + // Performance note: you might think that it's rather + // inefficient, recalculating the autoclose information + // for every tag that a token closes (since when we + // do an autoclose, we push a new token into the + // stream and then /process/ that, before + // re-processing this token.) But this is + // necessary, because an injector can make an + // arbitrary transformations to the autoclosing + // tokens we introduce, so things may have changed + // in the meantime. Also, doing the inefficient thing is + // "easy" to reason about (for certain perverse definitions + // of "easy") + + $parent = array_pop($this->stack); + $this->stack[] = $parent; + + $parent_def = null; + $parent_elements = null; + $autoclose = false; + if (isset($definition->info[$parent->name])) { + $parent_def = $definition->info[$parent->name]; + $parent_elements = $parent_def->child->getAllowedElements($config); + $autoclose = !isset($parent_elements[$token->name]); + } + + if ($autoclose && $definition->info[$token->name]->wrap) { + // Check if an element can be wrapped by another + // element to make it valid in a context (for + // example,
        needs a
      • in between) + $wrapname = $definition->info[$token->name]->wrap; + $wrapdef = $definition->info[$wrapname]; + $elements = $wrapdef->child->getAllowedElements($config); + if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) { + $newtoken = new HTMLPurifier_Token_Start($wrapname); + $token = $this->insertBefore($newtoken); + $reprocess = true; + continue; + } + } + + $carryover = false; + if ($autoclose && $parent_def->formatting) { + $carryover = true; + } + + if ($autoclose) { + // check if this autoclose is doomed to fail + // (this rechecks $parent, which his harmless) + $autoclose_ok = isset($global_parent_allowed_elements[$token->name]); + if (!$autoclose_ok) { + foreach ($this->stack as $ancestor) { + $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config); + if (isset($elements[$token->name])) { + $autoclose_ok = true; + break; + } + if ($definition->info[$token->name]->wrap) { + $wrapname = $definition->info[$token->name]->wrap; + $wrapdef = $definition->info[$wrapname]; + $wrap_elements = $wrapdef->child->getAllowedElements($config); + if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) { + $autoclose_ok = true; + break; + } + } + } + } + if ($autoclose_ok) { + // errors need to be updated + $new_token = new HTMLPurifier_Token_End($parent->name); + $new_token->start = $parent; + // [TagClosedSuppress] + if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) { + if (!$carryover) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent); + } else { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent); + } + } + if ($carryover) { + $element = clone $parent; + // [TagClosedAuto] + $element->armor['MakeWellFormed_TagClosedError'] = true; + $element->carryover = true; + $token = $this->processToken(array($new_token, $token, $element)); + } else { + $token = $this->insertBefore($new_token); + } + } else { + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + } + $ok = true; + } + + if ($ok) { + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + $r = $token; + $injector->handleElement($r); + $token = $this->processToken($r, $i); + $reprocess = true; + break; + } + if (!$reprocess) { + // ah, nothing interesting happened; do normal processing + if ($token instanceof HTMLPurifier_Token_Start) { + $this->stack[] = $token; + } elseif ($token instanceof HTMLPurifier_Token_End) { + throw new HTMLPurifier_Exception( + 'Improper handling of end tag in start code; possible error in MakeWellFormed' + ); + } + } + continue; + } + + // sanity check: we should be dealing with a closing tag + if (!$token instanceof HTMLPurifier_Token_End) { + throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier'); + } + + // make sure that we have something open + if (empty($this->stack)) { + if ($escape_invalid_tags) { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text'); + } + $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); + } else { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed'); + } + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + // first, check for the simplest case: everything closes neatly. + // Eventually, everything passes through here; if there are problems + // we modify the input stream accordingly and then punt, so that + // the tokens get processed again. + $current_parent = array_pop($this->stack); + if ($current_parent->name == $token->name) { + $token->start = $current_parent; + foreach ($this->injectors as $i => $injector) { + if (isset($token->skip[$i])) { + // See Note [Injector skips] + continue; + } + if ($token->rewind !== null && $token->rewind !== $i) { + continue; + } + $r = $token; + $injector->handleEnd($r); + $token = $this->processToken($r, $i); + $this->stack[] = $current_parent; + $reprocess = true; + break; + } + continue; + } + + // okay, so we're trying to close the wrong tag + + // undo the pop previous pop + $this->stack[] = $current_parent; + + // scroll back the entire nest, trying to find our tag. + // (feature could be to specify how far you'd like to go) + $size = count($this->stack); + // -2 because -1 is the last element, but we already checked that + $skipped_tags = false; + for ($j = $size - 2; $j >= 0; $j--) { + if ($this->stack[$j]->name == $token->name) { + $skipped_tags = array_slice($this->stack, $j); + break; + } + } + + // we didn't find the tag, so remove + if ($skipped_tags === false) { + if ($escape_invalid_tags) { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text'); + } + $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); + } else { + if ($e) { + $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed'); + } + $token = $this->remove(); + } + $reprocess = true; + continue; + } + + // do errors, in REVERSE $j order: a,b,c with + $c = count($skipped_tags); + if ($e) { + for ($j = $c - 1; $j > 0; $j--) { + // notice we exclude $j == 0, i.e. the current ending tag, from + // the errors... [TagClosedSuppress] + if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) { + $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]); + } + } + } + + // insert tags, in FORWARD $j order: c,b,a with + $replace = array($token); + for ($j = 1; $j < $c; $j++) { + // ...as well as from the insertions + $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name); + $new_token->start = $skipped_tags[$j]; + array_unshift($replace, $new_token); + if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) { + // [TagClosedAuto] + $element = clone $skipped_tags[$j]; + $element->carryover = true; + $element->armor['MakeWellFormed_TagClosedError'] = true; + $replace[] = $element; + } + } + $token = $this->processToken($replace); + $reprocess = true; + continue; + } + + $context->destroy('CurrentToken'); + $context->destroy('CurrentNesting'); + $context->destroy('InputZipper'); + + unset($this->injectors, $this->stack, $this->tokens); + return $zipper->toArray($token); + } + + /** + * Processes arbitrary token values for complicated substitution patterns. + * In general: + * + * If $token is an array, it is a list of tokens to substitute for the + * current token. These tokens then get individually processed. If there + * is a leading integer in the list, that integer determines how many + * tokens from the stream should be removed. + * + * If $token is a regular token, it is swapped with the current token. + * + * If $token is false, the current token is deleted. + * + * If $token is an integer, that number of tokens (with the first token + * being the current one) will be deleted. + * + * @param HTMLPurifier_Token|array|int|bool $token Token substitution value + * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if + * this is not an injector related operation. + * @throws HTMLPurifier_Exception + */ + protected function processToken($token, $injector = -1) + { + // Zend OpCache miscompiles $token = array($token), so + // avoid this pattern. See: https://github.com/ezyang/htmlpurifier/issues/108 + + // normalize forms of token + if (is_object($token)) { + $tmp = $token; + $token = array(1, $tmp); + } + if (is_int($token)) { + $tmp = $token; + $token = array($tmp); + } + if ($token === false) { + $token = array(1); + } + if (!is_array($token)) { + throw new HTMLPurifier_Exception('Invalid token type from injector'); + } + if (!is_int($token[0])) { + array_unshift($token, 1); + } + if ($token[0] === 0) { + throw new HTMLPurifier_Exception('Deleting zero tokens is not valid'); + } + + // $token is now an array with the following form: + // array(number nodes to delete, new node 1, new node 2, ...) + + $delete = array_shift($token); + list($old, $r) = $this->zipper->splice($this->token, $delete, $token); + + if ($injector > -1) { + // See Note [Injector skips] + // Determine appropriate skips. Here's what the code does: + // *If* we deleted one or more tokens, copy the skips + // of those tokens into the skips of the new tokens (in $token). + // Also, mark the newly inserted tokens as having come from + // $injector. + $oldskip = isset($old[0]) ? $old[0]->skip : array(); + foreach ($token as $object) { + $object->skip = $oldskip; + $object->skip[$injector] = true; + } + } + + return $r; + + } + + /** + * Inserts a token before the current token. Cursor now points to + * this token. You must reprocess after this. + * @param HTMLPurifier_Token $token + */ + private function insertBefore($token) + { + // NB not $this->zipper->insertBefore(), due to positioning + // differences + $splice = $this->zipper->splice($this->token, 0, array($token)); + + return $splice[1]; + } + + /** + * Removes current token. Cursor now points to new token occupying previously + * occupied space. You must reprocess after this. + */ + private function remove() + { + return $this->zipper->delete(); + } +} + +// Note [Injector skips] +// ~~~~~~~~~~~~~~~~~~~~~ +// When I originally designed this class, the idea behind the 'skip' +// property of HTMLPurifier_Token was to help avoid infinite loops +// in injector processing. For example, suppose you wrote an injector +// that bolded swear words. Naively, you might write it so that +// whenever you saw ****, you replaced it with ****. +// +// When this happens, we will reprocess all of the tokens with the +// other injectors. Now there is an opportunity for infinite loop: +// if we rerun the swear-word injector on these tokens, we might +// see **** and then reprocess again to get +// **** ad infinitum. +// +// Thus, the idea of a skip is that once we process a token with +// an injector, we mark all of those tokens as having "come from" +// the injector, and we never run the injector again on these +// tokens. +// +// There were two more complications, however: +// +// - With HTMLPurifier_Injector_RemoveEmpty, we noticed that if +// you had , after you removed the , you +// really would like this injector to go back and reprocess +// the tag, discovering that it is now empty and can be +// removed. So we reintroduced the possibility of infinite looping +// by adding a "rewind" function, which let you go back to an +// earlier point in the token stream and reprocess it with injectors. +// Needless to say, we need to UN-skip the token so it gets +// reprocessed. +// +// - Suppose that you successfuly process a token, replace it with +// one with your skip mark, but now another injector wants to +// process the skipped token with another token. Should you continue +// to skip that new token, or reprocess it? If you reprocess, +// you can end up with an infinite loop where one injector converts +// to , and then another injector converts it back. So +// we inherit the skips, but for some reason, I thought that we +// should inherit the skip from the first token of the token +// that we deleted. Why? Well, it seems to work OK. +// +// If I were to redesign this functionality, I would absolutely not +// go about doing it this way: the semantics are just not very well +// defined, and in any case you probably wanted to operate on trees, +// not token streams. + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/RemoveForeignElements.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/RemoveForeignElements.php new file mode 100644 index 00000000..1a8149ec --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/RemoveForeignElements.php @@ -0,0 +1,207 @@ +getHTMLDefinition(); + $generator = new HTMLPurifier_Generator($config, $context); + $result = array(); + + $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); + $remove_invalid_img = $config->get('Core.RemoveInvalidImg'); + + // currently only used to determine if comments should be kept + $trusted = $config->get('HTML.Trusted'); + $comment_lookup = $config->get('HTML.AllowedComments'); + $comment_regexp = $config->get('HTML.AllowedCommentsRegexp'); + $check_comments = $comment_lookup !== array() || $comment_regexp !== null; + + $remove_script_contents = $config->get('Core.RemoveScriptContents'); + $hidden_elements = $config->get('Core.HiddenElements'); + + // remove script contents compatibility + if ($remove_script_contents === true) { + $hidden_elements['script'] = true; + } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) { + unset($hidden_elements['script']); + } + + $attr_validator = new HTMLPurifier_AttrValidator(); + + // removes tokens until it reaches a closing tag with its value + $remove_until = false; + + // converts comments into text tokens when this is equal to a tag name + $textify_comments = false; + + $token = false; + $context->register('CurrentToken', $token); + + $e = false; + if ($config->get('Core.CollectErrors')) { + $e =& $context->get('ErrorCollector'); + } + + foreach ($tokens as $token) { + if ($remove_until) { + if (empty($token->is_tag) || $token->name !== $remove_until) { + continue; + } + } + if (!empty($token->is_tag)) { + // DEFINITION CALL + + // before any processing, try to transform the element + if (isset($definition->info_tag_transform[$token->name])) { + $original_name = $token->name; + // there is a transformation for this tag + // DEFINITION CALL + $token = $definition-> + info_tag_transform[$token->name]->transform($token, $config, $context); + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name); + } + } + + if (isset($definition->info[$token->name])) { + // mostly everything's good, but + // we need to make sure required attributes are in order + if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) && + $definition->info[$token->name]->required_attr && + ($token->name != 'img' || $remove_invalid_img) // ensure config option still works + ) { + $attr_validator->validateToken($token, $config, $context); + $ok = true; + foreach ($definition->info[$token->name]->required_attr as $name) { + if (!isset($token->attr[$name])) { + $ok = false; + break; + } + } + if (!$ok) { + if ($e) { + $e->send( + E_ERROR, + 'Strategy_RemoveForeignElements: Missing required attribute', + $name + ); + } + continue; + } + $token->armor['ValidateAttributes'] = true; + } + + if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) { + $textify_comments = $token->name; + } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) { + $textify_comments = false; + } + + } elseif ($escape_invalid_tags) { + // invalid tag, generate HTML representation and insert in + if ($e) { + $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text'); + } + $token = new HTMLPurifier_Token_Text( + $generator->generateFromToken($token) + ); + } else { + // check if we need to destroy all of the tag's children + // CAN BE GENERICIZED + if (isset($hidden_elements[$token->name])) { + if ($token instanceof HTMLPurifier_Token_Start) { + $remove_until = $token->name; + } elseif ($token instanceof HTMLPurifier_Token_Empty) { + // do nothing: we're still looking + } else { + $remove_until = false; + } + if ($e) { + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed'); + } + } else { + if ($e) { + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed'); + } + } + continue; + } + } elseif ($token instanceof HTMLPurifier_Token_Comment) { + // textify comments in script tags when they are allowed + if ($textify_comments !== false) { + $data = $token->data; + $token = new HTMLPurifier_Token_Text($data); + } elseif ($trusted || $check_comments) { + // always cleanup comments + $trailing_hyphen = false; + if ($e) { + // perform check whether or not there's a trailing hyphen + if (substr($token->data, -1) == '-') { + $trailing_hyphen = true; + } + } + $token->data = rtrim($token->data, '-'); + $found_double_hyphen = false; + while (strpos($token->data, '--') !== false) { + $found_double_hyphen = true; + $token->data = str_replace('--', '-', $token->data); + } + if ($trusted || !empty($comment_lookup[trim($token->data)]) || + ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) { + // OK good + if ($e) { + if ($trailing_hyphen) { + $e->send( + E_NOTICE, + 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed' + ); + } + if ($found_double_hyphen) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed'); + } + } + } else { + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); + } + continue; + } + } else { + // strip comments + if ($e) { + $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed'); + } + continue; + } + } elseif ($token instanceof HTMLPurifier_Token_Text) { + } else { + continue; + } + $result[] = $token; + } + if ($remove_until && $e) { + // we removed tokens until the end, throw error + $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until); + } + $context->destroy('CurrentToken'); + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/ValidateAttributes.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/ValidateAttributes.php new file mode 100644 index 00000000..fbb3d27c --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Strategy/ValidateAttributes.php @@ -0,0 +1,45 @@ +register('CurrentToken', $token); + + foreach ($tokens as $key => $token) { + + // only process tokens that have attributes, + // namely start and empty tags + if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) { + continue; + } + + // skip tokens that are armored + if (!empty($token->armor['ValidateAttributes'])) { + continue; + } + + // note that we have no facilities here for removing tokens + $validator->validateToken($token, $config, $context); + } + $context->destroy('CurrentToken'); + return $tokens; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHash.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHash.php new file mode 100644 index 00000000..c0737019 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHash.php @@ -0,0 +1,47 @@ +accessed[$index] = true; + return parent::offsetGet($index); + } + + /** + * Returns a lookup array of all array indexes that have been accessed. + * @return array in form array($index => true). + */ + public function getAccessed() + { + return $this->accessed; + } + + /** + * Resets the access array. + */ + public function resetAccessed() + { + $this->accessed = array(); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHashParser.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHashParser.php new file mode 100644 index 00000000..7c73f808 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/StringHashParser.php @@ -0,0 +1,136 @@ + 'DefaultKeyValue', + * 'KEY' => 'Value', + * 'KEY2' => 'Value2', + * 'MULTILINE-KEY' => "Multiline\nvalue.\n", + * ) + * + * We use this as an easy to use file-format for configuration schema + * files, but the class itself is usage agnostic. + * + * You can use ---- to forcibly terminate parsing of a single string-hash; + * this marker is used in multi string-hashes to delimit boundaries. + */ +class HTMLPurifier_StringHashParser +{ + + /** + * @type string + */ + public $default = 'ID'; + + /** + * Parses a file that contains a single string-hash. + * @param string $file + * @return array + */ + public function parseFile($file) + { + if (!file_exists($file)) { + return false; + } + $fh = fopen($file, 'r'); + if (!$fh) { + return false; + } + $ret = $this->parseHandle($fh); + fclose($fh); + return $ret; + } + + /** + * Parses a file that contains multiple string-hashes delimited by '----' + * @param string $file + * @return array + */ + public function parseMultiFile($file) + { + if (!file_exists($file)) { + return false; + } + $ret = array(); + $fh = fopen($file, 'r'); + if (!$fh) { + return false; + } + while (!feof($fh)) { + $ret[] = $this->parseHandle($fh); + } + fclose($fh); + return $ret; + } + + /** + * Internal parser that acepts a file handle. + * @note While it's possible to simulate in-memory parsing by using + * custom stream wrappers, if such a use-case arises we should + * factor out the file handle into its own class. + * @param resource $fh File handle with pointer at start of valid string-hash + * block. + * @return array + */ + protected function parseHandle($fh) + { + $state = false; + $single = false; + $ret = array(); + do { + $line = fgets($fh); + if ($line === false) { + break; + } + $line = rtrim($line, "\n\r"); + if (!$state && $line === '') { + continue; + } + if ($line === '----') { + break; + } + if (strncmp('--#', $line, 3) === 0) { + // Comment + continue; + } elseif (strncmp('--', $line, 2) === 0) { + // Multiline declaration + $state = trim($line, '- '); + if (!isset($ret[$state])) { + $ret[$state] = ''; + } + continue; + } elseif (!$state) { + $single = true; + if (strpos($line, ':') !== false) { + // Single-line declaration + list($state, $line) = explode(':', $line, 2); + $line = trim($line); + } else { + // Use default declaration + $state = $this->default; + } + } + if ($single) { + $ret[$state] = $line; + $single = false; + $state = false; + } else { + $ret[$state] .= "$line\n"; + } + } while (!feof($fh)); + return $ret; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform.php new file mode 100644 index 00000000..7b8d8334 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform.php @@ -0,0 +1,37 @@ + 'xx-small', + '1' => 'xx-small', + '2' => 'small', + '3' => 'medium', + '4' => 'large', + '5' => 'x-large', + '6' => 'xx-large', + '7' => '300%', + '-1' => 'smaller', + '-2' => '60%', + '+1' => 'larger', + '+2' => '150%', + '+3' => '200%', + '+4' => '300%' + ); + + /** + * @param HTMLPurifier_Token_Tag $tag + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_Token_End|string + */ + public function transform($tag, $config, $context) + { + if ($tag instanceof HTMLPurifier_Token_End) { + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + return $new_tag; + } + + $attr = $tag->attr; + $prepend_style = ''; + + // handle color transform + if (isset($attr['color'])) { + $prepend_style .= 'color:' . $attr['color'] . ';'; + unset($attr['color']); + } + + // handle face transform + if (isset($attr['face'])) { + $prepend_style .= 'font-family:' . $attr['face'] . ';'; + unset($attr['face']); + } + + // handle size transform + if (isset($attr['size'])) { + // normalize large numbers + if ($attr['size'] !== '') { + if ($attr['size'][0] == '+' || $attr['size'][0] == '-') { + $size = (int)$attr['size']; + if ($size < -2) { + $attr['size'] = '-2'; + } + if ($size > 4) { + $attr['size'] = '+4'; + } + } else { + $size = (int)$attr['size']; + if ($size > 7) { + $attr['size'] = '7'; + } + } + } + if (isset($this->_size_lookup[$attr['size']])) { + $prepend_style .= 'font-size:' . + $this->_size_lookup[$attr['size']] . ';'; + } + unset($attr['size']); + } + + if ($prepend_style) { + $attr['style'] = isset($attr['style']) ? + $prepend_style . $attr['style'] : + $prepend_style; + } + + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + $new_tag->attr = $attr; + + return $new_tag; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform/Simple.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform/Simple.php new file mode 100644 index 00000000..71bf10b9 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TagTransform/Simple.php @@ -0,0 +1,44 @@ +transform_to = $transform_to; + $this->style = $style; + } + + /** + * @param HTMLPurifier_Token_Tag $tag + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return string + */ + public function transform($tag, $config, $context) + { + $new_tag = clone $tag; + $new_tag->name = $this->transform_to; + if (!is_null($this->style) && + ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty) + ) { + $this->prependCSS($new_tag->attr, $this->style); + } + return $new_tag; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token.php new file mode 100644 index 00000000..84d3619a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token.php @@ -0,0 +1,100 @@ +line = $l; + $this->col = $c; + } + + /** + * Convenience function for DirectLex settings line/col position. + * @param int $l + * @param int $c + */ + public function rawPosition($l, $c) + { + if ($c === -1) { + $l++; + } + $this->line = $l; + $this->col = $c; + } + + /** + * Converts a token into its corresponding node. + */ + abstract public function toNode(); +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Comment.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Comment.php new file mode 100644 index 00000000..23453c70 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Comment.php @@ -0,0 +1,38 @@ +data = $data; + $this->line = $line; + $this->col = $col; + } + + public function toNode() { + return new HTMLPurifier_Node_Comment($this->data, $this->line, $this->col); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Empty.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Empty.php new file mode 100644 index 00000000..78a95f55 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Empty.php @@ -0,0 +1,15 @@ +empty = true; + return $n; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/End.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/End.php new file mode 100644 index 00000000..59b38fdc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/End.php @@ -0,0 +1,24 @@ +toNode not supported!"); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Start.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Start.php new file mode 100644 index 00000000..019f317a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Start.php @@ -0,0 +1,10 @@ +!empty($obj->is_tag) + * without having to use a function call is_a(). + * @type bool + */ + public $is_tag = true; + + /** + * The lower-case name of the tag, like 'a', 'b' or 'blockquote'. + * + * @note Strictly speaking, XML tags are case sensitive, so we shouldn't + * be lower-casing them, but these tokens cater to HTML tags, which are + * insensitive. + * @type string + */ + public $name; + + /** + * Associative array of the tag's attributes. + * @type array + */ + public $attr = array(); + + /** + * Non-overloaded constructor, which lower-cases passed tag name. + * + * @param string $name String name. + * @param array $attr Associative array of attributes. + * @param int $line + * @param int $col + * @param array $armor + */ + public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) + { + $this->name = ctype_lower($name) ? $name : strtolower($name); + foreach ($attr as $key => $value) { + // normalization only necessary when key is not lowercase + if (!ctype_lower($key)) { + $new_key = strtolower($key); + if (!isset($attr[$new_key])) { + $attr[$new_key] = $attr[$key]; + } + if ($new_key !== $key) { + unset($attr[$key]); + } + } + } + $this->attr = $attr; + $this->line = $line; + $this->col = $col; + $this->armor = $armor; + } + + public function toNode() { + return new HTMLPurifier_Node_Element($this->name, $this->attr, $this->line, $this->col, $this->armor); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Text.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Text.php new file mode 100644 index 00000000..f26a1c21 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/Token/Text.php @@ -0,0 +1,53 @@ +data = $data; + $this->is_whitespace = ctype_space($data); + $this->line = $line; + $this->col = $col; + } + + public function toNode() { + return new HTMLPurifier_Node_Text($this->data, $this->is_whitespace, $this->line, $this->col); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/TokenFactory.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TokenFactory.php new file mode 100644 index 00000000..dea2446b --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/TokenFactory.php @@ -0,0 +1,118 @@ +p_start = new HTMLPurifier_Token_Start('', array()); + $this->p_end = new HTMLPurifier_Token_End(''); + $this->p_empty = new HTMLPurifier_Token_Empty('', array()); + $this->p_text = new HTMLPurifier_Token_Text(''); + $this->p_comment = new HTMLPurifier_Token_Comment(''); + } + + /** + * Creates a HTMLPurifier_Token_Start. + * @param string $name Tag name + * @param array $attr Associative array of attributes + * @return HTMLPurifier_Token_Start Generated HTMLPurifier_Token_Start + */ + public function createStart($name, $attr = array()) + { + $p = clone $this->p_start; + $p->__construct($name, $attr); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_End. + * @param string $name Tag name + * @return HTMLPurifier_Token_End Generated HTMLPurifier_Token_End + */ + public function createEnd($name) + { + $p = clone $this->p_end; + $p->__construct($name); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Empty. + * @param string $name Tag name + * @param array $attr Associative array of attributes + * @return HTMLPurifier_Token_Empty Generated HTMLPurifier_Token_Empty + */ + public function createEmpty($name, $attr = array()) + { + $p = clone $this->p_empty; + $p->__construct($name, $attr); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Text. + * @param string $data Data of text token + * @return HTMLPurifier_Token_Text Generated HTMLPurifier_Token_Text + */ + public function createText($data) + { + $p = clone $this->p_text; + $p->__construct($data); + return $p; + } + + /** + * Creates a HTMLPurifier_Token_Comment. + * @param string $data Data of comment token + * @return HTMLPurifier_Token_Comment Generated HTMLPurifier_Token_Comment + */ + public function createComment($data) + { + $p = clone $this->p_comment; + $p->__construct($data); + return $p; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URI.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URI.php new file mode 100644 index 00000000..9c5be39d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URI.php @@ -0,0 +1,316 @@ +scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme); + $this->userinfo = $userinfo; + $this->host = $host; + $this->port = is_null($port) ? $port : (int)$port; + $this->path = $path; + $this->query = $query; + $this->fragment = $fragment; + } + + /** + * Retrieves a scheme object corresponding to the URI's scheme/default + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return HTMLPurifier_URIScheme Scheme object appropriate for validating this URI + */ + public function getSchemeObj($config, $context) + { + $registry = HTMLPurifier_URISchemeRegistry::instance(); + if ($this->scheme !== null) { + $scheme_obj = $registry->getScheme($this->scheme, $config, $context); + if (!$scheme_obj) { + return false; + } // invalid scheme, clean it out + } else { + // no scheme: retrieve the default one + $def = $config->getDefinition('URI'); + $scheme_obj = $def->getDefaultScheme($config, $context); + if (!$scheme_obj) { + if ($def->defaultScheme !== null) { + // something funky happened to the default scheme object + trigger_error( + 'Default scheme object "' . $def->defaultScheme . '" was not readable', + E_USER_WARNING + ); + } // suppress error if it's null + return false; + } + } + return $scheme_obj; + } + + /** + * Generic validation method applicable for all schemes. May modify + * this URI in order to get it into a compliant form. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool True if validation/filtering succeeds, false if failure + */ + public function validate($config, $context) + { + // ABNF definitions from RFC 3986 + $chars_sub_delims = '!$&\'()*+,;='; + $chars_gen_delims = ':/?#[]@'; + $chars_pchar = $chars_sub_delims . ':@'; + + // validate host + if (!is_null($this->host)) { + $host_def = new HTMLPurifier_AttrDef_URI_Host(); + $this->host = $host_def->validate($this->host, $config, $context); + if ($this->host === false) { + $this->host = null; + } + } + + // validate scheme + // NOTE: It's not appropriate to check whether or not this + // scheme is in our registry, since a URIFilter may convert a + // URI that we don't allow into one we do. So instead, we just + // check if the scheme can be dropped because there is no host + // and it is our default scheme. + if (!is_null($this->scheme) && is_null($this->host) || $this->host === '') { + // support for relative paths is pretty abysmal when the + // scheme is present, so axe it when possible + $def = $config->getDefinition('URI'); + if ($def->defaultScheme === $this->scheme) { + $this->scheme = null; + } + } + + // validate username + if (!is_null($this->userinfo)) { + $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':'); + $this->userinfo = $encoder->encode($this->userinfo); + } + + // validate port + if (!is_null($this->port)) { + if ($this->port < 1 || $this->port > 65535) { + $this->port = null; + } + } + + // validate path + $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/'); + if (!is_null($this->host)) { // this catches $this->host === '' + // path-abempty (hier and relative) + // http://www.example.com/my/path + // //www.example.com/my/path (looks odd, but works, and + // recognized by most browsers) + // (this set is valid or invalid on a scheme by scheme + // basis, so we'll deal with it later) + // file:///my/path + // ///my/path + $this->path = $segments_encoder->encode($this->path); + } elseif ($this->path !== '') { + if ($this->path[0] === '/') { + // path-absolute (hier and relative) + // http:/my/path + // /my/path + if (strlen($this->path) >= 2 && $this->path[1] === '/') { + // This could happen if both the host gets stripped + // out + // http://my/path + // //my/path + $this->path = ''; + } else { + $this->path = $segments_encoder->encode($this->path); + } + } elseif (!is_null($this->scheme)) { + // path-rootless (hier) + // http:my/path + // Short circuit evaluation means we don't need to check nz + $this->path = $segments_encoder->encode($this->path); + } else { + // path-noscheme (relative) + // my/path + // (once again, not checking nz) + $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@'); + $c = strpos($this->path, '/'); + if ($c !== false) { + $this->path = + $segment_nc_encoder->encode(substr($this->path, 0, $c)) . + $segments_encoder->encode(substr($this->path, $c)); + } else { + $this->path = $segment_nc_encoder->encode($this->path); + } + } + } else { + // path-empty (hier and relative) + $this->path = ''; // just to be safe + } + + // qf = query and fragment + $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?'); + + if (!is_null($this->query)) { + $this->query = $qf_encoder->encode($this->query); + } + + if (!is_null($this->fragment)) { + $this->fragment = $qf_encoder->encode($this->fragment); + } + return true; + } + + /** + * Convert URI back to string + * @return string URI appropriate for output + */ + public function toString() + { + // reconstruct authority + $authority = null; + // there is a rendering difference between a null authority + // (http:foo-bar) and an empty string authority + // (http:///foo-bar). + if (!is_null($this->host)) { + $authority = ''; + if (!is_null($this->userinfo)) { + $authority .= $this->userinfo . '@'; + } + $authority .= $this->host; + if (!is_null($this->port)) { + $authority .= ':' . $this->port; + } + } + + // Reconstruct the result + // One might wonder about parsing quirks from browsers after + // this reconstruction. Unfortunately, parsing behavior depends + // on what *scheme* was employed (file:///foo is handled *very* + // differently than http:///foo), so unfortunately we have to + // defer to the schemes to do the right thing. + $result = ''; + if (!is_null($this->scheme)) { + $result .= $this->scheme . ':'; + } + if (!is_null($authority)) { + $result .= '//' . $authority; + } + $result .= $this->path; + if (!is_null($this->query)) { + $result .= '?' . $this->query; + } + if (!is_null($this->fragment)) { + $result .= '#' . $this->fragment; + } + + return $result; + } + + /** + * Returns true if this URL might be considered a 'local' URL given + * the current context. This is true when the host is null, or + * when it matches the host supplied to the configuration. + * + * Note that this does not do any scheme checking, so it is mostly + * only appropriate for metadata that doesn't care about protocol + * security. isBenign is probably what you actually want. + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function isLocal($config, $context) + { + if ($this->host === null) { + return true; + } + $uri_def = $config->getDefinition('URI'); + if ($uri_def->host === $this->host) { + return true; + } + return false; + } + + /** + * Returns true if this URL should be considered a 'benign' URL, + * that is: + * + * - It is a local URL (isLocal), and + * - It has a equal or better level of security + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function isBenign($config, $context) + { + if (!$this->isLocal($config, $context)) { + return false; + } + + $scheme_obj = $this->getSchemeObj($config, $context); + if (!$scheme_obj) { + return false; + } // conservative approach + + $current_scheme_obj = $config->getDefinition('URI')->getDefaultScheme($config, $context); + if ($current_scheme_obj->secure) { + if (!$scheme_obj->secure) { + return false; + } + } + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIDefinition.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIDefinition.php new file mode 100644 index 00000000..e0bd8bcc --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIDefinition.php @@ -0,0 +1,112 @@ +registerFilter(new HTMLPurifier_URIFilter_DisableExternal()); + $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources()); + $this->registerFilter(new HTMLPurifier_URIFilter_DisableResources()); + $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist()); + $this->registerFilter(new HTMLPurifier_URIFilter_SafeIframe()); + $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute()); + $this->registerFilter(new HTMLPurifier_URIFilter_Munge()); + } + + public function registerFilter($filter) + { + $this->registeredFilters[$filter->name] = $filter; + } + + public function addFilter($filter, $config) + { + $r = $filter->prepare($config); + if ($r === false) return; // null is ok, for backwards compat + if ($filter->post) { + $this->postFilters[$filter->name] = $filter; + } else { + $this->filters[$filter->name] = $filter; + } + } + + protected function doSetup($config) + { + $this->setupMemberVariables($config); + $this->setupFilters($config); + } + + protected function setupFilters($config) + { + foreach ($this->registeredFilters as $name => $filter) { + if ($filter->always_load) { + $this->addFilter($filter, $config); + } else { + $conf = $config->get('URI.' . $name); + if ($conf !== false && $conf !== null) { + $this->addFilter($filter, $config); + } + } + } + unset($this->registeredFilters); + } + + protected function setupMemberVariables($config) + { + $this->host = $config->get('URI.Host'); + $base_uri = $config->get('URI.Base'); + if (!is_null($base_uri)) { + $parser = new HTMLPurifier_URIParser(); + $this->base = $parser->parse($base_uri); + $this->defaultScheme = $this->base->scheme; + if (is_null($this->host)) $this->host = $this->base->host; + } + if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme'); + } + + public function getDefaultScheme($config, $context) + { + return HTMLPurifier_URISchemeRegistry::instance()->getScheme($this->defaultScheme, $config, $context); + } + + public function filter(&$uri, $config, $context) + { + foreach ($this->filters as $name => $f) { + $result = $f->filter($uri, $config, $context); + if (!$result) return false; + } + return true; + } + + public function postFilter(&$uri, $config, $context) + { + foreach ($this->postFilters as $name => $f) { + $result = $f->filter($uri, $config, $context); + if (!$result) return false; + } + return true; + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter.php new file mode 100644 index 00000000..09724e9f --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter.php @@ -0,0 +1,74 @@ +getDefinition('URI')->host; + if ($our_host !== null) { + $this->ourHostParts = array_reverse(explode('.', $our_host)); + } + } + + /** + * @param HTMLPurifier_URI $uri Reference + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if (is_null($uri->host)) { + return true; + } + if ($this->ourHostParts === false) { + return false; + } + $host_parts = array_reverse(explode('.', $uri->host)); + foreach ($this->ourHostParts as $i => $x) { + if (!isset($host_parts[$i])) { + return false; + } + if ($host_parts[$i] != $this->ourHostParts[$i]) { + return false; + } + } + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableExternalResources.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableExternalResources.php new file mode 100644 index 00000000..c6562169 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableExternalResources.php @@ -0,0 +1,25 @@ +get('EmbeddedURI', true)) { + return true; + } + return parent::filter($uri, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableResources.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableResources.php new file mode 100644 index 00000000..d5c412c4 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/DisableResources.php @@ -0,0 +1,22 @@ +get('EmbeddedURI', true); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/HostBlacklist.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/HostBlacklist.php new file mode 100644 index 00000000..a6645c17 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/HostBlacklist.php @@ -0,0 +1,46 @@ +blacklist = $config->get('URI.HostBlacklist'); + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + foreach ($this->blacklist as $blacklisted_host_fragment) { + if (strpos($uri->host, $blacklisted_host_fragment) !== false) { + return false; + } + } + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/MakeAbsolute.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/MakeAbsolute.php new file mode 100644 index 00000000..c507bbff --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/MakeAbsolute.php @@ -0,0 +1,158 @@ +getDefinition('URI'); + $this->base = $def->base; + if (is_null($this->base)) { + trigger_error( + 'URI.MakeAbsolute is being ignored due to lack of ' . + 'value for URI.Base configuration', + E_USER_WARNING + ); + return false; + } + $this->base->fragment = null; // fragment is invalid for base URI + $stack = explode('/', $this->base->path); + array_pop($stack); // discard last segment + $stack = $this->_collapseStack($stack); // do pre-parsing + $this->basePathStack = $stack; + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if (is_null($this->base)) { + return true; + } // abort early + if ($uri->path === '' && is_null($uri->scheme) && + is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)) { + // reference to current document + $uri = clone $this->base; + return true; + } + if (!is_null($uri->scheme)) { + // absolute URI already: don't change + if (!is_null($uri->host)) { + return true; + } + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + // scheme not recognized + return false; + } + if (!$scheme_obj->hierarchical) { + // non-hierarchal URI with explicit scheme, don't change + return true; + } + // special case: had a scheme but always is hierarchical and had no authority + } + if (!is_null($uri->host)) { + // network path, don't bother + return true; + } + if ($uri->path === '') { + $uri->path = $this->base->path; + } elseif ($uri->path[0] !== '/') { + // relative path, needs more complicated processing + $stack = explode('/', $uri->path); + $new_stack = array_merge($this->basePathStack, $stack); + if ($new_stack[0] !== '' && !is_null($this->base->host)) { + array_unshift($new_stack, ''); + } + $new_stack = $this->_collapseStack($new_stack); + $uri->path = implode('/', $new_stack); + } else { + // absolute path, but still we should collapse + $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path))); + } + // re-combine + $uri->scheme = $this->base->scheme; + if (is_null($uri->userinfo)) { + $uri->userinfo = $this->base->userinfo; + } + if (is_null($uri->host)) { + $uri->host = $this->base->host; + } + if (is_null($uri->port)) { + $uri->port = $this->base->port; + } + return true; + } + + /** + * Resolve dots and double-dots in a path stack + * @param array $stack + * @return array + */ + private function _collapseStack($stack) + { + $result = array(); + $is_folder = false; + for ($i = 0; isset($stack[$i]); $i++) { + $is_folder = false; + // absorb an internally duplicated slash + if ($stack[$i] == '' && $i && isset($stack[$i + 1])) { + continue; + } + if ($stack[$i] == '..') { + if (!empty($result)) { + $segment = array_pop($result); + if ($segment === '' && empty($result)) { + // error case: attempted to back out too far: + // restore the leading slash + $result[] = ''; + } elseif ($segment === '..') { + $result[] = '..'; // cannot remove .. with .. + } + } else { + // relative path, preserve the double-dots + $result[] = '..'; + } + $is_folder = true; + continue; + } + if ($stack[$i] == '.') { + // silently absorb + $is_folder = true; + continue; + } + $result[] = $stack[$i]; + } + if ($is_folder) { + $result[] = ''; + } + return $result; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/Munge.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/Munge.php new file mode 100644 index 00000000..6e03315a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/Munge.php @@ -0,0 +1,115 @@ +target = $config->get('URI.' . $this->name); + $this->parser = new HTMLPurifier_URIParser(); + $this->doEmbed = $config->get('URI.MungeResources'); + $this->secretKey = $config->get('URI.MungeSecretKey'); + if ($this->secretKey && !function_exists('hash_hmac')) { + throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support."); + } + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + if ($context->get('EmbeddedURI', true) && !$this->doEmbed) { + return true; + } + + $scheme_obj = $uri->getSchemeObj($config, $context); + if (!$scheme_obj) { + return true; + } // ignore unknown schemes, maybe another postfilter did it + if (!$scheme_obj->browsable) { + return true; + } // ignore non-browseable schemes, since we can't munge those in a reasonable way + if ($uri->isBenign($config, $context)) { + return true; + } // don't redirect if a benign URL + + $this->makeReplace($uri, $config, $context); + $this->replace = array_map('rawurlencode', $this->replace); + + $new_uri = strtr($this->target, $this->replace); + $new_uri = $this->parser->parse($new_uri); + // don't redirect if the target host is the same as the + // starting host + if ($uri->host === $new_uri->host) { + return true; + } + $uri = $new_uri; // overwrite + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + */ + protected function makeReplace($uri, $config, $context) + { + $string = $uri->toString(); + // always available + $this->replace['%s'] = $string; + $this->replace['%r'] = $context->get('EmbeddedURI', true); + $token = $context->get('CurrentToken', true); + $this->replace['%n'] = $token ? $token->name : null; + $this->replace['%m'] = $context->get('CurrentAttr', true); + $this->replace['%p'] = $context->get('CurrentCSSProperty', true); + // not always available + if ($this->secretKey) { + $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey); + } + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/SafeIframe.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/SafeIframe.php new file mode 100644 index 00000000..f609c47a --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIFilter/SafeIframe.php @@ -0,0 +1,68 @@ +regexp = $config->get('URI.SafeIframeRegexp'); + return true; + } + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function filter(&$uri, $config, $context) + { + // check if filter not applicable + if (!$config->get('HTML.SafeIframe')) { + return true; + } + // check if the filter should actually trigger + if (!$context->get('EmbeddedURI', true)) { + return true; + } + $token = $context->get('CurrentToken', true); + if (!($token && $token->name == 'iframe')) { + return true; + } + // check if we actually have some whitelists enabled + if ($this->regexp === null) { + return false; + } + // actually check the whitelists + return preg_match($this->regexp, $uri->toString()); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIParser.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIParser.php new file mode 100644 index 00000000..0e7381a0 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIParser.php @@ -0,0 +1,71 @@ +percentEncoder = new HTMLPurifier_PercentEncoder(); + } + + /** + * Parses a URI. + * @param $uri string URI to parse + * @return HTMLPurifier_URI representation of URI. This representation has + * not been validated yet and may not conform to RFC. + */ + public function parse($uri) + { + $uri = $this->percentEncoder->normalize($uri); + + // Regexp is as per Appendix B. + // Note that ["<>] are an addition to the RFC's recommended + // characters, because they represent external delimeters. + $r_URI = '!'. + '(([a-zA-Z0-9\.\+\-]+):)?'. // 2. Scheme + '(//([^/?#"<>]*))?'. // 4. Authority + '([^?#"<>]*)'. // 5. Path + '(\?([^#"<>]*))?'. // 7. Query + '(#([^"<>]*))?'. // 8. Fragment + '!'; + + $matches = array(); + $result = preg_match($r_URI, $uri, $matches); + + if (!$result) return false; // *really* invalid URI + + // seperate out parts + $scheme = !empty($matches[1]) ? $matches[2] : null; + $authority = !empty($matches[3]) ? $matches[4] : null; + $path = $matches[5]; // always present, can be empty + $query = !empty($matches[6]) ? $matches[7] : null; + $fragment = !empty($matches[8]) ? $matches[9] : null; + + // further parse authority + if ($authority !== null) { + $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/"; + $matches = array(); + preg_match($r_authority, $authority, $matches); + $userinfo = !empty($matches[1]) ? $matches[2] : null; + $host = !empty($matches[3]) ? $matches[3] : ''; + $port = !empty($matches[4]) ? (int) $matches[5] : null; + } else { + $port = $host = $userinfo = null; + } + + return new HTMLPurifier_URI( + $scheme, $userinfo, $host, $port, $path, $query, $fragment); + } + +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme.php new file mode 100644 index 00000000..fe9e82cf --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme.php @@ -0,0 +1,102 @@ +, resolves edge cases + * with making relative URIs absolute + * @type bool + */ + public $hierarchical = false; + + /** + * Whether or not the URI may omit a hostname when the scheme is + * explicitly specified, ala file:///path/to/file. As of writing, + * 'file' is the only scheme that browsers support his properly. + * @type bool + */ + public $may_omit_host = false; + + /** + * Validates the components of a URI for a specific scheme. + * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool success or failure + */ + abstract public function doValidate(&$uri, $config, $context); + + /** + * Public interface for validating components of a URI. Performs a + * bunch of default actions. Don't overload this method. + * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool success or failure + */ + public function validate(&$uri, $config, $context) + { + if ($this->default_port == $uri->port) { + $uri->port = null; + } + // kludge: browsers do funny things when the scheme but not the + // authority is set + if (!$this->may_omit_host && + // if the scheme is present, a missing host is always in error + (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) || + // if the scheme is not present, a *blank* host is in error, + // since this translates into '///path' which most browsers + // interpret as being 'http://path'. + (is_null($uri->scheme) && $uri->host === '') + ) { + do { + if (is_null($uri->scheme)) { + if (substr($uri->path, 0, 2) != '//') { + $uri->host = null; + break; + } + // URI is '////path', so we cannot nullify the + // host to preserve semantics. Try expanding the + // hostname instead (fall through) + } + // first see if we can manually insert a hostname + $host = $config->get('URI.Host'); + if (!is_null($host)) { + $uri->host = $host; + } else { + // we can't do anything sensible, reject the URL. + return false; + } + } while (false); + } + return $this->doValidate($uri, $config, $context); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/data.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/data.php new file mode 100644 index 00000000..41c49d55 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/data.php @@ -0,0 +1,136 @@ + true, + 'image/gif' => true, + 'image/png' => true, + ); + // this is actually irrelevant since we only write out the path + // component + /** + * @type bool + */ + public $may_omit_host = true; + + /** + * @param HTMLPurifier_URI $uri + * @param HTMLPurifier_Config $config + * @param HTMLPurifier_Context $context + * @return bool + */ + public function doValidate(&$uri, $config, $context) + { + $result = explode(',', $uri->path, 2); + $is_base64 = false; + $charset = null; + $content_type = null; + if (count($result) == 2) { + list($metadata, $data) = $result; + // do some legwork on the metadata + $metas = explode(';', $metadata); + while (!empty($metas)) { + $cur = array_shift($metas); + if ($cur == 'base64') { + $is_base64 = true; + break; + } + if (substr($cur, 0, 8) == 'charset=') { + // doesn't match if there are arbitrary spaces, but + // whatever dude + if ($charset !== null) { + continue; + } // garbage + $charset = substr($cur, 8); // not used + } else { + if ($content_type !== null) { + continue; + } // garbage + $content_type = $cur; + } + } + } else { + $data = $result[0]; + } + if ($content_type !== null && empty($this->allowed_types[$content_type])) { + return false; + } + if ($charset !== null) { + // error; we don't allow plaintext stuff + $charset = null; + } + $data = rawurldecode($data); + if ($is_base64) { + $raw_data = base64_decode($data); + } else { + $raw_data = $data; + } + if ( strlen($raw_data) < 12 ) { + // error; exif_imagetype throws exception with small files, + // and this likely indicates a corrupt URI/failed parse anyway + return false; + } + // XXX probably want to refactor this into a general mechanism + // for filtering arbitrary content types + if (function_exists('sys_get_temp_dir')) { + $file = tempnam(sys_get_temp_dir(), ""); + } else { + $file = tempnam("/tmp", ""); + } + file_put_contents($file, $raw_data); + if (function_exists('exif_imagetype')) { + $image_code = exif_imagetype($file); + unlink($file); + } elseif (function_exists('getimagesize')) { + set_error_handler(array($this, 'muteErrorHandler')); + $info = getimagesize($file); + restore_error_handler(); + unlink($file); + if ($info == false) { + return false; + } + $image_code = $info[2]; + } else { + trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR); + } + $real_content_type = image_type_to_mime_type($image_code); + if ($real_content_type != $content_type) { + // we're nice guys; if the content type is something else we + // support, change it over + if (empty($this->allowed_types[$real_content_type])) { + return false; + } + $content_type = $real_content_type; + } + // ok, it's kosher, rewrite what we need + $uri->userinfo = null; + $uri->host = null; + $uri->port = null; + $uri->fragment = null; + $uri->query = null; + $uri->path = "$content_type;base64," . base64_encode($raw_data); + return true; + } + + /** + * @param int $errno + * @param string $errstr + */ + public function muteErrorHandler($errno, $errstr) + { + } +} diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/file.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/file.php new file mode 100644 index 00000000..215be4ba --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/file.php @@ -0,0 +1,44 @@ +userinfo = null; + // file:// makes no provisions for accessing the resource + $uri->port = null; + // While it seems to work on Firefox, the querystring has + // no possible effect and is thus stripped. + $uri->query = null; + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/ftp.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/ftp.php new file mode 100644 index 00000000..1eb43ee5 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/ftp.php @@ -0,0 +1,58 @@ +query = null; + + // typecode check + $semicolon_pos = strrpos($uri->path, ';'); // reverse + if ($semicolon_pos !== false) { + $type = substr($uri->path, $semicolon_pos + 1); // no semicolon + $uri->path = substr($uri->path, 0, $semicolon_pos); + $type_ret = ''; + if (strpos($type, '=') !== false) { + // figure out whether or not the declaration is correct + list($key, $typecode) = explode('=', $type, 2); + if ($key !== 'type') { + // invalid key, tack it back on encoded + $uri->path .= '%3B' . $type; + } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') { + $type_ret = ";type=$typecode"; + } + } else { + $uri->path .= '%3B' . $type; + } + $uri->path = str_replace(';', '%3B', $uri->path); + $uri->path .= $type_ret; + } + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/http.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/http.php new file mode 100644 index 00000000..ce69ec43 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/http.php @@ -0,0 +1,36 @@ +userinfo = null; + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/https.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/https.php new file mode 100644 index 00000000..0e96882d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/https.php @@ -0,0 +1,18 @@ +userinfo = null; + $uri->host = null; + $uri->port = null; + // we need to validate path against RFC 2368's addr-spec + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/news.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/news.php new file mode 100644 index 00000000..7490927d --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/news.php @@ -0,0 +1,35 @@ +userinfo = null; + $uri->host = null; + $uri->port = null; + $uri->query = null; + // typecode check needed on path + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/nntp.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/nntp.php new file mode 100644 index 00000000..f211d715 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/nntp.php @@ -0,0 +1,32 @@ +userinfo = null; + $uri->query = null; + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/tel.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/tel.php new file mode 100644 index 00000000..8cd19335 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URIScheme/tel.php @@ -0,0 +1,46 @@ +userinfo = null; + $uri->host = null; + $uri->port = null; + + // Delete all non-numeric characters, non-x characters + // from phone number, EXCEPT for a leading plus sign. + $uri->path = preg_replace('/(?!^\+)[^\dx]/', '', + // Normalize e(x)tension to lower-case + str_replace('X', 'x', $uri->path)); + + return true; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/URISchemeRegistry.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URISchemeRegistry.php new file mode 100644 index 00000000..4ac8a0b7 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/URISchemeRegistry.php @@ -0,0 +1,81 @@ +get('URI.AllowedSchemes'); + if (!$config->get('URI.OverrideAllowedSchemes') && + !isset($allowed_schemes[$scheme]) + ) { + return; + } + + if (isset($this->schemes[$scheme])) { + return $this->schemes[$scheme]; + } + if (!isset($allowed_schemes[$scheme])) { + return; + } + + $class = 'HTMLPurifier_URIScheme_' . $scheme; + if (!class_exists($class)) { + return; + } + $this->schemes[$scheme] = new $class(); + return $this->schemes[$scheme]; + } + + /** + * Registers a custom scheme to the cache, bypassing reflection. + * @param string $scheme Scheme name + * @param HTMLPurifier_URIScheme $scheme_obj + */ + public function register($scheme, $scheme_obj) + { + $this->schemes[$scheme] = $scheme_obj; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/UnitConverter.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/UnitConverter.php new file mode 100644 index 00000000..166f3bf3 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/UnitConverter.php @@ -0,0 +1,307 @@ + array( + 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary + 'pt' => 4, + 'pc' => 48, + 'in' => 288, + self::METRIC => array('pt', '0.352777778', 'mm'), + ), + self::METRIC => array( + 'mm' => 1, + 'cm' => 10, + self::ENGLISH => array('mm', '2.83464567', 'pt'), + ), + ); + + /** + * Minimum bcmath precision for output. + * @type int + */ + protected $outputPrecision; + + /** + * Bcmath precision for internal calculations. + * @type int + */ + protected $internalPrecision; + + /** + * Whether or not BCMath is available. + * @type bool + */ + private $bcmath; + + public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false) + { + $this->outputPrecision = $output_precision; + $this->internalPrecision = $internal_precision; + $this->bcmath = !$force_no_bcmath && function_exists('bcmul'); + } + + /** + * Converts a length object of one unit into another unit. + * @param HTMLPurifier_Length $length + * Instance of HTMLPurifier_Length to convert. You must validate() + * it before passing it here! + * @param string $to_unit + * Unit to convert to. + * @return HTMLPurifier_Length|bool + * @note + * About precision: This conversion function pays very special + * attention to the incoming precision of values and attempts + * to maintain a number of significant figure. Results are + * fairly accurate up to nine digits. Some caveats: + * - If a number is zero-padded as a result of this significant + * figure tracking, the zeroes will be eliminated. + * - If a number contains less than four sigfigs ($outputPrecision) + * and this causes some decimals to be excluded, those + * decimals will be added on. + */ + public function convert($length, $to_unit) + { + if (!$length->isValid()) { + return false; + } + + $n = $length->getN(); + $unit = $length->getUnit(); + + if ($n === '0' || $unit === false) { + return new HTMLPurifier_Length('0', false); + } + + $state = $dest_state = false; + foreach (self::$units as $k => $x) { + if (isset($x[$unit])) { + $state = $k; + } + if (isset($x[$to_unit])) { + $dest_state = $k; + } + } + if (!$state || !$dest_state) { + return false; + } + + // Some calculations about the initial precision of the number; + // this will be useful when we need to do final rounding. + $sigfigs = $this->getSigFigs($n); + if ($sigfigs < $this->outputPrecision) { + $sigfigs = $this->outputPrecision; + } + + // BCMath's internal precision deals only with decimals. Use + // our default if the initial number has no decimals, or increase + // it by how ever many decimals, thus, the number of guard digits + // will always be greater than or equal to internalPrecision. + $log = (int)floor(log(abs($n), 10)); + $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision + + for ($i = 0; $i < 2; $i++) { + + // Determine what unit IN THIS SYSTEM we need to convert to + if ($dest_state === $state) { + // Simple conversion + $dest_unit = $to_unit; + } else { + // Convert to the smallest unit, pending a system shift + $dest_unit = self::$units[$state][$dest_state][0]; + } + + // Do the conversion if necessary + if ($dest_unit !== $unit) { + $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp); + $n = $this->mul($n, $factor, $cp); + $unit = $dest_unit; + } + + // Output was zero, so bail out early. Shouldn't ever happen. + if ($n === '') { + $n = '0'; + $unit = $to_unit; + break; + } + + // It was a simple conversion, so bail out + if ($dest_state === $state) { + break; + } + + if ($i !== 0) { + // Conversion failed! Apparently, the system we forwarded + // to didn't have this unit. This should never happen! + return false; + } + + // Pre-condition: $i == 0 + + // Perform conversion to next system of units + $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp); + $unit = self::$units[$state][$dest_state][2]; + $state = $dest_state; + + // One more loop around to convert the unit in the new system. + + } + + // Post-condition: $unit == $to_unit + if ($unit !== $to_unit) { + return false; + } + + // Useful for debugging: + //echo "
        n";
        +        //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n
        \n"; + + $n = $this->round($n, $sigfigs); + if (strpos($n, '.') !== false) { + $n = rtrim($n, '0'); + } + $n = rtrim($n, '.'); + + return new HTMLPurifier_Length($n, $unit); + } + + /** + * Returns the number of significant figures in a string number. + * @param string $n Decimal number + * @return int number of sigfigs + */ + public function getSigFigs($n) + { + $n = ltrim($n, '0+-'); + $dp = strpos($n, '.'); // decimal position + if ($dp === false) { + $sigfigs = strlen(rtrim($n, '0')); + } else { + $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character + if ($dp !== 0) { + $sigfigs--; + } + } + return $sigfigs; + } + + /** + * Adds two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function add($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcadd($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 + (float)$s2, $scale); + } + } + + /** + * Multiples two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function mul($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcmul($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 * (float)$s2, $scale); + } + } + + /** + * Divides two numbers, using arbitrary precision when available. + * @param string $s1 + * @param string $s2 + * @param int $scale + * @return string + */ + private function div($s1, $s2, $scale) + { + if ($this->bcmath) { + return bcdiv($s1, $s2, $scale); + } else { + return $this->scale((float)$s1 / (float)$s2, $scale); + } + } + + /** + * Rounds a number according to the number of sigfigs it should have, + * using arbitrary precision when available. + * @param float $n + * @param int $sigfigs + * @return string + */ + private function round($n, $sigfigs) + { + $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1 + $rp = $sigfigs - $new_log - 1; // Number of decimal places needed + $neg = $n < 0 ? '-' : ''; // Negative sign + if ($this->bcmath) { + if ($rp >= 0) { + $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1); + $n = bcdiv($n, '1', $rp); + } else { + // This algorithm partially depends on the standardized + // form of numbers that comes out of bcmath. + $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0); + $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1); + } + return $n; + } else { + return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1); + } + } + + /** + * Scales a float to $scale digits right of decimal point, like BCMath. + * @param float $r + * @param int $scale + * @return string + */ + private function scale($r, $scale) + { + if ($scale < 0) { + // The f sprintf type doesn't support negative numbers, so we + // need to cludge things manually. First get the string. + $r = sprintf('%.0f', (float)$r); + // Due to floating point precision loss, $r will more than likely + // look something like 4652999999999.9234. We grab one more digit + // than we need to precise from $r and then use that to round + // appropriately. + $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1); + // Now we return it, truncating the zero that was rounded off. + return substr($precise, 0, -1) . str_repeat('0', -$scale + 1); + } + return sprintf('%.' . $scale . 'f', (float)$r); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser.php new file mode 100644 index 00000000..0c97c828 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser.php @@ -0,0 +1,198 @@ + self::C_STRING, + 'istring' => self::ISTRING, + 'text' => self::TEXT, + 'itext' => self::ITEXT, + 'int' => self::C_INT, + 'float' => self::C_FLOAT, + 'bool' => self::C_BOOL, + 'lookup' => self::LOOKUP, + 'list' => self::ALIST, + 'hash' => self::HASH, + 'mixed' => self::C_MIXED + ); + + /** + * Lookup table of types that are string, and can have aliases or + * allowed value lists. + */ + public static $stringTypes = array( + self::C_STRING => true, + self::ISTRING => true, + self::TEXT => true, + self::ITEXT => true, + ); + + /** + * Validate a variable according to type. + * It may return NULL as a valid type if $allow_null is true. + * + * @param mixed $var Variable to validate + * @param int $type Type of variable, see HTMLPurifier_VarParser->types + * @param bool $allow_null Whether or not to permit null as a value + * @return string Validated and type-coerced variable + * @throws HTMLPurifier_VarParserException + */ + final public function parse($var, $type, $allow_null = false) + { + if (is_string($type)) { + if (!isset(HTMLPurifier_VarParser::$types[$type])) { + throw new HTMLPurifier_VarParserException("Invalid type '$type'"); + } else { + $type = HTMLPurifier_VarParser::$types[$type]; + } + } + $var = $this->parseImplementation($var, $type, $allow_null); + if ($allow_null && $var === null) { + return null; + } + // These are basic checks, to make sure nothing horribly wrong + // happened in our implementations. + switch ($type) { + case (self::C_STRING): + case (self::ISTRING): + case (self::TEXT): + case (self::ITEXT): + if (!is_string($var)) { + break; + } + if ($type == self::ISTRING || $type == self::ITEXT) { + $var = strtolower($var); + } + return $var; + case (self::C_INT): + if (!is_int($var)) { + break; + } + return $var; + case (self::C_FLOAT): + if (!is_float($var)) { + break; + } + return $var; + case (self::C_BOOL): + if (!is_bool($var)) { + break; + } + return $var; + case (self::LOOKUP): + case (self::ALIST): + case (self::HASH): + if (!is_array($var)) { + break; + } + if ($type === self::LOOKUP) { + foreach ($var as $k) { + if ($k !== true) { + $this->error('Lookup table contains value other than true'); + } + } + } elseif ($type === self::ALIST) { + $keys = array_keys($var); + if (array_keys($keys) !== $keys) { + $this->error('Indices for list are not uniform'); + } + } + return $var; + case (self::C_MIXED): + return $var; + default: + $this->errorInconsistent(get_class($this), $type); + } + $this->errorGeneric($var, $type); + } + + /** + * Actually implements the parsing. Base implementation does not + * do anything to $var. Subclasses should overload this! + * @param mixed $var + * @param int $type + * @param bool $allow_null + * @return string + */ + protected function parseImplementation($var, $type, $allow_null) + { + return $var; + } + + /** + * Throws an exception. + * @throws HTMLPurifier_VarParserException + */ + protected function error($msg) + { + throw new HTMLPurifier_VarParserException($msg); + } + + /** + * Throws an inconsistency exception. + * @note This should not ever be called. It would be called if we + * extend the allowed values of HTMLPurifier_VarParser without + * updating subclasses. + * @param string $class + * @param int $type + * @throws HTMLPurifier_Exception + */ + protected function errorInconsistent($class, $type) + { + throw new HTMLPurifier_Exception( + "Inconsistency in $class: " . HTMLPurifier_VarParser::getTypeName($type) . + " not implemented" + ); + } + + /** + * Generic error for if a type didn't work. + * @param mixed $var + * @param int $type + */ + protected function errorGeneric($var, $type) + { + $vtype = gettype($var); + $this->error("Expected type " . HTMLPurifier_VarParser::getTypeName($type) . ", got $vtype"); + } + + /** + * @param int $type + * @return string + */ + public static function getTypeName($type) + { + static $lookup; + if (!$lookup) { + // Lazy load the alternative lookup table + $lookup = array_flip(HTMLPurifier_VarParser::$types); + } + if (!isset($lookup[$type])) { + return 'unknown'; + } + return $lookup[$type]; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Flexible.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Flexible.php new file mode 100644 index 00000000..3bfbe838 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Flexible.php @@ -0,0 +1,130 @@ + $j) { + $var[$i] = trim($j); + } + if ($type === self::HASH) { + // key:value,key2:value2 + $nvar = array(); + foreach ($var as $keypair) { + $c = explode(':', $keypair, 2); + if (!isset($c[1])) { + continue; + } + $nvar[trim($c[0])] = trim($c[1]); + } + $var = $nvar; + } + } + if (!is_array($var)) { + break; + } + $keys = array_keys($var); + if ($keys === array_keys($keys)) { + if ($type == self::ALIST) { + return $var; + } elseif ($type == self::LOOKUP) { + $new = array(); + foreach ($var as $key) { + $new[$key] = true; + } + return $new; + } else { + break; + } + } + if ($type === self::ALIST) { + trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING); + return array_values($var); + } + if ($type === self::LOOKUP) { + foreach ($var as $key => $value) { + if ($value !== true) { + trigger_error( + "Lookup array has non-true value at key '$key'; " . + "maybe your input array was not indexed numerically", + E_USER_WARNING + ); + } + $var[$key] = true; + } + } + return $var; + default: + $this->errorInconsistent(__CLASS__, $type); + } + $this->errorGeneric($var, $type); + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Native.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Native.php new file mode 100644 index 00000000..f11c318e --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParser/Native.php @@ -0,0 +1,38 @@ +evalExpression($var); + } + + /** + * @param string $expr + * @return mixed + * @throws HTMLPurifier_VarParserException + */ + protected function evalExpression($expr) + { + $var = null; + $result = eval("\$var = $expr;"); + if ($result === false) { + throw new HTMLPurifier_VarParserException("Fatal error in evaluated code"); + } + return $var; + } +} + +// vim: et sw=4 sts=4 diff --git a/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParserException.php b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParserException.php new file mode 100644 index 00000000..5df34149 --- /dev/null +++ b/lib/ezyang/htmlpurifier/library/HTMLPurifier/VarParserException.php @@ -0,0 +1,11 @@ +front = $front; + $this->back = $back; + } + + /** + * Creates a zipper from an array, with a hole in the + * 0-index position. + * @param Array to zipper-ify. + * @return Tuple of zipper and element of first position. + */ + static public function fromArray($array) { + $z = new self(array(), array_reverse($array)); + $t = $z->delete(); // delete the "dummy hole" + return array($z, $t); + } + + /** + * Convert zipper back into a normal array, optionally filling in + * the hole with a value. (Usually you should supply a $t, unless you + * are at the end of the array.) + */ + public function toArray($t = NULL) { + $a = $this->front; + if ($t !== NULL) $a[] = $t; + for ($i = count($this->back)-1; $i >= 0; $i--) { + $a[] = $this->back[$i]; + } + return $a; + } + + /** + * Move hole to the next element. + * @param $t Element to fill hole with + * @return Original contents of new hole. + */ + public function next($t) { + if ($t !== NULL) array_push($this->front, $t); + return empty($this->back) ? NULL : array_pop($this->back); + } + + /** + * Iterated hole advancement. + * @param $t Element to fill hole with + * @param $i How many forward to advance hole + * @return Original contents of new hole, i away + */ + public function advance($t, $n) { + for ($i = 0; $i < $n; $i++) { + $t = $this->next($t); + } + return $t; + } + + /** + * Move hole to the previous element + * @param $t Element to fill hole with + * @return Original contents of new hole. + */ + public function prev($t) { + if ($t !== NULL) array_push($this->back, $t); + return empty($this->front) ? NULL : array_pop($this->front); + } + + /** + * Delete contents of current hole, shifting hole to + * next element. + * @return Original contents of new hole. + */ + public function delete() { + return empty($this->back) ? NULL : array_pop($this->back); + } + + /** + * Returns true if we are at the end of the list. + * @return bool + */ + public function done() { + return empty($this->back); + } + + /** + * Insert element before hole. + * @param Element to insert + */ + public function insertBefore($t) { + if ($t !== NULL) array_push($this->front, $t); + } + + /** + * Insert element after hole. + * @param Element to insert + */ + public function insertAfter($t) { + if ($t !== NULL) array_push($this->back, $t); + } + + /** + * Splice in multiple elements at hole. Functional specification + * in terms of array_splice: + * + * $arr1 = $arr; + * $old1 = array_splice($arr1, $i, $delete, $replacement); + * + * list($z, $t) = HTMLPurifier_Zipper::fromArray($arr); + * $t = $z->advance($t, $i); + * list($old2, $t) = $z->splice($t, $delete, $replacement); + * $arr2 = $z->toArray($t); + * + * assert($old1 === $old2); + * assert($arr1 === $arr2); + * + * NB: the absolute index location after this operation is + * *unchanged!* + * + * @param Current contents of hole. + */ + public function splice($t, $delete, $replacement) { + // delete + $old = array(); + $r = $t; + for ($i = $delete; $i > 0; $i--) { + $old[] = $r; + $r = $this->delete(); + } + // insert + for ($i = count($replacement)-1; $i >= 0; $i--) { + $this->insertAfter($r); + $r = $replacement[$i]; + } + return array($old, $r); + } +} diff --git a/lib/guzzlehttp/guzzle/CHANGELOG.md b/lib/guzzlehttp/guzzle/CHANGELOG.md new file mode 100644 index 00000000..c3acb777 --- /dev/null +++ b/lib/guzzlehttp/guzzle/CHANGELOG.md @@ -0,0 +1,1479 @@ +# Change Log + +Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. + +## 7.4.0 - 2021-10-18 + +### Added + +- Support PHP 8.1 [#2929](https://github.com/guzzle/guzzle/pull/2929), [#2939](https://github.com/guzzle/guzzle/pull/2939) +- Support `psr/log` version 2 and 3 [#2943](https://github.com/guzzle/guzzle/pull/2943) + +### Fixed + +- Make sure we always call `restore_error_handler()` [#2915](https://github.com/guzzle/guzzle/pull/2915) +- Fix progress parameter type compatibility between the cURL and stream handlers [#2936](https://github.com/guzzle/guzzle/pull/2936) +- Throw `InvalidArgumentException` when an incorrect `headers` array is provided [#2916](https://github.com/guzzle/guzzle/pull/2916), [#2942](https://github.com/guzzle/guzzle/pull/2942) + +### Changed + +- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945) + +## 7.3.0 - 2021-03-23 + +### Added + +- Support for DER and P12 certificates [#2413](https://github.com/guzzle/guzzle/pull/2413) +- Support the cURL (http://) scheme for StreamHandler proxies [#2850](https://github.com/guzzle/guzzle/pull/2850) +- Support for `guzzlehttp/psr7:^2.0` [#2878](https://github.com/guzzle/guzzle/pull/2878) + +### Fixed + +- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872) + +## 7.2.0 - 2020-10-10 + +### Added + +- Support for PHP 8 [#2712](https://github.com/guzzle/guzzle/pull/2712), [#2715](https://github.com/guzzle/guzzle/pull/2715), [#2789](https://github.com/guzzle/guzzle/pull/2789) +- Support passing a body summarizer to the http errors middleware [#2795](https://github.com/guzzle/guzzle/pull/2795) + +### Fixed + +- Handle exceptions during response creation [#2591](https://github.com/guzzle/guzzle/pull/2591) +- Fix CURLOPT_ENCODING not to be overwritten [#2595](https://github.com/guzzle/guzzle/pull/2595) +- Make sure the Request always has a body object [#2804](https://github.com/guzzle/guzzle/pull/2804) + +### Changed + +- The `TooManyRedirectsException` has a response [#2660](https://github.com/guzzle/guzzle/pull/2660) +- Avoid "functions" from dependencies [#2712](https://github.com/guzzle/guzzle/pull/2712) + +### Deprecated + +- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786) + +## 7.1.1 - 2020-09-30 + +### Fixed + +- Incorrect EOF detection for response body streams on Windows. + +### Changed + +- We dont connect curl `sink` on HEAD requests. +- Removed some PHP 5 workarounds + +## 7.1.0 - 2020-09-22 + +### Added + +- `GuzzleHttp\MessageFormatterInterface` + +### Fixed + +- Fixed issue that caused cookies with no value not to be stored. +- On redirects, we allow all safe methods like GET, HEAD and OPTIONS. +- Fixed logging on empty responses. +- Make sure MessageFormatter::format returns string + +### Deprecated + +- All functions in `GuzzleHttp` has been deprecated. Use static methods on `Utils` instead. +- `ClientInterface::getConfig()` +- `Client::getConfig()` +- `Client::__call()` +- `Utils::defaultCaBundle()` +- `CurlFactory::LOW_CURL_VERSION_NUMBER` + +## 7.0.1 - 2020-06-27 + +* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699) + +## 7.0.0 - 2020-06-27 + +No changes since 7.0.0-rc1. + +## 7.0.0-rc1 - 2020-06-15 + +### Changed + +* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629) +* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675) + +## 7.0.0-beta2 - 2020-05-25 + +### Added + +* Using `Utils` class instead of functions in the `GuzzleHttp` namespace. [#2546](https://github.com/guzzle/guzzle/pull/2546) +* `ClientInterface::MAJOR_VERSION` [#2583](https://github.com/guzzle/guzzle/pull/2583) + +### Changed + +* Avoid the `getenv` function when unsafe [#2531](https://github.com/guzzle/guzzle/pull/2531) +* Added real client methods [#2529](https://github.com/guzzle/guzzle/pull/2529) +* Avoid functions due to global install conflicts [#2546](https://github.com/guzzle/guzzle/pull/2546) +* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550) +* Adding methods for HTTP verbs like `Client::get()`, `Client::head()`, `Client::patch()` etc [#2529](https://github.com/guzzle/guzzle/pull/2529) +* `ConnectException` extends `TransferException` [#2541](https://github.com/guzzle/guzzle/pull/2541) +* Updated the default User Agent to "GuzzleHttp/7" [#2654](https://github.com/guzzle/guzzle/pull/2654) + +### Fixed + +* Various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626) + +### Removed + +* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528) + +## 7.0.0-beta1 - 2019-12-30 + +The diff might look very big but 95% of Guzzle users will be able to upgrade without modification. +Please see [the upgrade document](UPGRADING.md) that describes all BC breaking changes. + +### Added + +* Implement PSR-18 and dropped PHP 5 support [#2421](https://github.com/guzzle/guzzle/pull/2421) [#2474](https://github.com/guzzle/guzzle/pull/2474) +* PHP 7 types [#2442](https://github.com/guzzle/guzzle/pull/2442) [#2449](https://github.com/guzzle/guzzle/pull/2449) [#2466](https://github.com/guzzle/guzzle/pull/2466) [#2497](https://github.com/guzzle/guzzle/pull/2497) [#2499](https://github.com/guzzle/guzzle/pull/2499) +* IDN support for redirects [2424](https://github.com/guzzle/guzzle/pull/2424) + +### Changed + +* Dont allow passing null as third argument to `BadResponseException::__construct()` [#2427](https://github.com/guzzle/guzzle/pull/2427) +* Use SAPI constant instead of method call [#2450](https://github.com/guzzle/guzzle/pull/2450) +* Use native function invocation [#2444](https://github.com/guzzle/guzzle/pull/2444) +* Better defaults for PHP installations with old ICU lib [2454](https://github.com/guzzle/guzzle/pull/2454) +* Added visibility to all constants [#2462](https://github.com/guzzle/guzzle/pull/2462) +* Dont allow passing `null` as URI to `Client::request()` and `Client::requestAsync()` [#2461](https://github.com/guzzle/guzzle/pull/2461) +* Widen the exception argument to throwable [#2495](https://github.com/guzzle/guzzle/pull/2495) + +### Fixed + +* Logging when Promise rejected with a string [#2311](https://github.com/guzzle/guzzle/pull/2311) + +### Removed + +* Class `SeekException` [#2162](https://github.com/guzzle/guzzle/pull/2162) +* `RequestException::getResponseBodySummary()` [#2425](https://github.com/guzzle/guzzle/pull/2425) +* `CookieJar::getCookieValue()` [#2433](https://github.com/guzzle/guzzle/pull/2433) +* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440) +* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464) + +## 6.5.2 - 2019-12-23 + +* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489) + +## 6.5.1 - 2019-12-21 + +* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454) +* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424) + +## 6.5.0 - 2019-12-07 + +* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143) +* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287) +* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132) +* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348) +* Deprecated `ClientInterface::VERSION` + +## 6.4.1 - 2019-10-23 + +* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that +* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar` + +## 6.4.0 - 2019-10-23 + +* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108) +* Fix: Test if response is readable before returning a summary in `RequestException::getResponseBodySummary()` [#2081](https://github.com/guzzle/guzzle/pull/2081) +* Fix: Add support for GUZZLE_CURL_SELECT_TIMEOUT environment variable [#2161](https://github.com/guzzle/guzzle/pull/2161) +* Improvement: Added `GuzzleHttp\Exception\InvalidArgumentException` [#2163](https://github.com/guzzle/guzzle/pull/2163) +* Improvement: Added `GuzzleHttp\_current_time()` to use `hrtime()` if that function exists. [#2242](https://github.com/guzzle/guzzle/pull/2242) +* Improvement: Added curl's `appconnect_time` in `TransferStats` [#2284](https://github.com/guzzle/guzzle/pull/2284) +* Improvement: Make GuzzleException extend Throwable wherever it's available [#2273](https://github.com/guzzle/guzzle/pull/2273) +* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335) +* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362) + +## 6.3.3 - 2018-04-22 + +* Fix: Default headers when decode_content is specified + + +## 6.3.2 - 2018-03-26 + +* Fix: Release process + + +## 6.3.1 - 2018-03-26 + +* Bug fix: Parsing 0 epoch expiry times in cookies [#2014](https://github.com/guzzle/guzzle/pull/2014) +* Improvement: Better ConnectException detection [#2012](https://github.com/guzzle/guzzle/pull/2012) +* Bug fix: Malformed domain that contains a "/" [#1999](https://github.com/guzzle/guzzle/pull/1999) +* Bug fix: Undefined offset when a cookie has no first key-value pair [#1998](https://github.com/guzzle/guzzle/pull/1998) +* Improvement: Support PHPUnit 6 [#1953](https://github.com/guzzle/guzzle/pull/1953) +* Bug fix: Support empty headers [#1915](https://github.com/guzzle/guzzle/pull/1915) +* Bug fix: Ignore case during header modifications [#1916](https://github.com/guzzle/guzzle/pull/1916) + ++ Minor code cleanups, documentation fixes and clarifications. + + +## 6.3.0 - 2017-06-22 + +* Feature: force IP resolution (ipv4 or ipv6) [#1608](https://github.com/guzzle/guzzle/pull/1608), [#1659](https://github.com/guzzle/guzzle/pull/1659) +* Improvement: Don't include summary in exception message when body is empty [#1621](https://github.com/guzzle/guzzle/pull/1621) +* Improvement: Handle `on_headers` option in MockHandler [#1580](https://github.com/guzzle/guzzle/pull/1580) +* Improvement: Added SUSE Linux CA path [#1609](https://github.com/guzzle/guzzle/issues/1609) +* Improvement: Use class reference for getting the name of the class instead of using hardcoded strings [#1641](https://github.com/guzzle/guzzle/pull/1641) +* Feature: Added `read_timeout` option [#1611](https://github.com/guzzle/guzzle/pull/1611) +* Bug fix: PHP 7.x fixes [#1685](https://github.com/guzzle/guzzle/pull/1685), [#1686](https://github.com/guzzle/guzzle/pull/1686), [#1811](https://github.com/guzzle/guzzle/pull/1811) +* Deprecation: BadResponseException instantiation without a response [#1642](https://github.com/guzzle/guzzle/pull/1642) +* Feature: Added NTLM auth [#1569](https://github.com/guzzle/guzzle/pull/1569) +* Feature: Track redirect HTTP status codes [#1711](https://github.com/guzzle/guzzle/pull/1711) +* Improvement: Check handler type during construction [#1745](https://github.com/guzzle/guzzle/pull/1745) +* Improvement: Always include the Content-Length if there's a body [#1721](https://github.com/guzzle/guzzle/pull/1721) +* Feature: Added convenience method to access a cookie by name [#1318](https://github.com/guzzle/guzzle/pull/1318) +* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684) +* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827) + + ++ Minor code cleanups, documentation fixes and clarifications. + +## 6.2.3 - 2017-02-28 + +* Fix deprecations with guzzle/psr7 version 1.4 + +## 6.2.2 - 2016-10-08 + +* Allow to pass nullable Response to delay callable +* Only add scheme when host is present +* Fix drain case where content-length is the literal string zero +* Obfuscate in-URL credentials in exceptions + +## 6.2.1 - 2016-07-18 + +* Address HTTP_PROXY security vulnerability, CVE-2016-5385: + https://httpoxy.org/ +* Fixing timeout bug with StreamHandler: + https://github.com/guzzle/guzzle/pull/1488 +* Only read up to `Content-Length` in PHP StreamHandler to avoid timeouts when + a server does not honor `Connection: close`. +* Ignore URI fragment when sending requests. + +## 6.2.0 - 2016-03-21 + +* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`. + https://github.com/guzzle/guzzle/pull/1389 +* Bug fix: Fix sleep calculation when waiting for delayed requests. + https://github.com/guzzle/guzzle/pull/1324 +* Feature: More flexible history containers. + https://github.com/guzzle/guzzle/pull/1373 +* Bug fix: defer sink stream opening in StreamHandler. + https://github.com/guzzle/guzzle/pull/1377 +* Bug fix: do not attempt to escape cookie values. + https://github.com/guzzle/guzzle/pull/1406 +* Feature: report original content encoding and length on decoded responses. + https://github.com/guzzle/guzzle/pull/1409 +* Bug fix: rewind seekable request bodies before dispatching to cURL. + https://github.com/guzzle/guzzle/pull/1422 +* Bug fix: provide an empty string to `http_build_query` for HHVM workaround. + https://github.com/guzzle/guzzle/pull/1367 + +## 6.1.1 - 2015-11-22 + +* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler + https://github.com/guzzle/guzzle/commit/911bcbc8b434adce64e223a6d1d14e9a8f63e4e4 +* Feature: HandlerStack is now more generic. + https://github.com/guzzle/guzzle/commit/f2102941331cda544745eedd97fc8fd46e1ee33e +* Bug fix: setting verify to false in the StreamHandler now disables peer + verification. https://github.com/guzzle/guzzle/issues/1256 +* Feature: Middleware now uses an exception factory, including more error + context. https://github.com/guzzle/guzzle/pull/1282 +* Feature: better support for disabled functions. + https://github.com/guzzle/guzzle/pull/1287 +* Bug fix: fixed regression where MockHandler was not using `sink`. + https://github.com/guzzle/guzzle/pull/1292 + +## 6.1.0 - 2015-09-08 + +* Feature: Added the `on_stats` request option to provide access to transfer + statistics for requests. https://github.com/guzzle/guzzle/pull/1202 +* Feature: Added the ability to persist session cookies in CookieJars. + https://github.com/guzzle/guzzle/pull/1195 +* Feature: Some compatibility updates for Google APP Engine + https://github.com/guzzle/guzzle/pull/1216 +* Feature: Added support for NO_PROXY to prevent the use of a proxy based on + a simple set of rules. https://github.com/guzzle/guzzle/pull/1197 +* Feature: Cookies can now contain square brackets. + https://github.com/guzzle/guzzle/pull/1237 +* Bug fix: Now correctly parsing `=` inside of quotes in Cookies. + https://github.com/guzzle/guzzle/pull/1232 +* Bug fix: Cusotm cURL options now correctly override curl options of the + same name. https://github.com/guzzle/guzzle/pull/1221 +* Bug fix: Content-Type header is now added when using an explicitly provided + multipart body. https://github.com/guzzle/guzzle/pull/1218 +* Bug fix: Now ignoring Set-Cookie headers that have no name. +* Bug fix: Reason phrase is no longer cast to an int in some cases in the + cURL handler. https://github.com/guzzle/guzzle/pull/1187 +* Bug fix: Remove the Authorization header when redirecting if the Host + header changes. https://github.com/guzzle/guzzle/pull/1207 +* Bug fix: Cookie path matching fixes + https://github.com/guzzle/guzzle/issues/1129 +* Bug fix: Fixing the cURL `body_as_string` setting + https://github.com/guzzle/guzzle/pull/1201 +* Bug fix: quotes are no longer stripped when parsing cookies. + https://github.com/guzzle/guzzle/issues/1172 +* Bug fix: `form_params` and `query` now always uses the `&` separator. + https://github.com/guzzle/guzzle/pull/1163 +* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set. + https://github.com/guzzle/guzzle/pull/1189 + +## 6.0.2 - 2015-07-04 + +* Fixed a memory leak in the curl handlers in which references to callbacks + were not being removed by `curl_reset`. +* Cookies are now extracted properly before redirects. +* Cookies now allow more character ranges. +* Decoded Content-Encoding responses are now modified to correctly reflect + their state if the encoding was automatically removed by a handler. This + means that the `Content-Encoding` header may be removed an the + `Content-Length` modified to reflect the message size after removing the + encoding. +* Added a more explicit error message when trying to use `form_params` and + `multipart` in the same request. +* Several fixes for HHVM support. +* Functions are now conditionally required using an additional level of + indirection to help with global Composer installations. + +## 6.0.1 - 2015-05-27 + +* Fixed a bug with serializing the `query` request option where the `&` + separator was missing. +* Added a better error message for when `body` is provided as an array. Please + use `form_params` or `multipart` instead. +* Various doc fixes. + +## 6.0.0 - 2015-05-26 + +* See the UPGRADING.md document for more information. +* Added `multipart` and `form_params` request options. +* Added `synchronous` request option. +* Added the `on_headers` request option. +* Fixed `expect` handling. +* No longer adding default middlewares in the client ctor. These need to be + present on the provided handler in order to work. +* Requests are no longer initiated when sending async requests with the + CurlMultiHandler. This prevents unexpected recursion from requests completing + while ticking the cURL loop. +* Removed the semantics of setting `default` to `true`. This is no longer + required now that the cURL loop is not ticked for async requests. +* Added request and response logging middleware. +* No longer allowing self signed certificates when using the StreamHandler. +* Ensuring that `sink` is valid if saving to a file. +* Request exceptions now include a "handler context" which provides handler + specific contextual information. +* Added `GuzzleHttp\RequestOptions` to allow request options to be applied + using constants. +* `$maxHandles` has been removed from CurlMultiHandler. +* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package. + +## 5.3.0 - 2015-05-19 + +* Mock now supports `save_to` +* Marked `AbstractRequestEvent::getTransaction()` as public. +* Fixed a bug in which multiple headers using different casing would overwrite + previous headers in the associative array. +* Added `Utils::getDefaultHandler()` +* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated. +* URL scheme is now always lowercased. + +## 6.0.0-beta.1 + +* Requires PHP >= 5.5 +* Updated to use PSR-7 + * Requires immutable messages, which basically means an event based system + owned by a request instance is no longer possible. + * Utilizing the [Guzzle PSR-7 package](https://github.com/guzzle/psr7). + * Removed the dependency on `guzzlehttp/streams`. These stream abstractions + are available in the `guzzlehttp/psr7` package under the `GuzzleHttp\Psr7` + namespace. +* Added middleware and handler system + * Replaced the Guzzle event and subscriber system with a middleware system. + * No longer depends on RingPHP, but rather places the HTTP handlers directly + in Guzzle, operating on PSR-7 messages. + * Retry logic is now encapsulated in `GuzzleHttp\Middleware::retry`, which + means the `guzzlehttp/retry-subscriber` is now obsolete. + * Mocking responses is now handled using `GuzzleHttp\Handler\MockHandler`. +* Asynchronous responses + * No longer supports the `future` request option to send an async request. + Instead, use one of the `*Async` methods of a client (e.g., `requestAsync`, + `getAsync`, etc.). + * Utilizing `GuzzleHttp\Promise` instead of React's promise library to avoid + recursion required by chaining and forwarding react promises. See + https://github.com/guzzle/promises + * Added `requestAsync` and `sendAsync` to send request asynchronously. + * Added magic methods for `getAsync()`, `postAsync()`, etc. to send requests + asynchronously. +* Request options + * POST and form updates + * Added the `form_fields` and `form_files` request options. + * Removed the `GuzzleHttp\Post` namespace. + * The `body` request option no longer accepts an array for POST requests. + * The `exceptions` request option has been deprecated in favor of the + `http_errors` request options. + * The `save_to` request option has been deprecated in favor of `sink` request + option. +* Clients no longer accept an array of URI template string and variables for + URI variables. You will need to expand URI templates before passing them + into a client constructor or request method. +* Client methods `get()`, `post()`, `put()`, `patch()`, `options()`, etc. are + now magic methods that will send synchronous requests. +* Replaced `Utils.php` with plain functions in `functions.php`. +* Removed `GuzzleHttp\Collection`. +* Removed `GuzzleHttp\BatchResults`. Batched pool results are now returned as + an array. +* Removed `GuzzleHttp\Query`. Query string handling is now handled using an + associative array passed into the `query` request option. The query string + is serialized using PHP's `http_build_query`. If you need more control, you + can pass the query string in as a string. +* `GuzzleHttp\QueryParser` has been replaced with the + `GuzzleHttp\Psr7\parse_query`. + +## 5.2.0 - 2015-01-27 + +* Added `AppliesHeadersInterface` to make applying headers to a request based + on the body more generic and not specific to `PostBodyInterface`. +* Reduced the number of stack frames needed to send requests. +* Nested futures are now resolved in the client rather than the RequestFsm +* Finishing state transitions is now handled in the RequestFsm rather than the + RingBridge. +* Added a guard in the Pool class to not use recursion for request retries. + +## 5.1.0 - 2014-12-19 + +* Pool class no longer uses recursion when a request is intercepted. +* The size of a Pool can now be dynamically adjusted using a callback. + See https://github.com/guzzle/guzzle/pull/943. +* Setting a request option to `null` when creating a request with a client will + ensure that the option is not set. This allows you to overwrite default + request options on a per-request basis. + See https://github.com/guzzle/guzzle/pull/937. +* Added the ability to limit which protocols are allowed for redirects by + specifying a `protocols` array in the `allow_redirects` request option. +* Nested futures due to retries are now resolved when waiting for synchronous + responses. See https://github.com/guzzle/guzzle/pull/947. +* `"0"` is now an allowed URI path. See + https://github.com/guzzle/guzzle/pull/935. +* `Query` no longer typehints on the `$query` argument in the constructor, + allowing for strings and arrays. +* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle + specific exceptions if necessary. + +## 5.0.3 - 2014-11-03 + +This change updates query strings so that they are treated as un-encoded values +by default where the value represents an un-encoded value to send over the +wire. A Query object then encodes the value before sending over the wire. This +means that even value query string values (e.g., ":") are url encoded. This +makes the Query class match PHP's http_build_query function. However, if you +want to send requests over the wire using valid query string characters that do +not need to be encoded, then you can provide a string to Url::setQuery() and +pass true as the second argument to specify that the query string is a raw +string that should not be parsed or encoded (unless a call to getQuery() is +subsequently made, forcing the query-string to be converted into a Query +object). + +## 5.0.2 - 2014-10-30 + +* Added a trailing `\r\n` to multipart/form-data payloads. See + https://github.com/guzzle/guzzle/pull/871 +* Added a `GuzzleHttp\Pool::send()` convenience method to match the docs. +* Status codes are now returned as integers. See + https://github.com/guzzle/guzzle/issues/881 +* No longer overwriting an existing `application/x-www-form-urlencoded` header + when sending POST requests, allowing for customized headers. See + https://github.com/guzzle/guzzle/issues/877 +* Improved path URL serialization. + + * No longer double percent-encoding characters in the path or query string if + they are already encoded. + * Now properly encoding the supplied path to a URL object, instead of only + encoding ' ' and '?'. + * Note: This has been changed in 5.0.3 to now encode query string values by + default unless the `rawString` argument is provided when setting the query + string on a URL: Now allowing many more characters to be present in the + query string without being percent encoded. See https://tools.ietf.org/html/rfc3986#appendix-A + +## 5.0.1 - 2014-10-16 + +Bugfix release. + +* Fixed an issue where connection errors still returned response object in + error and end events event though the response is unusable. This has been + corrected so that a response is not returned in the `getResponse` method of + these events if the response did not complete. https://github.com/guzzle/guzzle/issues/867 +* Fixed an issue where transfer statistics were not being populated in the + RingBridge. https://github.com/guzzle/guzzle/issues/866 + +## 5.0.0 - 2014-10-12 + +Adding support for non-blocking responses and some minor API cleanup. + +### New Features + +* Added support for non-blocking responses based on `guzzlehttp/guzzle-ring`. +* Added a public API for creating a default HTTP adapter. +* Updated the redirect plugin to be non-blocking so that redirects are sent + concurrently. Other plugins like this can now be updated to be non-blocking. +* Added a "progress" event so that you can get upload and download progress + events. +* Added `GuzzleHttp\Pool` which implements FutureInterface and transfers + requests concurrently using a capped pool size as efficiently as possible. +* Added `hasListeners()` to EmitterInterface. +* Removed `GuzzleHttp\ClientInterface::sendAll` and marked + `GuzzleHttp\Client::sendAll` as deprecated (it's still there, just not the + recommended way). + +### Breaking changes + +The breaking changes in this release are relatively minor. The biggest thing to +look out for is that request and response objects no longer implement fluent +interfaces. + +* Removed the fluent interfaces (i.e., `return $this`) from requests, + responses, `GuzzleHttp\Collection`, `GuzzleHttp\Url`, + `GuzzleHttp\Query`, `GuzzleHttp\Post\PostBody`, and + `GuzzleHttp\Cookie\SetCookie`. This blog post provides a good outline of + why I did this: https://ocramius.github.io/blog/fluent-interfaces-are-evil/. + This also makes the Guzzle message interfaces compatible with the current + PSR-7 message proposal. +* Removed "functions.php", so that Guzzle is truly PSR-4 compliant. Except + for the HTTP request functions from function.php, these functions are now + implemented in `GuzzleHttp\Utils` using camelCase. `GuzzleHttp\json_decode` + moved to `GuzzleHttp\Utils::jsonDecode`. `GuzzleHttp\get_path` moved to + `GuzzleHttp\Utils::getPath`. `GuzzleHttp\set_path` moved to + `GuzzleHttp\Utils::setPath`. `GuzzleHttp\batch` should now be + `GuzzleHttp\Pool::batch`, which returns an `objectStorage`. Using functions.php + caused problems for many users: they aren't PSR-4 compliant, require an + explicit include, and needed an if-guard to ensure that the functions are not + declared multiple times. +* Rewrote adapter layer. + * Removing all classes from `GuzzleHttp\Adapter`, these are now + implemented as callables that are stored in `GuzzleHttp\Ring\Client`. + * Removed the concept of "parallel adapters". Sending requests serially or + concurrently is now handled using a single adapter. + * Moved `GuzzleHttp\Adapter\Transaction` to `GuzzleHttp\Transaction`. The + Transaction object now exposes the request, response, and client as public + properties. The getters and setters have been removed. +* Removed the "headers" event. This event was only useful for changing the + body a response once the headers of the response were known. You can implement + a similar behavior in a number of ways. One example might be to use a + FnStream that has access to the transaction being sent. For example, when the + first byte is written, you could check if the response headers match your + expectations, and if so, change the actual stream body that is being + written to. +* Removed the `asArray` parameter from + `GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header + value as an array, then use the newly added `getHeaderAsArray()` method of + `MessageInterface`. This change makes the Guzzle interfaces compatible with + the PSR-7 interfaces. +* `GuzzleHttp\Message\MessageFactory` no longer allows subclasses to add + custom request options using double-dispatch (this was an implementation + detail). Instead, you should now provide an associative array to the + constructor which is a mapping of the request option name mapping to a + function that applies the option value to a request. +* Removed the concept of "throwImmediately" from exceptions and error events. + This control mechanism was used to stop a transfer of concurrent requests + from completing. This can now be handled by throwing the exception or by + cancelling a pool of requests or each outstanding future request individually. +* Updated to "GuzzleHttp\Streams" 3.0. + * `GuzzleHttp\Stream\StreamInterface::getContents()` no longer accepts a + `maxLen` parameter. This update makes the Guzzle streams project + compatible with the current PSR-7 proposal. + * `GuzzleHttp\Stream\Stream::__construct`, + `GuzzleHttp\Stream\Stream::factory`, and + `GuzzleHttp\Stream\Utils::create` no longer accept a size in the second + argument. They now accept an associative array of options, including the + "size" key and "metadata" key which can be used to provide custom metadata. + +## 4.2.2 - 2014-09-08 + +* Fixed a memory leak in the CurlAdapter when reusing cURL handles. +* No longer using `request_fulluri` in stream adapter proxies. +* Relative redirects are now based on the last response, not the first response. + +## 4.2.1 - 2014-08-19 + +* Ensuring that the StreamAdapter does not always add a Content-Type header +* Adding automated github releases with a phar and zip + +## 4.2.0 - 2014-08-17 + +* Now merging in default options using a case-insensitive comparison. + Closes https://github.com/guzzle/guzzle/issues/767 +* Added the ability to automatically decode `Content-Encoding` response bodies + using the `decode_content` request option. This is set to `true` by default + to decode the response body if it comes over the wire with a + `Content-Encoding`. Set this value to `false` to disable decoding the + response content, and pass a string to provide a request `Accept-Encoding` + header and turn on automatic response decoding. This feature now allows you + to pass an `Accept-Encoding` header in the headers of a request but still + disable automatic response decoding. + Closes https://github.com/guzzle/guzzle/issues/764 +* Added the ability to throw an exception immediately when transferring + requests in parallel. Closes https://github.com/guzzle/guzzle/issues/760 +* Updating guzzlehttp/streams dependency to ~2.1 +* No longer utilizing the now deprecated namespaced methods from the stream + package. + +## 4.1.8 - 2014-08-14 + +* Fixed an issue in the CurlFactory that caused setting the `stream=false` + request option to throw an exception. + See: https://github.com/guzzle/guzzle/issues/769 +* TransactionIterator now calls rewind on the inner iterator. + See: https://github.com/guzzle/guzzle/pull/765 +* You can now set the `Content-Type` header to `multipart/form-data` + when creating POST requests to force multipart bodies. + See https://github.com/guzzle/guzzle/issues/768 + +## 4.1.7 - 2014-08-07 + +* Fixed an error in the HistoryPlugin that caused the same request and response + to be logged multiple times when an HTTP protocol error occurs. +* Ensuring that cURL does not add a default Content-Type when no Content-Type + has been supplied by the user. This prevents the adapter layer from modifying + the request that is sent over the wire after any listeners may have already + put the request in a desired state (e.g., signed the request). +* Throwing an exception when you attempt to send requests that have the + "stream" set to true in parallel using the MultiAdapter. +* Only calling curl_multi_select when there are active cURL handles. This was + previously changed and caused performance problems on some systems due to PHP + always selecting until the maximum select timeout. +* Fixed a bug where multipart/form-data POST fields were not correctly + aggregated (e.g., values with "&"). + +## 4.1.6 - 2014-08-03 + +* Added helper methods to make it easier to represent messages as strings, + including getting the start line and getting headers as a string. + +## 4.1.5 - 2014-08-02 + +* Automatically retrying cURL "Connection died, retrying a fresh connect" + errors when possible. +* cURL implementation cleanup +* Allowing multiple event subscriber listeners to be registered per event by + passing an array of arrays of listener configuration. + +## 4.1.4 - 2014-07-22 + +* Fixed a bug that caused multi-part POST requests with more than one field to + serialize incorrectly. +* Paths can now be set to "0" +* `ResponseInterface::xml` now accepts a `libxml_options` option and added a + missing default argument that was required when parsing XML response bodies. +* A `save_to` stream is now created lazily, which means that files are not + created on disk unless a request succeeds. + +## 4.1.3 - 2014-07-15 + +* Various fixes to multipart/form-data POST uploads +* Wrapping function.php in an if-statement to ensure Guzzle can be used + globally and in a Composer install +* Fixed an issue with generating and merging in events to an event array +* POST headers are only applied before sending a request to allow you to change + the query aggregator used before uploading +* Added much more robust query string parsing +* Fixed various parsing and normalization issues with URLs +* Fixing an issue where multi-valued headers were not being utilized correctly + in the StreamAdapter + +## 4.1.2 - 2014-06-18 + +* Added support for sending payloads with GET requests + +## 4.1.1 - 2014-06-08 + +* Fixed an issue related to using custom message factory options in subclasses +* Fixed an issue with nested form fields in a multi-part POST +* Fixed an issue with using the `json` request option for POST requests +* Added `ToArrayInterface` to `GuzzleHttp\Cookie\CookieJar` + +## 4.1.0 - 2014-05-27 + +* Added a `json` request option to easily serialize JSON payloads. +* Added a `GuzzleHttp\json_decode()` wrapper to safely parse JSON. +* Added `setPort()` and `getPort()` to `GuzzleHttp\Message\RequestInterface`. +* Added the ability to provide an emitter to a client in the client constructor. +* Added the ability to persist a cookie session using $_SESSION. +* Added a trait that can be used to add event listeners to an iterator. +* Removed request method constants from RequestInterface. +* Fixed warning when invalid request start-lines are received. +* Updated MessageFactory to work with custom request option methods. +* Updated cacert bundle to latest build. + +4.0.2 (2014-04-16) +------------------ + +* Proxy requests using the StreamAdapter now properly use request_fulluri (#632) +* Added the ability to set scalars as POST fields (#628) + +## 4.0.1 - 2014-04-04 + +* The HTTP status code of a response is now set as the exception code of + RequestException objects. +* 303 redirects will now correctly switch from POST to GET requests. +* The default parallel adapter of a client now correctly uses the MultiAdapter. +* HasDataTrait now initializes the internal data array as an empty array so + that the toArray() method always returns an array. + +## 4.0.0 - 2014-03-29 + +* For information on changes and upgrading, see: + https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 +* Added `GuzzleHttp\batch()` as a convenience function for sending requests in + parallel without needing to write asynchronous code. +* Restructured how events are added to `GuzzleHttp\ClientInterface::sendAll()`. + You can now pass a callable or an array of associative arrays where each + associative array contains the "fn", "priority", and "once" keys. + +## 4.0.0.rc-2 - 2014-03-25 + +* Removed `getConfig()` and `setConfig()` from clients to avoid confusion + around whether things like base_url, message_factory, etc. should be able to + be retrieved or modified. +* Added `getDefaultOption()` and `setDefaultOption()` to ClientInterface +* functions.php functions were renamed using snake_case to match PHP idioms +* Added support for `HTTP_PROXY`, `HTTPS_PROXY`, and + `GUZZLE_CURL_SELECT_TIMEOUT` environment variables +* Added the ability to specify custom `sendAll()` event priorities +* Added the ability to specify custom stream context options to the stream + adapter. +* Added a functions.php function for `get_path()` and `set_path()` +* CurlAdapter and MultiAdapter now use a callable to generate curl resources +* MockAdapter now properly reads a body and emits a `headers` event +* Updated Url class to check if a scheme and host are set before adding ":" + and "//". This allows empty Url (e.g., "") to be serialized as "". +* Parsing invalid XML no longer emits warnings +* Curl classes now properly throw AdapterExceptions +* Various performance optimizations +* Streams are created with the faster `Stream\create()` function +* Marked deprecation_proxy() as internal +* Test server is now a collection of static methods on a class + +## 4.0.0-rc.1 - 2014-03-15 + +* See https://github.com/guzzle/guzzle/blob/master/UPGRADING.md#3x-to-40 + +## 3.8.1 - 2014-01-28 + +* Bug: Always using GET requests when redirecting from a 303 response +* Bug: CURLOPT_SSL_VERIFYHOST is now correctly set to false when setting `$certificateAuthority` to false in + `Guzzle\Http\ClientInterface::setSslVerification()` +* Bug: RedirectPlugin now uses strict RFC 3986 compliance when combining a base URL with a relative URL +* Bug: The body of a request can now be set to `"0"` +* Sending PHP stream requests no longer forces `HTTP/1.0` +* Adding more information to ExceptionCollection exceptions so that users have more context, including a stack trace of + each sub-exception +* Updated the `$ref` attribute in service descriptions to merge over any existing parameters of a schema (rather than + clobbering everything). +* Merging URLs will now use the query string object from the relative URL (thus allowing custom query aggregators) +* Query strings are now parsed in a way that they do no convert empty keys with no value to have a dangling `=`. + For example `foo&bar=baz` is now correctly parsed and recognized as `foo&bar=baz` rather than `foo=&bar=baz`. +* Now properly escaping the regular expression delimiter when matching Cookie domains. +* Network access is now disabled when loading XML documents + +## 3.8.0 - 2013-12-05 + +* Added the ability to define a POST name for a file +* JSON response parsing now properly walks additionalProperties +* cURL error code 18 is now retried automatically in the BackoffPlugin +* Fixed a cURL error when URLs contain fragments +* Fixed an issue in the BackoffPlugin retry event where it was trying to access all exceptions as if they were + CurlExceptions +* CURLOPT_PROGRESS function fix for PHP 5.5 (69fcc1e) +* Added the ability for Guzzle to work with older versions of cURL that do not support `CURLOPT_TIMEOUT_MS` +* Fixed a bug that was encountered when parsing empty header parameters +* UriTemplate now has a `setRegex()` method to match the docs +* The `debug` request parameter now checks if it is truthy rather than if it exists +* Setting the `debug` request parameter to true shows verbose cURL output instead of using the LogPlugin +* Added the ability to combine URLs using strict RFC 3986 compliance +* Command objects can now return the validation errors encountered by the command +* Various fixes to cache revalidation (#437 and 29797e5) +* Various fixes to the AsyncPlugin +* Cleaned up build scripts + +## 3.7.4 - 2013-10-02 + +* Bug fix: 0 is now an allowed value in a description parameter that has a default value (#430) +* Bug fix: SchemaFormatter now returns an integer when formatting to a Unix timestamp + (see https://github.com/aws/aws-sdk-php/issues/147) +* Bug fix: Cleaned up and fixed URL dot segment removal to properly resolve internal dots +* Minimum PHP version is now properly specified as 5.3.3 (up from 5.3.2) (#420) +* Updated the bundled cacert.pem (#419) +* OauthPlugin now supports adding authentication to headers or query string (#425) + +## 3.7.3 - 2013-09-08 + +* Added the ability to get the exception associated with a request/command when using `MultiTransferException` and + `CommandTransferException`. +* Setting `additionalParameters` of a response to false is now honored when parsing responses with a service description +* Schemas are only injected into response models when explicitly configured. +* No longer guessing Content-Type based on the path of a request. Content-Type is now only guessed based on the path of + an EntityBody. +* Bug fix: ChunkedIterator can now properly chunk a \Traversable as well as an \Iterator. +* Bug fix: FilterIterator now relies on `\Iterator` instead of `\Traversable`. +* Bug fix: Gracefully handling malformed responses in RequestMediator::writeResponseBody() +* Bug fix: Replaced call to canCache with canCacheRequest in the CallbackCanCacheStrategy of the CachePlugin +* Bug fix: Visiting XML attributes first before visiting XML children when serializing requests +* Bug fix: Properly parsing headers that contain commas contained in quotes +* Bug fix: mimetype guessing based on a filename is now case-insensitive + +## 3.7.2 - 2013-08-02 + +* Bug fix: Properly URL encoding paths when using the PHP-only version of the UriTemplate expander + See https://github.com/guzzle/guzzle/issues/371 +* Bug fix: Cookie domains are now matched correctly according to RFC 6265 + See https://github.com/guzzle/guzzle/issues/377 +* Bug fix: GET parameters are now used when calculating an OAuth signature +* Bug fix: Fixed an issue with cache revalidation where the If-None-Match header was being double quoted +* `Guzzle\Common\AbstractHasDispatcher::dispatch()` now returns the event that was dispatched +* `Guzzle\Http\QueryString::factory()` now guesses the most appropriate query aggregator to used based on the input. + See https://github.com/guzzle/guzzle/issues/379 +* Added a way to add custom domain objects to service description parsing using the `operation.parse_class` event. See + https://github.com/guzzle/guzzle/pull/380 +* cURL multi cleanup and optimizations + +## 3.7.1 - 2013-07-05 + +* Bug fix: Setting default options on a client now works +* Bug fix: Setting options on HEAD requests now works. See #352 +* Bug fix: Moving stream factory before send event to before building the stream. See #353 +* Bug fix: Cookies no longer match on IP addresses per RFC 6265 +* Bug fix: Correctly parsing header parameters that are in `<>` and quotes +* Added `cert` and `ssl_key` as request options +* `Host` header can now diverge from the host part of a URL if the header is set manually +* `Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor` was rewritten to change from using SimpleXML to XMLWriter +* OAuth parameters are only added via the plugin if they aren't already set +* Exceptions are now thrown when a URL cannot be parsed +* Returning `false` if `Guzzle\Http\EntityBody::getContentMd5()` fails +* Not setting a `Content-MD5` on a command if calculating the Content-MD5 fails via the CommandContentMd5Plugin + +## 3.7.0 - 2013-06-10 + +* See UPGRADING.md for more information on how to upgrade. +* Requests now support the ability to specify an array of $options when creating a request to more easily modify a + request. You can pass a 'request.options' configuration setting to a client to apply default request options to + every request created by a client (e.g. default query string variables, headers, curl options, etc.). +* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`. + See `Guzzle\Http\StaticClient::mount`. +* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests + created by a command (e.g. custom headers, query string variables, timeout settings, etc.). +* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the + headers of a response +* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key + (e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`) +* ServiceBuilders now support storing and retrieving arbitrary data +* CachePlugin can now purge all resources for a given URI +* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource +* CachePlugin now uses the Vary header to determine if a resource is a cache hit +* `Guzzle\Http\Message\Response` now implements `\Serializable` +* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters +* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable +* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()` +* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size +* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message +* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older + Symfony users can still use the old version of Monolog. +* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`. + Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`. +* Several performance improvements to `Guzzle\Common\Collection` +* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +* Added `Guzzle\Stream\StreamInterface::isRepeatable` +* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + $client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`. +* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`. +* Removed `Guzzle\Http\ClientInterface::expandTemplate()` +* Removed `Guzzle\Http\ClientInterface::setRequestFactory()` +* Removed `Guzzle\Http\ClientInterface::getCurlMulti()` +* Removed `Guzzle\Http\Message\RequestInterface::canCache` +* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect` +* Removed `Guzzle\Http\Message\RequestInterface::isRedirect` +* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. +* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting + `Guzzle\Common\Version::$emitWarnings` to true. +* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use + `$request->getResponseBody()->isRepeatable()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use + `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. + These will work through Guzzle 4.0 +* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params]. +* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`. +* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. +* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +* Marked `Guzzle\Common\Collection::inject()` as deprecated. +* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');` +* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +* Always setting X-cache headers on cached responses +* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +* Added `CacheStorageInterface::purge($url)` +* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +## 3.6.0 - 2013-05-29 + +* ServiceDescription now implements ToArrayInterface +* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters +* Guzzle can now correctly parse incomplete URLs +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess +* Added the ability to cast Model objects to a string to view debug information. + +## 3.5.0 - 2013-05-13 + +* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times +* Bug: Better cleanup of one-time events across the board (when an event is meant to fire once, it will now remove + itself from the EventDispatcher) +* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values +* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too +* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a + non-existent key +* Bug: All __call() method arguments are now required (helps with mocking frameworks) +* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference + to help with refcount based garbage collection of resources created by sending a request +* Deprecating ZF1 cache and log adapters. These will be removed in the next major version. +* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it's deprecated). Use the + HistoryPlugin for a history. +* Added a `responseBody` alias for the `response_body` location +* Refactored internals to no longer rely on Response::getRequest() +* HistoryPlugin can now be cast to a string +* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests + and responses that are sent over the wire +* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects + +## 3.4.3 - 2013-04-30 + +* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response +* Added a check to re-extract the temp cacert bundle from the phar before sending each request + +## 3.4.2 - 2013-04-29 + +* Bug fix: Stream objects now work correctly with "a" and "a+" modes +* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present +* Bug fix: AsyncPlugin no longer forces HEAD requests +* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter +* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails +* Setting a response on a request will write to the custom request body from the response body if one is specified +* LogPlugin now writes to php://output when STDERR is undefined +* Added the ability to set multiple POST files for the same key in a single call +* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default +* Added the ability to queue CurlExceptions to the MockPlugin +* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send) +* Configuration loading now allows remote files + +## 3.4.1 - 2013-04-16 + +* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti + handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost. +* Exceptions are now properly grouped when sending requests in parallel +* Redirects are now properly aggregated when a multi transaction fails +* Redirects now set the response on the original object even in the event of a failure +* Bug fix: Model names are now properly set even when using $refs +* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax +* Added support for oauth_callback in OAuth signatures +* Added support for oauth_verifier in OAuth signatures +* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection + +## 3.4.0 - 2013-04-11 + +* Bug fix: URLs are now resolved correctly based on https://tools.ietf.org/html/rfc3986#section-5.2. #289 +* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289 +* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263 +* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264. +* Bug fix: Added `number` type to service descriptions. +* Bug fix: empty parameters are removed from an OAuth signature +* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header +* Bug fix: Fixed "array to string" error when validating a union of types in a service description +* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream +* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin. +* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs. +* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections. +* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if + the Content-Type can be determined based on the entity body or the path of the request. +* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder. +* Added support for a PSR-3 LogAdapter. +* Added a `command.after_prepare` event +* Added `oauth_callback` parameter to the OauthPlugin +* Added the ability to create a custom stream class when using a stream factory +* Added a CachingEntityBody decorator +* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized. +* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar. +* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies +* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This + means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use + POST fields or files (the latter is only used when emulating a form POST in the browser). +* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest + +## 3.3.1 - 2013-03-10 + +* Added the ability to create PHP streaming responses from HTTP requests +* Bug fix: Running any filters when parsing response headers with service descriptions +* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing +* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across + response location visitors. +* Bug fix: Removed the possibility of creating configuration files with circular dependencies +* RequestFactory::create() now uses the key of a POST file when setting the POST file name +* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set + +## 3.3.0 - 2013-03-03 + +* A large number of performance optimizations have been made +* Bug fix: Added 'wb' as a valid write mode for streams +* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned +* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()` +* BC: Removed `Guzzle\Http\Utils` class +* BC: Setting a service description on a client will no longer modify the client's command factories. +* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using + the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' +* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to + lowercase +* Operation parameter objects are now lazy loaded internally +* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses +* Added support for instantiating responseType=class responseClass classes. Classes must implement + `Guzzle\Service\Command\ResponseClassInterface` +* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These + additional properties also support locations and can be used to parse JSON responses where the outermost part of the + JSON is an array +* Added support for nested renaming of JSON models (rename sentAs to name) +* CachePlugin + * Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error + * Debug headers can now added to cached response in the CachePlugin + +## 3.2.0 - 2013-02-14 + +* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients. +* URLs with no path no longer contain a "/" by default +* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url. +* BadResponseException no longer includes the full request and response message +* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface +* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface +* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription +* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list +* xmlEncoding can now be customized for the XML declaration of a XML service description operation +* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value + aggregation and no longer uses callbacks +* The URL encoding implementation of Guzzle\Http\QueryString can now be customized +* Bug fix: Filters were not always invoked for array service description parameters +* Bug fix: Redirects now use a target response body rather than a temporary response body +* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded +* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives + +## 3.1.2 - 2013-01-27 + +* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the + response body. For example, the XmlVisitor now parses the XML response into an array in the before() method. +* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent +* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444) +* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse() +* Setting default headers on a client after setting the user-agent will not erase the user-agent setting + +## 3.1.1 - 2013-01-20 + +* Adding wildcard support to Guzzle\Common\Collection::getPath() +* Adding alias support to ServiceBuilder configs +* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface + +## 3.1.0 - 2013-01-12 + +* BC: CurlException now extends from RequestException rather than BadResponseException +* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse() +* Added getData to ServiceDescriptionInterface +* Added context array to RequestInterface::setState() +* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http +* Bug: Adding required content-type when JSON request visitor adds JSON to a command +* Bug: Fixing the serialization of a service description with custom data +* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing + an array of successful and failed responses +* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection +* Added Guzzle\Http\IoEmittingEntityBody +* Moved command filtration from validators to location visitors +* Added `extends` attributes to service description parameters +* Added getModels to ServiceDescriptionInterface + +## 3.0.7 - 2012-12-19 + +* Fixing phar detection when forcing a cacert to system if null or true +* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()` +* Cleaning up `Guzzle\Common\Collection::inject` method +* Adding a response_body location to service descriptions + +## 3.0.6 - 2012-12-09 + +* CurlMulti performance improvements +* Adding setErrorResponses() to Operation +* composer.json tweaks + +## 3.0.5 - 2012-11-18 + +* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin +* Bug: Response body can now be a string containing "0" +* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert +* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs +* Added support for XML attributes in service description responses +* DefaultRequestSerializer now supports array URI parameter values for URI template expansion +* Added better mimetype guessing to requests and post files + +## 3.0.4 - 2012-11-11 + +* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value +* Bug: Cookies can now be added that have a name, domain, or value set to "0" +* Bug: Using the system cacert bundle when using the Phar +* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures +* Enhanced cookie jar de-duplication +* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added +* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies +* Added the ability to create any sort of hash for a stream rather than just an MD5 hash + +## 3.0.3 - 2012-11-04 + +* Implementing redirects in PHP rather than cURL +* Added PECL URI template extension and using as default parser if available +* Bug: Fixed Content-Length parsing of Response factory +* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams. +* Adding ToArrayInterface throughout library +* Fixing OauthPlugin to create unique nonce values per request + +## 3.0.2 - 2012-10-25 + +* Magic methods are enabled by default on clients +* Magic methods return the result of a command +* Service clients no longer require a base_url option in the factory +* Bug: Fixed an issue with URI templates where null template variables were being expanded + +## 3.0.1 - 2012-10-22 + +* Models can now be used like regular collection objects by calling filter, map, etc. +* Models no longer require a Parameter structure or initial data in the constructor +* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator` + +## 3.0.0 - 2012-10-15 + +* Rewrote service description format to be based on Swagger + * Now based on JSON schema + * Added nested input structures and nested response models + * Support for JSON and XML input and output models + * Renamed `commands` to `operations` + * Removed dot class notation + * Removed custom types +* Broke the project into smaller top-level namespaces to be more component friendly +* Removed support for XML configs and descriptions. Use arrays or JSON files. +* Removed the Validation component and Inspector +* Moved all cookie code to Guzzle\Plugin\Cookie +* Magic methods on a Guzzle\Service\Client now return the command un-executed. +* Calling getResult() or getResponse() on a command will lazily execute the command if needed. +* Now shipping with cURL's CA certs and using it by default +* Added previousResponse() method to response objects +* No longer sending Accept and Accept-Encoding headers on every request +* Only sending an Expect header by default when a payload is greater than 1MB +* Added/moved client options: + * curl.blacklist to curl.option.blacklist + * Added ssl.certificate_authority +* Added a Guzzle\Iterator component +* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin +* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin) +* Added a more robust caching plugin +* Added setBody to response objects +* Updating LogPlugin to use a more flexible MessageFormatter +* Added a completely revamped build process +* Cleaning up Collection class and removing default values from the get method +* Fixed ZF2 cache adapters + +## 2.8.8 - 2012-10-15 + +* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did + +## 2.8.7 - 2012-09-30 + +* Bug: Fixed config file aliases for JSON includes +* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests +* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload +* Bug: Hardening request and response parsing to account for missing parts +* Bug: Fixed PEAR packaging +* Bug: Fixed Request::getInfo +* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail +* Adding the ability for the namespace Iterator factory to look in multiple directories +* Added more getters/setters/removers from service descriptions +* Added the ability to remove POST fields from OAuth signatures +* OAuth plugin now supports 2-legged OAuth + +## 2.8.6 - 2012-09-05 + +* Added the ability to modify and build service descriptions +* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command +* Added a `json` parameter location +* Now allowing dot notation for classes in the CacheAdapterFactory +* Using the union of two arrays rather than an array_merge when extending service builder services and service params +* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references + in service builder config files. +* Services defined in two different config files that include one another will by default replace the previously + defined service, but you can now create services that extend themselves and merge their settings over the previous +* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like + '_default' with a default JSON configuration file. + +## 2.8.5 - 2012-08-29 + +* Bug: Suppressed empty arrays from URI templates +* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching +* Added support for HTTP responses that do not contain a reason phrase in the start-line +* AbstractCommand commands are now invokable +* Added a way to get the data used when signing an Oauth request before a request is sent + +## 2.8.4 - 2012-08-15 + +* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin +* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable. +* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream +* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream +* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5()) +* Added additional response status codes +* Removed SSL information from the default User-Agent header +* DELETE requests can now send an entity body +* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries +* Added the ability of the MockPlugin to consume mocked request bodies +* LogPlugin now exposes request and response objects in the extras array + +## 2.8.3 - 2012-07-30 + +* Bug: Fixed a case where empty POST requests were sent as GET requests +* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body +* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new +* Added multiple inheritance to service description commands +* Added an ApiCommandInterface and added `getParamNames()` and `hasParam()` +* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything +* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles + +## 2.8.2 - 2012-07-24 + +* Bug: Query string values set to 0 are no longer dropped from the query string +* Bug: A Collection object is no longer created each time a call is made to `Guzzle\Service\Command\AbstractCommand::getRequestHeaders()` +* Bug: `+` is now treated as an encoded space when parsing query strings +* QueryString and Collection performance improvements +* Allowing dot notation for class paths in filters attribute of a service descriptions + +## 2.8.1 - 2012-07-16 + +* Loosening Event Dispatcher dependency +* POST redirects can now be customized using CURLOPT_POSTREDIR + +## 2.8.0 - 2012-07-15 + +* BC: Guzzle\Http\Query + * Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl) + * Changed isEncodingValues() and isEncodingFields() to isUrlEncoding() + * Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool) + * Changed the aggregation functions of QueryString to be static methods + * Can now use fromString() with querystrings that have a leading ? +* cURL configuration values can be specified in service descriptions using `curl.` prefixed parameters +* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body +* Cookies are no longer URL decoded by default +* Bug: URI template variables set to null are no longer expanded + +## 2.7.2 - 2012-07-02 + +* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser. +* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty() +* CachePlugin now allows for a custom request parameter function to check if a request can be cached +* Bug fix: CachePlugin now only caches GET and HEAD requests by default +* Bug fix: Using header glue when transferring headers over the wire +* Allowing deeply nested arrays for composite variables in URI templates +* Batch divisors can now return iterators or arrays + +## 2.7.1 - 2012-06-26 + +* Minor patch to update version number in UA string +* Updating build process + +## 2.7.0 - 2012-06-25 + +* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes. +* BC: Removed magic setX methods from commands +* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method +* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable. +* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity) +* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace +* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin +* Added the ability to set POST fields and files in a service description +* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method +* Adding a command.before_prepare event to clients +* Added BatchClosureTransfer and BatchClosureDivisor +* BatchTransferException now includes references to the batch divisor and transfer strategies +* Fixed some tests so that they pass more reliably +* Added Guzzle\Common\Log\ArrayLogAdapter + +## 2.6.6 - 2012-06-10 + +* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin +* BC: Removing Guzzle\Service\Command\CommandSet +* Adding generic batching system (replaces the batch queue plugin and command set) +* Updating ZF cache and log adapters and now using ZF's composer repository +* Bug: Setting the name of each ApiParam when creating through an ApiCommand +* Adding result_type, result_doc, deprecated, and doc_url to service descriptions +* Bug: Changed the default cookie header casing back to 'Cookie' + +## 2.6.5 - 2012-06-03 + +* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource() +* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from +* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data +* BC: Renaming methods in the CookieJarInterface +* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations +* Making the default glue for HTTP headers ';' instead of ',' +* Adding a removeValue to Guzzle\Http\Message\Header +* Adding getCookies() to request interface. +* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber() + +## 2.6.4 - 2012-05-30 + +* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class. +* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand +* Bug: Fixing magic method command calls on clients +* Bug: Email constraint only validates strings +* Bug: Aggregate POST fields when POST files are present in curl handle +* Bug: Fixing default User-Agent header +* Bug: Only appending or prepending parameters in commands if they are specified +* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes +* Allowing the use of dot notation for class namespaces when using instance_of constraint +* Added any_match validation constraint +* Added an AsyncPlugin +* Passing request object to the calculateWait method of the ExponentialBackoffPlugin +* Allowing the result of a command object to be changed +* Parsing location and type sub values when instantiating a service description rather than over and over at runtime + +## 2.6.3 - 2012-05-23 + +* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options. +* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields. +* You can now use an array of data when creating PUT request bodies in the request factory. +* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable. +* [Http] Adding support for Content-Type in multipart POST uploads per upload +* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1]) +* Adding more POST data operations for easier manipulation of POST data. +* You can now set empty POST fields. +* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files. +* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate. +* CS updates + +## 2.6.2 - 2012-05-19 + +* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method. + +## 2.6.1 - 2012-05-19 + +* [BC] Removing 'path' support in service descriptions. Use 'uri'. +* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache. +* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it. +* [BC] Removing Guzzle\Common\XmlElement. +* All commands, both dynamic and concrete, have ApiCommand objects. +* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits. +* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored. +* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible. + +## 2.6.0 - 2012-05-15 + +* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder +* [BC] Executing a Command returns the result of the command rather than the command +* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed. +* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args. +* [BC] Moving ResourceIterator* to Guzzle\Service\Resource +* [BC] Completely refactored ResourceIterators to iterate over a cloned command object +* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate +* [BC] Guzzle\Guzzle is now deprecated +* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject +* Adding Guzzle\Version class to give version information about Guzzle +* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate() +* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data +* ServiceDescription and ServiceBuilder are now cacheable using similar configs +* Changing the format of XML and JSON service builder configs. Backwards compatible. +* Cleaned up Cookie parsing +* Trimming the default Guzzle User-Agent header +* Adding a setOnComplete() method to Commands that is called when a command completes +* Keeping track of requests that were mocked in the MockPlugin +* Fixed a caching bug in the CacheAdapterFactory +* Inspector objects can be injected into a Command object +* Refactoring a lot of code and tests to be case insensitive when dealing with headers +* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL +* Adding the ability to set global option overrides to service builder configs +* Adding the ability to include other service builder config files from within XML and JSON files +* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method. + +## 2.5.0 - 2012-05-08 + +* Major performance improvements +* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated. +* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component. +* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}" +* Added the ability to passed parameters to all requests created by a client +* Added callback functionality to the ExponentialBackoffPlugin +* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies. +* Rewinding request stream bodies when retrying requests +* Exception is thrown when JSON response body cannot be decoded +* Added configurable magic method calls to clients and commands. This is off by default. +* Fixed a defect that added a hash to every parsed URL part +* Fixed duplicate none generation for OauthPlugin. +* Emitting an event each time a client is generated by a ServiceBuilder +* Using an ApiParams object instead of a Collection for parameters of an ApiCommand +* cache.* request parameters should be renamed to params.cache.* +* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc.). See CurlHandle. +* Added the ability to disable type validation of service descriptions +* ServiceDescriptions and ServiceBuilders are now Serializable diff --git a/lib/guzzlehttp/guzzle/LICENSE b/lib/guzzlehttp/guzzle/LICENSE new file mode 100644 index 00000000..fd2375d8 --- /dev/null +++ b/lib/guzzlehttp/guzzle/LICENSE @@ -0,0 +1,27 @@ +The MIT License (MIT) + +Copyright (c) 2011 Michael Dowling +Copyright (c) 2012 Jeremy Lindblom +Copyright (c) 2014 Graham Campbell +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Tobias Schultze +Copyright (c) 2016 Tobias Nyholm +Copyright (c) 2016 George Mponos + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/lib/guzzlehttp/guzzle/README.md b/lib/guzzlehttp/guzzle/README.md new file mode 100644 index 00000000..0025aa7a --- /dev/null +++ b/lib/guzzlehttp/guzzle/README.md @@ -0,0 +1,94 @@ +![Guzzle](.github/logo.png?raw=true) + +# Guzzle, PHP HTTP client + +[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases) +[![Build Status](https://img.shields.io/github/workflow/status/guzzle/guzzle/CI?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI) +[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle) + +Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and +trivial to integrate with web services. + +- Simple interface for building query strings, POST requests, streaming large + uploads, streaming large downloads, using HTTP cookies, uploading JSON data, + etc... +- Can send both synchronous and asynchronous requests using the same interface. +- Uses PSR-7 interfaces for requests, responses, and streams. This allows you + to utilize other PSR-7 compatible libraries with Guzzle. +- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients. +- Abstracts away the underlying HTTP transport, allowing you to write + environment and transport agnostic code; i.e., no hard dependency on cURL, + PHP streams, sockets, or non-blocking event loops. +- Middleware system allows you to augment and compose client behavior. + +```php +$client = new \GuzzleHttp\Client(); +$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); + +echo $response->getStatusCode(); // 200 +echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' +echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' + +// Send an asynchronous request. +$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org'); +$promise = $client->sendAsync($request)->then(function ($response) { + echo 'I completed! ' . $response->getBody(); +}); + +$promise->wait(); +``` + +## Help and docs + +We use GitHub issues only to discuss bugs and new features. For support please refer to: + +- [Documentation](http://guzzlephp.org/) +- [Stack Overflow](http://stackoverflow.com/questions/tagged/guzzle) +- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](http://slack.httplug.io/) +- [Gitter](https://gitter.im/guzzle/guzzle) + + +## Installing Guzzle + +The recommended way to install Guzzle is through +[Composer](https://getcomposer.org/). + +```bash +composer require guzzlehttp/guzzle +``` + + +## Version Guidance + +| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version | +|---------|------------|---------------------|--------------|---------------------|---------------------|-------|-------------| +| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >= 5.3.3 | +| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >= 5.4 | +| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >= 5.4 | +| 6.x | Security fixes | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >= 5.5 | +| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >= 7.2 | + +[guzzle-3-repo]: https://github.com/guzzle/guzzle3 +[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x +[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3 +[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5 +[guzzle-7-repo]: https://github.com/guzzle/guzzle +[guzzle-3-docs]: http://guzzle3.readthedocs.org +[guzzle-5-docs]: http://docs.guzzlephp.org/en/5.3/ +[guzzle-6-docs]: http://docs.guzzlephp.org/en/6.5/ +[guzzle-7-docs]: http://docs.guzzlephp.org/en/latest/ + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/lib/guzzlehttp/guzzle/UPGRADING.md b/lib/guzzlehttp/guzzle/UPGRADING.md new file mode 100644 index 00000000..45417a7e --- /dev/null +++ b/lib/guzzlehttp/guzzle/UPGRADING.md @@ -0,0 +1,1253 @@ +Guzzle Upgrade Guide +==================== + +6.0 to 7.0 +---------- + +In order to take advantage of the new features of PHP, Guzzle dropped the support +of PHP 5. The minimum supported PHP version is now PHP 7.2. Type hints and return +types for functions and methods have been added wherever possible. + +Please make sure: +- You are calling a function or a method with the correct type. +- If you extend a class of Guzzle; update all signatures on methods you override. + +#### Other backwards compatibility breaking changes + +- Class `GuzzleHttp\UriTemplate` is removed. +- Class `GuzzleHttp\Exception\SeekException` is removed. +- Classes `GuzzleHttp\Exception\BadResponseException`, `GuzzleHttp\Exception\ClientException`, + `GuzzleHttp\Exception\ServerException` can no longer be initialized with an empty + Response as argument. +- Class `GuzzleHttp\Exception\ConnectException` now extends `GuzzleHttp\Exception\TransferException` + instead of `GuzzleHttp\Exception\RequestException`. +- Function `GuzzleHttp\Exception\ConnectException::getResponse()` is removed. +- Function `GuzzleHttp\Exception\ConnectException::hasResponse()` is removed. +- Constant `GuzzleHttp\ClientInterface::VERSION` is removed. Added `GuzzleHttp\ClientInterface::MAJOR_VERSION` instead. +- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed. + Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative. +- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed. +- Request option `exception` is removed. Please use `http_errors`. +- Request option `save_to` is removed. Please use `sink`. +- Pool option `pool_size` is removed. Please use `concurrency`. +- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility. +- The `get`, `head`, `put`, `post`, `patch`, `delete`, `getAsync`, `headAsync`, `putAsync`, `postAsync`, `patchAsync`, and `deleteAsync` methods are now implemented as genuine methods on `GuzzleHttp\Client`, with strong typing. The original `__call` implementation remains unchanged for now, for maximum backwards compatibility, but won't be invoked under normal operation. +- The `log` middleware will log the errors with level `error` instead of `notice` +- Support for international domain names (IDN) is now disabled by default, and enabling it requires installing ext-intl, linked against a modern version of the C library (ICU 4.6 or higher). + +#### Native functions calls + +All internal native functions calls of Guzzle are now prefixed with a slash. This +change makes it impossible for method overloading by other libraries or applications. +Example: + +```php +// Before: +curl_version(); + +// After: +\curl_version(); +``` + +For the full diff you can check [here](https://github.com/guzzle/guzzle/compare/6.5.4..master). + +5.0 to 6.0 +---------- + +Guzzle now uses [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP messages. +Due to the fact that these messages are immutable, this prompted a refactoring +of Guzzle to use a middleware based system rather than an event system. Any +HTTP message interaction (e.g., `GuzzleHttp\Message\Request`) need to be +updated to work with the new immutable PSR-7 request and response objects. Any +event listeners or subscribers need to be updated to become middleware +functions that wrap handlers (or are injected into a +`GuzzleHttp\HandlerStack`). + +- Removed `GuzzleHttp\BatchResults` +- Removed `GuzzleHttp\Collection` +- Removed `GuzzleHttp\HasDataTrait` +- Removed `GuzzleHttp\ToArrayInterface` +- The `guzzlehttp/streams` dependency has been removed. Stream functionality + is now present in the `GuzzleHttp\Psr7` namespace provided by the + `guzzlehttp/psr7` package. +- Guzzle no longer uses ReactPHP promises and now uses the + `guzzlehttp/promises` library. We use a custom promise library for three + significant reasons: + 1. React promises (at the time of writing this) are recursive. Promise + chaining and promise resolution will eventually blow the stack. Guzzle + promises are not recursive as they use a sort of trampolining technique. + Note: there has been movement in the React project to modify promises to + no longer utilize recursion. + 2. Guzzle needs to have the ability to synchronously block on a promise to + wait for a result. Guzzle promises allows this functionality (and does + not require the use of recursion). + 3. Because we need to be able to wait on a result, doing so using React + promises requires wrapping react promises with RingPHP futures. This + overhead is no longer needed, reducing stack sizes, reducing complexity, + and improving performance. +- `GuzzleHttp\Mimetypes` has been moved to a function in + `GuzzleHttp\Psr7\mimetype_from_extension` and + `GuzzleHttp\Psr7\mimetype_from_filename`. +- `GuzzleHttp\Query` and `GuzzleHttp\QueryParser` have been removed. Query + strings must now be passed into request objects as strings, or provided to + the `query` request option when creating requests with clients. The `query` + option uses PHP's `http_build_query` to convert an array to a string. If you + need a different serialization technique, you will need to pass the query + string in as a string. There are a couple helper functions that will make + working with query strings easier: `GuzzleHttp\Psr7\parse_query` and + `GuzzleHttp\Psr7\build_query`. +- Guzzle no longer has a dependency on RingPHP. Due to the use of a middleware + system based on PSR-7, using RingPHP and it's middleware system as well adds + more complexity than the benefits it provides. All HTTP handlers that were + present in RingPHP have been modified to work directly with PSR-7 messages + and placed in the `GuzzleHttp\Handler` namespace. This significantly reduces + complexity in Guzzle, removes a dependency, and improves performance. RingPHP + will be maintained for Guzzle 5 support, but will no longer be a part of + Guzzle 6. +- As Guzzle now uses a middleware based systems the event system and RingPHP + integration has been removed. Note: while the event system has been removed, + it is possible to add your own type of event system that is powered by the + middleware system. + - Removed the `Event` namespace. + - Removed the `Subscriber` namespace. + - Removed `Transaction` class + - Removed `RequestFsm` + - Removed `RingBridge` + - `GuzzleHttp\Subscriber\Cookie` is now provided by + `GuzzleHttp\Middleware::cookies` + - `GuzzleHttp\Subscriber\HttpError` is now provided by + `GuzzleHttp\Middleware::httpError` + - `GuzzleHttp\Subscriber\History` is now provided by + `GuzzleHttp\Middleware::history` + - `GuzzleHttp\Subscriber\Mock` is now provided by + `GuzzleHttp\Handler\MockHandler` + - `GuzzleHttp\Subscriber\Prepare` is now provided by + `GuzzleHttp\PrepareBodyMiddleware` + - `GuzzleHttp\Subscriber\Redirect` is now provided by + `GuzzleHttp\RedirectMiddleware` +- Guzzle now uses `Psr\Http\Message\UriInterface` (implements in + `GuzzleHttp\Psr7\Uri`) for URI support. `GuzzleHttp\Url` is now gone. +- Static functions in `GuzzleHttp\Utils` have been moved to namespaced + functions under the `GuzzleHttp` namespace. This requires either a Composer + based autoloader or you to include functions.php. +- `GuzzleHttp\ClientInterface::getDefaultOption` has been renamed to + `GuzzleHttp\ClientInterface::getConfig`. +- `GuzzleHttp\ClientInterface::setDefaultOption` has been removed. +- The `json` and `xml` methods of response objects has been removed. With the + migration to strictly adhering to PSR-7 as the interface for Guzzle messages, + adding methods to message interfaces would actually require Guzzle messages + to extend from PSR-7 messages rather then work with them directly. + +## Migrating to middleware + +The change to PSR-7 unfortunately required significant refactoring to Guzzle +due to the fact that PSR-7 messages are immutable. Guzzle 5 relied on an event +system from plugins. The event system relied on mutability of HTTP messages and +side effects in order to work. With immutable messages, you have to change your +workflow to become more about either returning a value (e.g., functional +middlewares) or setting a value on an object. Guzzle v6 has chosen the +functional middleware approach. + +Instead of using the event system to listen for things like the `before` event, +you now create a stack based middleware function that intercepts a request on +the way in and the promise of the response on the way out. This is a much +simpler and more predictable approach than the event system and works nicely +with PSR-7 middleware. Due to the use of promises, the middleware system is +also asynchronous. + +v5: + +```php +use GuzzleHttp\Event\BeforeEvent; +$client = new GuzzleHttp\Client(); +// Get the emitter and listen to the before event. +$client->getEmitter()->on('before', function (BeforeEvent $e) { + // Guzzle v5 events relied on mutation + $e->getRequest()->setHeader('X-Foo', 'Bar'); +}); +``` + +v6: + +In v6, you can modify the request before it is sent using the `mapRequest` +middleware. The idiomatic way in v6 to modify the request/response lifecycle is +to setup a handler middleware stack up front and inject the handler into a +client. + +```php +use GuzzleHttp\Middleware; +// Create a handler stack that has all of the default middlewares attached +$handler = GuzzleHttp\HandlerStack::create(); +// Push the handler onto the handler stack +$handler->push(Middleware::mapRequest(function (RequestInterface $request) { + // Notice that we have to return a request object + return $request->withHeader('X-Foo', 'Bar'); +})); +// Inject the handler into the client +$client = new GuzzleHttp\Client(['handler' => $handler]); +``` + +## POST Requests + +This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params) +and `multipart` request options. `form_params` is an associative array of +strings or array of strings and is used to serialize an +`application/x-www-form-urlencoded` POST request. The +[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart) +option is now used to send a multipart/form-data POST request. + +`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add +POST files to a multipart/form-data request. + +The `body` option no longer accepts an array to send POST requests. Please use +`multipart` or `form_params` instead. + +The `base_url` option has been renamed to `base_uri`. + +4.x to 5.0 +---------- + +## Rewritten Adapter Layer + +Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send +HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor +is still supported, but it has now been renamed to `handler`. Instead of +passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP +`callable` that follows the RingPHP specification. + +## Removed Fluent Interfaces + +[Fluent interfaces were removed](https://ocramius.github.io/blog/fluent-interfaces-are-evil/) +from the following classes: + +- `GuzzleHttp\Collection` +- `GuzzleHttp\Url` +- `GuzzleHttp\Query` +- `GuzzleHttp\Post\PostBody` +- `GuzzleHttp\Cookie\SetCookie` + +## Removed functions.php + +Removed "functions.php", so that Guzzle is truly PSR-4 compliant. The following +functions can be used as replacements. + +- `GuzzleHttp\json_decode` -> `GuzzleHttp\Utils::jsonDecode` +- `GuzzleHttp\get_path` -> `GuzzleHttp\Utils::getPath` +- `GuzzleHttp\Utils::setPath` -> `GuzzleHttp\set_path` +- `GuzzleHttp\Pool::batch` -> `GuzzleHttp\batch`. This function is, however, + deprecated in favor of using `GuzzleHttp\Pool::batch()`. + +The "procedural" global client has been removed with no replacement (e.g., +`GuzzleHttp\get()`, `GuzzleHttp\post()`, etc.). Use a `GuzzleHttp\Client` +object as a replacement. + +## `throwImmediately` has been removed + +The concept of "throwImmediately" has been removed from exceptions and error +events. This control mechanism was used to stop a transfer of concurrent +requests from completing. This can now be handled by throwing the exception or +by cancelling a pool of requests or each outstanding future request +individually. + +## headers event has been removed + +Removed the "headers" event. This event was only useful for changing the +body a response once the headers of the response were known. You can implement +a similar behavior in a number of ways. One example might be to use a +FnStream that has access to the transaction being sent. For example, when the +first byte is written, you could check if the response headers match your +expectations, and if so, change the actual stream body that is being +written to. + +## Updates to HTTP Messages + +Removed the `asArray` parameter from +`GuzzleHttp\Message\MessageInterface::getHeader`. If you want to get a header +value as an array, then use the newly added `getHeaderAsArray()` method of +`MessageInterface`. This change makes the Guzzle interfaces compatible with +the PSR-7 interfaces. + +3.x to 4.0 +---------- + +## Overarching changes: + +- Now requires PHP 5.4 or greater. +- No longer requires cURL to send requests. +- Guzzle no longer wraps every exception it throws. Only exceptions that are + recoverable are now wrapped by Guzzle. +- Various namespaces have been removed or renamed. +- No longer requiring the Symfony EventDispatcher. A custom event dispatcher + based on the Symfony EventDispatcher is + now utilized in `GuzzleHttp\Event\EmitterInterface` (resulting in significant + speed and functionality improvements). + +Changes per Guzzle 3.x namespace are described below. + +## Batch + +The `Guzzle\Batch` namespace has been removed. This is best left to +third-parties to implement on top of Guzzle's core HTTP library. + +## Cache + +The `Guzzle\Cache` namespace has been removed. (Todo: No suitable replacement +has been implemented yet, but hoping to utilize a PSR cache interface). + +## Common + +- Removed all of the wrapped exceptions. It's better to use the standard PHP + library for unrecoverable exceptions. +- `FromConfigInterface` has been removed. +- `Guzzle\Common\Version` has been removed. The VERSION constant can be found + at `GuzzleHttp\ClientInterface::VERSION`. + +### Collection + +- `getAll` has been removed. Use `toArray` to convert a collection to an array. +- `inject` has been removed. +- `keySearch` has been removed. +- `getPath` no longer supports wildcard expressions. Use something better like + JMESPath for this. +- `setPath` now supports appending to an existing array via the `[]` notation. + +### Events + +Guzzle no longer requires Symfony's EventDispatcher component. Guzzle now uses +`GuzzleHttp\Event\Emitter`. + +- `Symfony\Component\EventDispatcher\EventDispatcherInterface` is replaced by + `GuzzleHttp\Event\EmitterInterface`. +- `Symfony\Component\EventDispatcher\EventDispatcher` is replaced by + `GuzzleHttp\Event\Emitter`. +- `Symfony\Component\EventDispatcher\Event` is replaced by + `GuzzleHttp\Event\Event`, and Guzzle now has an EventInterface in + `GuzzleHttp\Event\EventInterface`. +- `AbstractHasDispatcher` has moved to a trait, `HasEmitterTrait`, and + `HasDispatcherInterface` has moved to `HasEmitterInterface`. Retrieving the + event emitter of a request, client, etc. now uses the `getEmitter` method + rather than the `getDispatcher` method. + +#### Emitter + +- Use the `once()` method to add a listener that automatically removes itself + the first time it is invoked. +- Use the `listeners()` method to retrieve a list of event listeners rather than + the `getListeners()` method. +- Use `emit()` instead of `dispatch()` to emit an event from an emitter. +- Use `attach()` instead of `addSubscriber()` and `detach()` instead of + `removeSubscriber()`. + +```php +$mock = new Mock(); +// 3.x +$request->getEventDispatcher()->addSubscriber($mock); +$request->getEventDispatcher()->removeSubscriber($mock); +// 4.x +$request->getEmitter()->attach($mock); +$request->getEmitter()->detach($mock); +``` + +Use the `on()` method to add a listener rather than the `addListener()` method. + +```php +// 3.x +$request->getEventDispatcher()->addListener('foo', function (Event $event) { /* ... */ } ); +// 4.x +$request->getEmitter()->on('foo', function (Event $event, $name) { /* ... */ } ); +``` + +## Http + +### General changes + +- The cacert.pem certificate has been moved to `src/cacert.pem`. +- Added the concept of adapters that are used to transfer requests over the + wire. +- Simplified the event system. +- Sending requests in parallel is still possible, but batching is no longer a + concept of the HTTP layer. Instead, you must use the `complete` and `error` + events to asynchronously manage parallel request transfers. +- `Guzzle\Http\Url` has moved to `GuzzleHttp\Url`. +- `Guzzle\Http\QueryString` has moved to `GuzzleHttp\Query`. +- QueryAggregators have been rewritten so that they are simply callable + functions. +- `GuzzleHttp\StaticClient` has been removed. Use the functions provided in + `functions.php` for an easy to use static client instance. +- Exceptions in `GuzzleHttp\Exception` have been updated to all extend from + `GuzzleHttp\Exception\TransferException`. + +### Client + +Calling methods like `get()`, `post()`, `head()`, etc. no longer create and +return a request, but rather creates a request, sends the request, and returns +the response. + +```php +// 3.0 +$request = $client->get('/'); +$response = $request->send(); + +// 4.0 +$response = $client->get('/'); + +// or, to mirror the previous behavior +$request = $client->createRequest('GET', '/'); +$response = $client->send($request); +``` + +`GuzzleHttp\ClientInterface` has changed. + +- The `send` method no longer accepts more than one request. Use `sendAll` to + send multiple requests in parallel. +- `setUserAgent()` has been removed. Use a default request option instead. You + could, for example, do something like: + `$client->setConfig('defaults/headers/User-Agent', 'Foo/Bar ' . $client::getDefaultUserAgent())`. +- `setSslVerification()` has been removed. Use default request options instead, + like `$client->setConfig('defaults/verify', true)`. + +`GuzzleHttp\Client` has changed. + +- The constructor now accepts only an associative array. You can include a + `base_url` string or array to use a URI template as the base URL of a client. + You can also specify a `defaults` key that is an associative array of default + request options. You can pass an `adapter` to use a custom adapter, + `batch_adapter` to use a custom adapter for sending requests in parallel, or + a `message_factory` to change the factory used to create HTTP requests and + responses. +- The client no longer emits a `client.create_request` event. +- Creating requests with a client no longer automatically utilize a URI + template. You must pass an array into a creational method (e.g., + `createRequest`, `get`, `put`, etc.) in order to expand a URI template. + +### Messages + +Messages no longer have references to their counterparts (i.e., a request no +longer has a reference to it's response, and a response no loger has a +reference to its request). This association is now managed through a +`GuzzleHttp\Adapter\TransactionInterface` object. You can get references to +these transaction objects using request events that are emitted over the +lifecycle of a request. + +#### Requests with a body + +- `GuzzleHttp\Message\EntityEnclosingRequest` and + `GuzzleHttp\Message\EntityEnclosingRequestInterface` have been removed. The + separation between requests that contain a body and requests that do not + contain a body has been removed, and now `GuzzleHttp\Message\RequestInterface` + handles both use cases. +- Any method that previously accepts a `GuzzleHttp\Response` object now accept a + `GuzzleHttp\Message\ResponseInterface`. +- `GuzzleHttp\Message\RequestFactoryInterface` has been renamed to + `GuzzleHttp\Message\MessageFactoryInterface`. This interface is used to create + both requests and responses and is implemented in + `GuzzleHttp\Message\MessageFactory`. +- POST field and file methods have been removed from the request object. You + must now use the methods made available to `GuzzleHttp\Post\PostBodyInterface` + to control the format of a POST body. Requests that are created using a + standard `GuzzleHttp\Message\MessageFactoryInterface` will automatically use + a `GuzzleHttp\Post\PostBody` body if the body was passed as an array or if + the method is POST and no body is provided. + +```php +$request = $client->createRequest('POST', '/'); +$request->getBody()->setField('foo', 'bar'); +$request->getBody()->addFile(new PostFile('file_key', fopen('/path/to/content', 'r'))); +``` + +#### Headers + +- `GuzzleHttp\Message\Header` has been removed. Header values are now simply + represented by an array of values or as a string. Header values are returned + as a string by default when retrieving a header value from a message. You can + pass an optional argument of `true` to retrieve a header value as an array + of strings instead of a single concatenated string. +- `GuzzleHttp\PostFile` and `GuzzleHttp\PostFileInterface` have been moved to + `GuzzleHttp\Post`. This interface has been simplified and now allows the + addition of arbitrary headers. +- Custom headers like `GuzzleHttp\Message\Header\Link` have been removed. Most + of the custom headers are now handled separately in specific + subscribers/plugins, and `GuzzleHttp\Message\HeaderValues::parseParams()` has + been updated to properly handle headers that contain parameters (like the + `Link` header). + +#### Responses + +- `GuzzleHttp\Message\Response::getInfo()` and + `GuzzleHttp\Message\Response::setInfo()` have been removed. Use the event + system to retrieve this type of information. +- `GuzzleHttp\Message\Response::getRawHeaders()` has been removed. +- `GuzzleHttp\Message\Response::getMessage()` has been removed. +- `GuzzleHttp\Message\Response::calculateAge()` and other cache specific + methods have moved to the CacheSubscriber. +- Header specific helper functions like `getContentMd5()` have been removed. + Just use `getHeader('Content-MD5')` instead. +- `GuzzleHttp\Message\Response::setRequest()` and + `GuzzleHttp\Message\Response::getRequest()` have been removed. Use the event + system to work with request and response objects as a transaction. +- `GuzzleHttp\Message\Response::getRedirectCount()` has been removed. Use the + Redirect subscriber instead. +- `GuzzleHttp\Message\Response::isSuccessful()` and other related methods have + been removed. Use `getStatusCode()` instead. + +#### Streaming responses + +Streaming requests can now be created by a client directly, returning a +`GuzzleHttp\Message\ResponseInterface` object that contains a body stream +referencing an open PHP HTTP stream. + +```php +// 3.0 +use Guzzle\Stream\PhpStreamRequestFactory; +$request = $client->get('/'); +$factory = new PhpStreamRequestFactory(); +$stream = $factory->fromRequest($request); +$data = $stream->read(1024); + +// 4.0 +$response = $client->get('/', ['stream' => true]); +// Read some data off of the stream in the response body +$data = $response->getBody()->read(1024); +``` + +#### Redirects + +The `configureRedirects()` method has been removed in favor of a +`allow_redirects` request option. + +```php +// Standard redirects with a default of a max of 5 redirects +$request = $client->createRequest('GET', '/', ['allow_redirects' => true]); + +// Strict redirects with a custom number of redirects +$request = $client->createRequest('GET', '/', [ + 'allow_redirects' => ['max' => 5, 'strict' => true] +]); +``` + +#### EntityBody + +EntityBody interfaces and classes have been removed or moved to +`GuzzleHttp\Stream`. All classes and interfaces that once required +`GuzzleHttp\EntityBodyInterface` now require +`GuzzleHttp\Stream\StreamInterface`. Creating a new body for a request no +longer uses `GuzzleHttp\EntityBody::factory` but now uses +`GuzzleHttp\Stream\Stream::factory` or even better: +`GuzzleHttp\Stream\create()`. + +- `Guzzle\Http\EntityBodyInterface` is now `GuzzleHttp\Stream\StreamInterface` +- `Guzzle\Http\EntityBody` is now `GuzzleHttp\Stream\Stream` +- `Guzzle\Http\CachingEntityBody` is now `GuzzleHttp\Stream\CachingStream` +- `Guzzle\Http\ReadLimitEntityBody` is now `GuzzleHttp\Stream\LimitStream` +- `Guzzle\Http\IoEmittyinEntityBody` has been removed. + +#### Request lifecycle events + +Requests previously submitted a large number of requests. The number of events +emitted over the lifecycle of a request has been significantly reduced to make +it easier to understand how to extend the behavior of a request. All events +emitted during the lifecycle of a request now emit a custom +`GuzzleHttp\Event\EventInterface` object that contains context providing +methods and a way in which to modify the transaction at that specific point in +time (e.g., intercept the request and set a response on the transaction). + +- `request.before_send` has been renamed to `before` and now emits a + `GuzzleHttp\Event\BeforeEvent` +- `request.complete` has been renamed to `complete` and now emits a + `GuzzleHttp\Event\CompleteEvent`. +- `request.sent` has been removed. Use `complete`. +- `request.success` has been removed. Use `complete`. +- `error` is now an event that emits a `GuzzleHttp\Event\ErrorEvent`. +- `request.exception` has been removed. Use `error`. +- `request.receive.status_line` has been removed. +- `curl.callback.progress` has been removed. Use a custom `StreamInterface` to + maintain a status update. +- `curl.callback.write` has been removed. Use a custom `StreamInterface` to + intercept writes. +- `curl.callback.read` has been removed. Use a custom `StreamInterface` to + intercept reads. + +`headers` is a new event that is emitted after the response headers of a +request have been received before the body of the response is downloaded. This +event emits a `GuzzleHttp\Event\HeadersEvent`. + +You can intercept a request and inject a response using the `intercept()` event +of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and +`GuzzleHttp\Event\ErrorEvent` event. + +See: http://docs.guzzlephp.org/en/latest/events.html + +## Inflection + +The `Guzzle\Inflection` namespace has been removed. This is not a core concern +of Guzzle. + +## Iterator + +The `Guzzle\Iterator` namespace has been removed. + +- `Guzzle\Iterator\AppendIterator`, `Guzzle\Iterator\ChunkedIterator`, and + `Guzzle\Iterator\MethodProxyIterator` are nice, but not a core requirement of + Guzzle itself. +- `Guzzle\Iterator\FilterIterator` is no longer needed because an equivalent + class is shipped with PHP 5.4. +- `Guzzle\Iterator\MapIterator` is not really needed when using PHP 5.5 because + it's easier to just wrap an iterator in a generator that maps values. + +For a replacement of these iterators, see https://github.com/nikic/iter + +## Log + +The LogPlugin has moved to https://github.com/guzzle/log-subscriber. The +`Guzzle\Log` namespace has been removed. Guzzle now relies on +`Psr\Log\LoggerInterface` for all logging. The MessageFormatter class has been +moved to `GuzzleHttp\Subscriber\Log\Formatter`. + +## Parser + +The `Guzzle\Parser` namespace has been removed. This was previously used to +make it possible to plug in custom parsers for cookies, messages, URI +templates, and URLs; however, this level of complexity is not needed in Guzzle +so it has been removed. + +- Cookie: Cookie parsing logic has been moved to + `GuzzleHttp\Cookie\SetCookie::fromString`. +- Message: Message parsing logic for both requests and responses has been moved + to `GuzzleHttp\Message\MessageFactory::fromMessage`. Message parsing is only + used in debugging or deserializing messages, so it doesn't make sense for + Guzzle as a library to add this level of complexity to parsing messages. +- UriTemplate: URI template parsing has been moved to + `GuzzleHttp\UriTemplate`. The Guzzle library will automatically use the PECL + URI template library if it is installed. +- Url: URL parsing is now performed in `GuzzleHttp\Url::fromString` (previously + it was `Guzzle\Http\Url::factory()`). If custom URL parsing is necessary, + then developers are free to subclass `GuzzleHttp\Url`. + +## Plugin + +The `Guzzle\Plugin` namespace has been renamed to `GuzzleHttp\Subscriber`. +Several plugins are shipping with the core Guzzle library under this namespace. + +- `GuzzleHttp\Subscriber\Cookie`: Replaces the old CookiePlugin. Cookie jar + code has moved to `GuzzleHttp\Cookie`. +- `GuzzleHttp\Subscriber\History`: Replaces the old HistoryPlugin. +- `GuzzleHttp\Subscriber\HttpError`: Throws errors when a bad HTTP response is + received. +- `GuzzleHttp\Subscriber\Mock`: Replaces the old MockPlugin. +- `GuzzleHttp\Subscriber\Prepare`: Prepares the body of a request just before + sending. This subscriber is attached to all requests by default. +- `GuzzleHttp\Subscriber\Redirect`: Replaces the RedirectPlugin. + +The following plugins have been removed (third-parties are free to re-implement +these if needed): + +- `GuzzleHttp\Plugin\Async` has been removed. +- `GuzzleHttp\Plugin\CurlAuth` has been removed. +- `GuzzleHttp\Plugin\ErrorResponse\ErrorResponsePlugin` has been removed. This + functionality should instead be implemented with event listeners that occur + after normal response parsing occurs in the guzzle/command package. + +The following plugins are not part of the core Guzzle package, but are provided +in separate repositories: + +- `Guzzle\Http\Plugin\BackoffPlugin` has been rewritten to be much simpler + to build custom retry policies using simple functions rather than various + chained classes. See: https://github.com/guzzle/retry-subscriber +- `Guzzle\Http\Plugin\Cache\CachePlugin` has moved to + https://github.com/guzzle/cache-subscriber +- `Guzzle\Http\Plugin\Log\LogPlugin` has moved to + https://github.com/guzzle/log-subscriber +- `Guzzle\Http\Plugin\Md5\Md5Plugin` has moved to + https://github.com/guzzle/message-integrity-subscriber +- `Guzzle\Http\Plugin\Mock\MockPlugin` has moved to + `GuzzleHttp\Subscriber\MockSubscriber`. +- `Guzzle\Http\Plugin\Oauth\OauthPlugin` has moved to + https://github.com/guzzle/oauth-subscriber + +## Service + +The service description layer of Guzzle has moved into two separate packages: + +- http://github.com/guzzle/command Provides a high level abstraction over web + services by representing web service operations using commands. +- http://github.com/guzzle/guzzle-services Provides an implementation of + guzzle/command that provides request serialization and response parsing using + Guzzle service descriptions. + +## Stream + +Stream have moved to a separate package available at +https://github.com/guzzle/streams. + +`Guzzle\Stream\StreamInterface` has been given a large update to cleanly take +on the responsibilities of `Guzzle\Http\EntityBody` and +`Guzzle\Http\EntityBodyInterface` now that they have been removed. The number +of methods implemented by the `StreamInterface` has been drastically reduced to +allow developers to more easily extend and decorate stream behavior. + +## Removed methods from StreamInterface + +- `getStream` and `setStream` have been removed to better encapsulate streams. +- `getMetadata` and `setMetadata` have been removed in favor of + `GuzzleHttp\Stream\MetadataStreamInterface`. +- `getWrapper`, `getWrapperData`, `getStreamType`, and `getUri` have all been + removed. This data is accessible when + using streams that implement `GuzzleHttp\Stream\MetadataStreamInterface`. +- `rewind` has been removed. Use `seek(0)` for a similar behavior. + +## Renamed methods + +- `detachStream` has been renamed to `detach`. +- `feof` has been renamed to `eof`. +- `ftell` has been renamed to `tell`. +- `readLine` has moved from an instance method to a static class method of + `GuzzleHttp\Stream\Stream`. + +## Metadata streams + +`GuzzleHttp\Stream\MetadataStreamInterface` has been added to denote streams +that contain additional metadata accessible via `getMetadata()`. +`GuzzleHttp\Stream\StreamInterface::getMetadata` and +`GuzzleHttp\Stream\StreamInterface::setMetadata` have been removed. + +## StreamRequestFactory + +The entire concept of the StreamRequestFactory has been removed. The way this +was used in Guzzle 3 broke the actual interface of sending streaming requests +(instead of getting back a Response, you got a StreamInterface). Streaming +PHP requests are now implemented through the `GuzzleHttp\Adapter\StreamAdapter`. + +3.6 to 3.7 +---------- + +### Deprecations + +- You can now enable E_USER_DEPRECATED warnings to see if you are using any deprecated methods.: + +```php +\Guzzle\Common\Version::$emitWarnings = true; +``` + +The following APIs and options have been marked as deprecated: + +- Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use `$request->getResponseBody()->isRepeatable()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use `Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead. +- Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead. +- Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated +- Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client. +- Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8. +- Marked `Guzzle\Common\Collection::inject()` as deprecated. +- Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use + `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` or + `$client->setDefaultOption('auth', array('user', 'pass', 'Basic|Digest|NTLM|Any'));` + +3.7 introduces `request.options` as a parameter for a client configuration and as an optional argument to all creational +request methods. When paired with a client's configuration settings, these options allow you to specify default settings +for various aspects of a request. Because these options make other previous configuration options redundant, several +configuration options and methods of a client and AbstractCommand have been deprecated. + +- Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use `$client->getDefaultOption('headers')`. +- Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use `$client->setDefaultOption('headers/{header_name}', 'value')`. +- Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use `$client->setDefaultOption('params/{param_name}', 'value')` +- Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand. These will work through Guzzle 4.0 + + $command = $client->getCommand('foo', array( + 'command.headers' => array('Test' => '123'), + 'command.response_body' => '/path/to/file' + )); + + // Should be changed to: + + $command = $client->getCommand('foo', array( + 'command.request_options' => array( + 'headers' => array('Test' => '123'), + 'save_as' => '/path/to/file' + ) + )); + +### Interface changes + +Additions and changes (you will need to update any implementations or subclasses you may have created): + +- Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`: + createRequest, head, delete, put, patch, post, options, prepareRequest +- Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()` +- Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface` +- Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to + `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a + resource, string, or EntityBody into the $options parameter to specify the download location of the response. +- Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a + default `array()` +- Added `Guzzle\Stream\StreamInterface::isRepeatable` +- Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods. + +The following methods were removed from interfaces. All of these methods are still available in the concrete classes +that implement them, but you should update your code to use alternative methods: + +- Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use + `$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or + `$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))` or + `$client->setDefaultOption('headers/{header_name}', 'value')`. or + `$client->setDefaultOption('headers', array('header_name' => 'value'))`. +- Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use `$client->getConfig()->getPath('request.options/headers')`. +- Removed `Guzzle\Http\ClientInterface::expandTemplate()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::setRequestFactory()`. This is an implementation detail. +- Removed `Guzzle\Http\ClientInterface::getCurlMulti()`. This is a very specific implementation detail. +- Removed `Guzzle\Http\Message\RequestInterface::canCache`. Use the CachePlugin. +- Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`. Use the HistoryPlugin. +- Removed `Guzzle\Http\Message\RequestInterface::isRedirect`. Use the HistoryPlugin. + +### Cache plugin breaking changes + +- CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a + CacheStorageInterface. These two objects and interface will be removed in a future version. +- Always setting X-cache headers on cached responses +- Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin +- `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface + $request, Response $response);` +- `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);` +- `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);` +- Added `CacheStorageInterface::purge($url)` +- `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin + $plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache, + CanCacheStrategyInterface $canCache = null)` +- Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)` + +3.5 to 3.6 +---------- + +* Mixed casing of headers are now forced to be a single consistent casing across all values for that header. +* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution +* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader(). + For example, setHeader() first removes the header using unset on a HeaderCollection and then calls addHeader(). + Keeping the Host header and URL host in sync is now handled by overriding the addHeader method in Request. +* Specific header implementations can be created for complex headers. When a message creates a header, it uses a + HeaderFactory which can map specific headers to specific header classes. There is now a Link header and + CacheControl header implementation. +* Moved getLinks() from Response to just be used on a Link header object. + +If you previously relied on Guzzle\Http\Message\Header::raw(), then you will need to update your code to use the +HeaderInterface (e.g. toArray(), getAll(), etc.). + +### Interface changes + +* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate +* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti() +* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in + Guzzle\Http\Curl\RequestMediator +* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string. +* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface +* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders() + +### Removed deprecated functions + +* Removed Guzzle\Parser\ParserRegister::get(). Use getParser() +* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser(). + +### Deprecations + +* The ability to case-insensitively search for header values +* Guzzle\Http\Message\Header::hasExactHeader +* Guzzle\Http\Message\Header::raw. Use getAll() +* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object + instead. + +### Other changes + +* All response header helper functions return a string rather than mixing Header objects and strings inconsistently +* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc. are managed by Guzzle + directly via interfaces +* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist + but are a no-op until removed. +* Most classes that used to require a `Guzzle\Service\Command\CommandInterface` typehint now request a + `Guzzle\Service\Command\ArrayCommandInterface`. +* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response + on a request while the request is still being transferred +* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess + +3.3 to 3.4 +---------- + +Base URLs of a client now follow the rules of https://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs. + +3.2 to 3.3 +---------- + +### Response::getEtag() quote stripping removed + +`Guzzle\Http\Message\Response::getEtag()` no longer strips quotes around the ETag response header + +### Removed `Guzzle\Http\Utils` + +The `Guzzle\Http\Utils` class was removed. This class was only used for testing. + +### Stream wrapper and type + +`Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getStreamType()` are no longer converted to lowercase. + +### curl.emit_io became emit_io + +Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using the +'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io' + +3.1 to 3.2 +---------- + +### CurlMulti is no longer reused globally + +Before 3.2, the same CurlMulti object was reused globally for each client. This can cause issue where plugins added +to a single client can pollute requests dispatched from other clients. + +If you still wish to reuse the same CurlMulti object with each client, then you can add a listener to the +ServiceBuilder's `service_builder.create_client` event to inject a custom CurlMulti object into each client as it is +created. + +```php +$multi = new Guzzle\Http\Curl\CurlMulti(); +$builder = Guzzle\Service\Builder\ServiceBuilder::factory('/path/to/config.json'); +$builder->addListener('service_builder.create_client', function ($event) use ($multi) { + $event['client']->setCurlMulti($multi); +} +}); +``` + +### No default path + +URLs no longer have a default path value of '/' if no path was specified. + +Before: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com/ +``` + +After: + +```php +$request = $client->get('http://www.foo.com'); +echo $request->getUrl(); +// >> http://www.foo.com +``` + +### Less verbose BadResponseException + +The exception message for `Guzzle\Http\Exception\BadResponseException` no longer contains the full HTTP request and +response information. You can, however, get access to the request and response object by calling `getRequest()` or +`getResponse()` on the exception object. + +### Query parameter aggregation + +Multi-valued query parameters are no longer aggregated using a callback function. `Guzzle\Http\Query` now has a +setAggregator() method that accepts a `Guzzle\Http\QueryAggregator\QueryAggregatorInterface` object. This object is +responsible for handling the aggregation of multi-valued query string variables into a flattened hash. + +2.8 to 3.x +---------- + +### Guzzle\Service\Inspector + +Change `\Guzzle\Service\Inspector::fromConfig` to `\Guzzle\Common\Collection::fromConfig` + +**Before** + +```php +use Guzzle\Service\Inspector; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Inspector::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +**After** + +```php +use Guzzle\Common\Collection; + +class YourClient extends \Guzzle\Service\Client +{ + public static function factory($config = array()) + { + $default = array(); + $required = array('base_url', 'username', 'api_key'); + $config = Collection::fromConfig($config, $default, $required); + + $client = new self( + $config->get('base_url'), + $config->get('username'), + $config->get('api_key') + ); + $client->setConfig($config); + + $client->setDescription(ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'client.json')); + + return $client; + } +``` + +### Convert XML Service Descriptions to JSON + +**Before** + +```xml + + + + + + Get a list of groups + + + Uses a search query to get a list of groups + + + + Create a group + + + + + Delete a group by ID + + + + + + + Update a group + + + + + + +``` + +**After** + +```json +{ + "name": "Zendesk REST API v2", + "apiVersion": "2012-12-31", + "description":"Provides access to Zendesk views, groups, tickets, ticket fields, and users", + "operations": { + "list_groups": { + "httpMethod":"GET", + "uri": "groups.json", + "summary": "Get a list of groups" + }, + "search_groups":{ + "httpMethod":"GET", + "uri": "search.json?query=\"{query} type:group\"", + "summary": "Uses a search query to get a list of groups", + "parameters":{ + "query":{ + "location": "uri", + "description":"Zendesk Search Query", + "type": "string", + "required": true + } + } + }, + "create_group": { + "httpMethod":"POST", + "uri": "groups.json", + "summary": "Create a group", + "parameters":{ + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + }, + "delete_group": { + "httpMethod":"DELETE", + "uri": "groups/{id}.json", + "summary": "Delete a group", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to delete by ID", + "type": "integer", + "required": true + } + } + }, + "get_group": { + "httpMethod":"GET", + "uri": "groups/{id}.json", + "summary": "Get a ticket", + "parameters":{ + "id":{ + "location": "uri", + "description":"Group to get by ID", + "type": "integer", + "required": true + } + } + }, + "update_group": { + "httpMethod":"PUT", + "uri": "groups/{id}.json", + "summary": "Update a group", + "parameters":{ + "id": { + "location": "uri", + "description":"Group to update by ID", + "type": "integer", + "required": true + }, + "data": { + "type": "array", + "location": "body", + "description":"Group JSON", + "filters": "json_encode", + "required": true + }, + "Content-Type":{ + "type": "string", + "location":"header", + "static": "application/json" + } + } + } +} +``` + +### Guzzle\Service\Description\ServiceDescription + +Commands are now called Operations + +**Before** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getCommands(); // @returns ApiCommandInterface[] +$sd->hasCommand($name); +$sd->getCommand($name); // @returns ApiCommandInterface|null +$sd->addCommand($command); // @param ApiCommandInterface $command +``` + +**After** + +```php +use Guzzle\Service\Description\ServiceDescription; + +$sd = new ServiceDescription(); +$sd->getOperations(); // @returns OperationInterface[] +$sd->hasOperation($name); +$sd->getOperation($name); // @returns OperationInterface|null +$sd->addOperation($operation); // @param OperationInterface $operation +``` + +### Guzzle\Common\Inflection\Inflector + +Namespace is now `Guzzle\Inflection\Inflector` + +### Guzzle\Http\Plugin + +Namespace is now `Guzzle\Plugin`. Many other changes occur within this namespace and are detailed in their own sections below. + +### Guzzle\Http\Plugin\LogPlugin and Guzzle\Common\Log + +Now `Guzzle\Plugin\Log\LogPlugin` and `Guzzle\Log` respectively. + +**Before** + +```php +use Guzzle\Common\Log\ClosureLogAdapter; +use Guzzle\Http\Plugin\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $verbosity is an integer indicating desired message verbosity level +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $verbosity = LogPlugin::LOG_VERBOSE); +``` + +**After** + +```php +use Guzzle\Log\ClosureLogAdapter; +use Guzzle\Log\MessageFormatter; +use Guzzle\Plugin\Log\LogPlugin; + +/** @var \Guzzle\Http\Client */ +$client; + +// $format is a string indicating desired message format -- @see MessageFormatter +$client->addSubscriber(new LogPlugin(new ClosureLogAdapter(function($m) { echo $m; }, $format = MessageFormatter::DEBUG_FORMAT); +``` + +### Guzzle\Http\Plugin\CurlAuthPlugin + +Now `Guzzle\Plugin\CurlAuth\CurlAuthPlugin`. + +### Guzzle\Http\Plugin\ExponentialBackoffPlugin + +Now `Guzzle\Plugin\Backoff\BackoffPlugin`, and other changes. + +**Before** + +```php +use Guzzle\Http\Plugin\ExponentialBackoffPlugin; + +$backoffPlugin = new ExponentialBackoffPlugin($maxRetries, array_merge( + ExponentialBackoffPlugin::getDefaultFailureCodes(), array(429) + )); + +$client->addSubscriber($backoffPlugin); +``` + +**After** + +```php +use Guzzle\Plugin\Backoff\BackoffPlugin; +use Guzzle\Plugin\Backoff\HttpBackoffStrategy; + +// Use convenient factory method instead -- see implementation for ideas of what +// you can do with chaining backoff strategies +$backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, array_merge( + HttpBackoffStrategy::getDefaultFailureCodes(), array(429) + )); +$client->addSubscriber($backoffPlugin); +``` + +### Known Issues + +#### [BUG] Accept-Encoding header behavior changed unintentionally. + +(See #217) (Fixed in 09daeb8c666fb44499a0646d655a8ae36456575e) + +In version 2.8 setting the `Accept-Encoding` header would set the CURLOPT_ENCODING option, which permitted cURL to +properly handle gzip/deflate compressed responses from the server. In versions affected by this bug this does not happen. +See issue #217 for a workaround, or use a version containing the fix. diff --git a/lib/guzzlehttp/guzzle/composer.json b/lib/guzzlehttp/guzzle/composer.json new file mode 100644 index 00000000..5d2025b9 --- /dev/null +++ b/lib/guzzlehttp/guzzle/composer.json @@ -0,0 +1,98 @@ +{ + "name": "guzzlehttp/guzzle", + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "framework", + "http", + "rest", + "web service", + "curl", + "client", + "HTTP client", + "PSR-7", + "PSR-18" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "ext-json": "*", + "guzzlehttp/promises": "^1.5", + "guzzlehttp/psr7": "^1.8.3 || ^2.1", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.2" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ext-curl": "*", + "bamarni/composer-bin-plugin": "^1.4.1", + "php-http/client-integration-tests": "^3.0", + "phpunit/phpunit": "^8.5.5 || ^9.3.5", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-master": "7.4-dev" + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\": "tests/" + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/BodySummarizer.php b/lib/guzzlehttp/guzzle/src/BodySummarizer.php new file mode 100644 index 00000000..6eca94ef --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/BodySummarizer.php @@ -0,0 +1,28 @@ +truncateAt = $truncateAt; + } + + /** + * Returns a summarized message body. + */ + public function summarize(MessageInterface $message): ?string + { + return $this->truncateAt === null + ? \GuzzleHttp\Psr7\Message::bodySummary($message) + : \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt); + } +} diff --git a/lib/guzzlehttp/guzzle/src/BodySummarizerInterface.php b/lib/guzzlehttp/guzzle/src/BodySummarizerInterface.php new file mode 100644 index 00000000..3e02e036 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/BodySummarizerInterface.php @@ -0,0 +1,13 @@ + 'http://www.foo.com/1.0/', + * 'timeout' => 0, + * 'allow_redirects' => false, + * 'proxy' => '192.168.16.1:10' + * ]); + * + * Client configuration settings include the following options: + * + * - handler: (callable) Function that transfers HTTP requests over the + * wire. The function is called with a Psr7\Http\Message\RequestInterface + * and array of transfer options, and must return a + * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a + * Psr7\Http\Message\ResponseInterface on success. + * If no handler is provided, a default handler will be created + * that enables all of the request options below by attaching all of the + * default middleware to the handler. + * - base_uri: (string|UriInterface) Base URI of the client that is merged + * into relative URIs. Can be a string or instance of UriInterface. + * - **: any request option + * + * @param array $config Client configuration settings. + * + * @see \GuzzleHttp\RequestOptions for a list of available request options. + */ + public function __construct(array $config = []) + { + if (!isset($config['handler'])) { + $config['handler'] = HandlerStack::create(); + } elseif (!\is_callable($config['handler'])) { + throw new InvalidArgumentException('handler must be a callable'); + } + + // Convert the base_uri to a UriInterface + if (isset($config['base_uri'])) { + $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']); + } + + $this->configureDefaults($config); + } + + /** + * @param string $method + * @param array $args + * + * @return PromiseInterface|ResponseInterface + * + * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0. + */ + public function __call($method, $args) + { + if (\count($args) < 1) { + throw new InvalidArgumentException('Magic request methods require a URI and optional options array'); + } + + $uri = $args[0]; + $opts = $args[1] ?? []; + + return \substr($method, -5) === 'Async' + ? $this->requestAsync(\substr($method, 0, -5), $uri, $opts) + : $this->request($method, $uri, $opts); + } + + /** + * Asynchronously send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + */ + public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface + { + // Merge the base URI into the request URI if needed. + $options = $this->prepareDefaults($options); + + return $this->transfer( + $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')), + $options + ); + } + + /** + * Send an HTTP request. + * + * @param array $options Request options to apply to the given + * request and to the transfer. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->sendAsync($request, $options)->wait(); + } + + /** + * The HttpClient PSR (PSR-18) specify this method. + * + * @inheritDoc + */ + public function sendRequest(RequestInterface $request): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + $options[RequestOptions::ALLOW_REDIRECTS] = false; + $options[RequestOptions::HTTP_ERRORS] = false; + + return $this->sendAsync($request, $options)->wait(); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + */ + public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface + { + $options = $this->prepareDefaults($options); + // Remove request modifying parameter because it can be done up-front. + $headers = $options['headers'] ?? []; + $body = $options['body'] ?? null; + $version = $options['version'] ?? '1.1'; + // Merge the URI into the base URI. + $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options); + if (\is_array($body)) { + throw $this->invalidBody(); + } + $request = new Psr7\Request($method, $uri, $headers, $body, $version); + // Remove the option so that they are not doubly-applied. + unset($options['headers'], $options['body'], $options['version']); + + return $this->transfer($request, $options); + } + + /** + * Create and send an HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string $method HTTP method. + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. See \GuzzleHttp\RequestOptions. + * + * @throws GuzzleException + */ + public function request(string $method, $uri = '', array $options = []): ResponseInterface + { + $options[RequestOptions::SYNCHRONOUS] = true; + return $this->requestAsync($method, $uri, $options)->wait(); + } + + /** + * Get a client configuration option. + * + * These options include default request options of the client, a "handler" + * (if utilized by the concrete client), and a "base_uri" if utilized by + * the concrete client. + * + * @param string|null $option The config option to retrieve. + * + * @return mixed + * + * @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0. + */ + public function getConfig(?string $option = null) + { + return $option === null + ? $this->config + : ($this->config[$option] ?? null); + } + + private function buildUri(UriInterface $uri, array $config): UriInterface + { + if (isset($config['base_uri'])) { + $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri); + } + + if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) { + $idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri; + } + + /** + * Configures the default options for a client. + */ + private function configureDefaults(array $config): void + { + $defaults = [ + 'allow_redirects' => RedirectMiddleware::$defaultSettings, + 'http_errors' => true, + 'decode_content' => true, + 'verify' => true, + 'cookies' => false, + 'idn_conversion' => false, + ]; + + // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set. + + // We can only trust the HTTP_PROXY environment variable in a CLI + // process due to the fact that PHP has no reliable mechanism to + // get environment variables that start with "HTTP_". + if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) { + $defaults['proxy']['http'] = $proxy; + } + + if ($proxy = Utils::getenv('HTTPS_PROXY')) { + $defaults['proxy']['https'] = $proxy; + } + + if ($noProxy = Utils::getenv('NO_PROXY')) { + $cleanedNoProxy = \str_replace(' ', '', $noProxy); + $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy); + } + + $this->config = $config + $defaults; + + if (!empty($config['cookies']) && $config['cookies'] === true) { + $this->config['cookies'] = new CookieJar(); + } + + // Add the default user-agent header. + if (!isset($this->config['headers'])) { + $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + } else { + // Add the User-Agent header if one was not already set. + foreach (\array_keys($this->config['headers']) as $name) { + if (\strtolower($name) === 'user-agent') { + return; + } + } + $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + } + } + + /** + * Merges default options into the array. + * + * @param array $options Options to modify by reference + */ + private function prepareDefaults(array $options): array + { + $defaults = $this->config; + + if (!empty($defaults['headers'])) { + // Default headers are only added if they are not present. + $defaults['_conditional'] = $defaults['headers']; + unset($defaults['headers']); + } + + // Special handling for headers is required as they are added as + // conditional headers and as headers passed to a request ctor. + if (\array_key_exists('headers', $options)) { + // Allows default headers to be unset. + if ($options['headers'] === null) { + $defaults['_conditional'] = []; + unset($options['headers']); + } elseif (!\is_array($options['headers'])) { + throw new InvalidArgumentException('headers must be an array'); + } + } + + // Shallow merge defaults underneath options. + $result = $options + $defaults; + + // Remove null values. + foreach ($result as $k => $v) { + if ($v === null) { + unset($result[$k]); + } + } + + return $result; + } + + /** + * Transfers the given request and applies request options. + * + * The URI of the request is not modified and the request options are used + * as-is without merging in default options. + * + * @param array $options See \GuzzleHttp\RequestOptions. + */ + private function transfer(RequestInterface $request, array $options): PromiseInterface + { + $request = $this->applyOptions($request, $options); + /** @var HandlerStack $handler */ + $handler = $options['handler']; + + try { + return P\Create::promiseFor($handler($request, $options)); + } catch (\Exception $e) { + return P\Create::rejectionFor($e); + } + } + + /** + * Applies the array of request options to a request. + */ + private function applyOptions(RequestInterface $request, array &$options): RequestInterface + { + $modify = [ + 'set_headers' => [], + ]; + + if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new InvalidArgumentException('The headers array must have header name as keys.'); + } + $modify['set_headers'] = $options['headers']; + unset($options['headers']); + } + + if (isset($options['form_params'])) { + if (isset($options['multipart'])) { + throw new InvalidArgumentException('You cannot use ' + . 'form_params and multipart at the same time. Use the ' + . 'form_params option if you want to send application/' + . 'x-www-form-urlencoded requests, and the multipart ' + . 'option to send multipart/form-data requests.'); + } + $options['body'] = \http_build_query($options['form_params'], '', '&'); + unset($options['form_params']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded'; + } + + if (isset($options['multipart'])) { + $options['body'] = new Psr7\MultipartStream($options['multipart']); + unset($options['multipart']); + } + + if (isset($options['json'])) { + $options['body'] = Utils::jsonEncode($options['json']); + unset($options['json']); + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'application/json'; + } + + if (!empty($options['decode_content']) + && $options['decode_content'] !== true + ) { + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']); + $modify['set_headers']['Accept-Encoding'] = $options['decode_content']; + } + + if (isset($options['body'])) { + if (\is_array($options['body'])) { + throw $this->invalidBody(); + } + $modify['body'] = Psr7\Utils::streamFor($options['body']); + unset($options['body']); + } + + if (!empty($options['auth']) && \is_array($options['auth'])) { + $value = $options['auth']; + $type = isset($value[2]) ? \strtolower($value[2]) : 'basic'; + switch ($type) { + case 'basic': + // Ensure that we don't have the header in different case and set the new value. + $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']); + $modify['set_headers']['Authorization'] = 'Basic ' + . \base64_encode("$value[0]:$value[1]"); + break; + case 'digest': + // @todo: Do not rely on curl + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + case 'ntlm': + $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM; + $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]"; + break; + } + } + + if (isset($options['query'])) { + $value = $options['query']; + if (\is_array($value)) { + $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986); + } + if (!\is_string($value)) { + throw new InvalidArgumentException('query must be a string or array'); + } + $modify['query'] = $value; + unset($options['query']); + } + + // Ensure that sink is not an invalid value. + if (isset($options['sink'])) { + // TODO: Add more sink validation? + if (\is_bool($options['sink'])) { + throw new InvalidArgumentException('sink must not be a boolean'); + } + } + + $request = Psr7\Utils::modifyRequest($request, $modify); + if ($request->getBody() instanceof Psr7\MultipartStream) { + // Use a multipart/form-data POST if a Content-Type is not set. + // Ensure that we don't have the header in different case and set the new value. + $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']); + $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary=' + . $request->getBody()->getBoundary(); + } + + // Merge in conditional headers if they are not present. + if (isset($options['_conditional'])) { + // Build up the changes so it's in a single clone of the message. + $modify = []; + foreach ($options['_conditional'] as $k => $v) { + if (!$request->hasHeader($k)) { + $modify['set_headers'][$k] = $v; + } + } + $request = Psr7\Utils::modifyRequest($request, $modify); + // Don't pass this internal value along to middleware/handlers. + unset($options['_conditional']); + } + + return $request; + } + + /** + * Return an InvalidArgumentException with pre-set message. + */ + private function invalidBody(): InvalidArgumentException + { + return new InvalidArgumentException('Passing in the "body" request ' + . 'option as an array to send a request is not supported. ' + . 'Please use the "form_params" request option to send a ' + . 'application/x-www-form-urlencoded request, or the "multipart" ' + . 'request option to send a multipart/form-data request.'); + } +} diff --git a/lib/guzzlehttp/guzzle/src/ClientInterface.php b/lib/guzzlehttp/guzzle/src/ClientInterface.php new file mode 100644 index 00000000..6aaee61a --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/ClientInterface.php @@ -0,0 +1,84 @@ +request('GET', $uri, $options); + } + + /** + * Create and send an HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function head($uri, array $options = []): ResponseInterface + { + return $this->request('HEAD', $uri, $options); + } + + /** + * Create and send an HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function put($uri, array $options = []): ResponseInterface + { + return $this->request('PUT', $uri, $options); + } + + /** + * Create and send an HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function post($uri, array $options = []): ResponseInterface + { + return $this->request('POST', $uri, $options); + } + + /** + * Create and send an HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function patch($uri, array $options = []): ResponseInterface + { + return $this->request('PATCH', $uri, $options); + } + + /** + * Create and send an HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + * + * @throws GuzzleException + */ + public function delete($uri, array $options = []): ResponseInterface + { + return $this->request('DELETE', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string $method HTTP method + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface; + + /** + * Create and send an asynchronous HTTP GET request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function getAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('GET', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP HEAD request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function headAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('HEAD', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PUT request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function putAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PUT', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP POST request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function postAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('POST', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP PATCH request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function patchAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('PATCH', $uri, $options); + } + + /** + * Create and send an asynchronous HTTP DELETE request. + * + * Use an absolute path to override the base path of the client, or a + * relative path to append to the base path of the client. The URL can + * contain the query string as well. Use an array to provide a URL + * template and additional variables to use in the URL template expansion. + * + * @param string|UriInterface $uri URI object or string. + * @param array $options Request options to apply. + */ + public function deleteAsync($uri, array $options = []): PromiseInterface + { + return $this->requestAsync('DELETE', $uri, $options); + } +} diff --git a/lib/guzzlehttp/guzzle/src/Cookie/CookieJar.php b/lib/guzzlehttp/guzzle/src/Cookie/CookieJar.php new file mode 100644 index 00000000..d6757c65 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Cookie/CookieJar.php @@ -0,0 +1,313 @@ +strictMode = $strictMode; + + foreach ($cookieArray as $cookie) { + if (!($cookie instanceof SetCookie)) { + $cookie = new SetCookie($cookie); + } + $this->setCookie($cookie); + } + } + + /** + * Create a new Cookie jar from an associative array and domain. + * + * @param array $cookies Cookies to create the jar from + * @param string $domain Domain to set the cookies to + */ + public static function fromArray(array $cookies, string $domain): self + { + $cookieJar = new self(); + foreach ($cookies as $name => $value) { + $cookieJar->setCookie(new SetCookie([ + 'Domain' => $domain, + 'Name' => $name, + 'Value' => $value, + 'Discard' => true + ])); + } + + return $cookieJar; + } + + /** + * Evaluate if this cookie should be persisted to storage + * that survives between requests. + * + * @param SetCookie $cookie Being evaluated. + * @param bool $allowSessionCookies If we should persist session cookies + */ + public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool + { + if ($cookie->getExpires() || $allowSessionCookies) { + if (!$cookie->getDiscard()) { + return true; + } + } + + return false; + } + + /** + * Finds and returns the cookie based on the name + * + * @param string $name cookie name to search for + * + * @return SetCookie|null cookie that was found or null if not found + */ + public function getCookieByName(string $name): ?SetCookie + { + foreach ($this->cookies as $cookie) { + if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) { + return $cookie; + } + } + + return null; + } + + /** + * @inheritDoc + */ + public function toArray(): array + { + return \array_map(static function (SetCookie $cookie): array { + return $cookie->toArray(); + }, $this->getIterator()->getArrayCopy()); + } + + /** + * @inheritDoc + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void + { + if (!$domain) { + $this->cookies = []; + return; + } elseif (!$path) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($domain): bool { + return !$cookie->matchesDomain($domain); + } + ); + } elseif (!$name) { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain): bool { + return !($cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } else { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie) use ($path, $domain, $name) { + return !($cookie->getName() == $name && + $cookie->matchesPath($path) && + $cookie->matchesDomain($domain)); + } + ); + } + } + + /** + * @inheritDoc + */ + public function clearSessionCookies(): void + { + $this->cookies = \array_filter( + $this->cookies, + static function (SetCookie $cookie): bool { + return !$cookie->getDiscard() && $cookie->getExpires(); + } + ); + } + + /** + * @inheritDoc + */ + public function setCookie(SetCookie $cookie): bool + { + // If the name string is empty (but not 0), ignore the set-cookie + // string entirely. + $name = $cookie->getName(); + if (!$name && $name !== '0') { + return false; + } + + // Only allow cookies with set and valid domain, name, value + $result = $cookie->validate(); + if ($result !== true) { + if ($this->strictMode) { + throw new \RuntimeException('Invalid cookie: ' . $result); + } + $this->removeCookieIfEmpty($cookie); + return false; + } + + // Resolve conflicts with previously set cookies + foreach ($this->cookies as $i => $c) { + + // Two cookies are identical, when their path, and domain are + // identical. + if ($c->getPath() != $cookie->getPath() || + $c->getDomain() != $cookie->getDomain() || + $c->getName() != $cookie->getName() + ) { + continue; + } + + // The previously set cookie is a discard cookie and this one is + // not so allow the new cookie to be set + if (!$cookie->getDiscard() && $c->getDiscard()) { + unset($this->cookies[$i]); + continue; + } + + // If the new cookie's expiration is further into the future, then + // replace the old cookie + if ($cookie->getExpires() > $c->getExpires()) { + unset($this->cookies[$i]); + continue; + } + + // If the value has changed, we better change it + if ($cookie->getValue() !== $c->getValue()) { + unset($this->cookies[$i]); + continue; + } + + // The cookie exists, so no need to continue + return false; + } + + $this->cookies[] = $cookie; + + return true; + } + + public function count(): int + { + return \count($this->cookies); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator(\array_values($this->cookies)); + } + + public function extractCookies(RequestInterface $request, ResponseInterface $response): void + { + if ($cookieHeader = $response->getHeader('Set-Cookie')) { + foreach ($cookieHeader as $cookie) { + $sc = SetCookie::fromString($cookie); + if (!$sc->getDomain()) { + $sc->setDomain($request->getUri()->getHost()); + } + if (0 !== \strpos($sc->getPath(), '/')) { + $sc->setPath($this->getCookiePathFromRequest($request)); + } + $this->setCookie($sc); + } + } + } + + /** + * Computes cookie path following RFC 6265 section 5.1.4 + * + * @link https://tools.ietf.org/html/rfc6265#section-5.1.4 + */ + private function getCookiePathFromRequest(RequestInterface $request): string + { + $uriPath = $request->getUri()->getPath(); + if ('' === $uriPath) { + return '/'; + } + if (0 !== \strpos($uriPath, '/')) { + return '/'; + } + if ('/' === $uriPath) { + return '/'; + } + $lastSlashPos = \strrpos($uriPath, '/'); + if (0 === $lastSlashPos || false === $lastSlashPos) { + return '/'; + } + + return \substr($uriPath, 0, $lastSlashPos); + } + + public function withCookieHeader(RequestInterface $request): RequestInterface + { + $values = []; + $uri = $request->getUri(); + $scheme = $uri->getScheme(); + $host = $uri->getHost(); + $path = $uri->getPath() ?: '/'; + + foreach ($this->cookies as $cookie) { + if ($cookie->matchesPath($path) && + $cookie->matchesDomain($host) && + !$cookie->isExpired() && + (!$cookie->getSecure() || $scheme === 'https') + ) { + $values[] = $cookie->getName() . '=' + . $cookie->getValue(); + } + } + + return $values + ? $request->withHeader('Cookie', \implode('; ', $values)) + : $request; + } + + /** + * If a cookie already exists and the server asks to set it again with a + * null value, the cookie must be deleted. + */ + private function removeCookieIfEmpty(SetCookie $cookie): void + { + $cookieValue = $cookie->getValue(); + if ($cookieValue === null || $cookieValue === '') { + $this->clear( + $cookie->getDomain(), + $cookie->getPath(), + $cookie->getName() + ); + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php b/lib/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php new file mode 100644 index 00000000..7df374b5 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Cookie/CookieJarInterface.php @@ -0,0 +1,79 @@ + + */ +interface CookieJarInterface extends \Countable, \IteratorAggregate +{ + /** + * Create a request with added cookie headers. + * + * If no matching cookies are found in the cookie jar, then no Cookie + * header is added to the request and the same request is returned. + * + * @param RequestInterface $request Request object to modify. + * + * @return RequestInterface returns the modified request. + */ + public function withCookieHeader(RequestInterface $request): RequestInterface; + + /** + * Extract cookies from an HTTP response and store them in the CookieJar. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface $response Response that was received + */ + public function extractCookies(RequestInterface $request, ResponseInterface $response): void; + + /** + * Sets a cookie in the cookie jar. + * + * @param SetCookie $cookie Cookie to set. + * + * @return bool Returns true on success or false on failure + */ + public function setCookie(SetCookie $cookie): bool; + + /** + * Remove cookies currently held in the cookie jar. + * + * Invoking this method without arguments will empty the whole cookie jar. + * If given a $domain argument only cookies belonging to that domain will + * be removed. If given a $domain and $path argument, cookies belonging to + * the specified path within that domain are removed. If given all three + * arguments, then the cookie with the specified name, path and domain is + * removed. + * + * @param string|null $domain Clears cookies matching a domain + * @param string|null $path Clears cookies matching a domain and path + * @param string|null $name Clears cookies matching a domain, path, and name + */ + public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void; + + /** + * Discard all sessions cookies. + * + * Removes cookies that don't have an expire field or a have a discard + * field set to true. To be called when the user agent shuts down according + * to RFC 2965. + */ + public function clearSessionCookies(): void; + + /** + * Converts the cookie jar to an array. + */ + public function toArray(): array; +} diff --git a/lib/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php b/lib/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php new file mode 100644 index 00000000..290236d5 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php @@ -0,0 +1,101 @@ +filename = $cookieFile; + $this->storeSessionCookies = $storeSessionCookies; + + if (\file_exists($cookieFile)) { + $this->load($cookieFile); + } + } + + /** + * Saves the file when shutting down + */ + public function __destruct() + { + $this->save($this->filename); + } + + /** + * Saves the cookies to a file. + * + * @param string $filename File to save + * + * @throws \RuntimeException if the file cannot be found or created + */ + public function save(string $filename): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $jsonStr = Utils::jsonEncode($json); + if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) { + throw new \RuntimeException("Unable to save file {$filename}"); + } + } + + /** + * Load cookies from a JSON formatted file. + * + * Old cookies are kept unless overwritten by newly loaded ones. + * + * @param string $filename Cookie file to load. + * + * @throws \RuntimeException if the file cannot be loaded. + */ + public function load(string $filename): void + { + $json = \file_get_contents($filename); + if (false === $json) { + throw new \RuntimeException("Unable to load file {$filename}"); + } + if ($json === '') { + return; + } + + $data = Utils::jsonDecode($json, true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\is_scalar($data) && !empty($data)) { + throw new \RuntimeException("Invalid cookie file: {$filename}"); + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php b/lib/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php new file mode 100644 index 00000000..5d51ca98 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Cookie/SessionCookieJar.php @@ -0,0 +1,77 @@ +sessionKey = $sessionKey; + $this->storeSessionCookies = $storeSessionCookies; + $this->load(); + } + + /** + * Saves cookies to session when shutting down + */ + public function __destruct() + { + $this->save(); + } + + /** + * Save cookies to the client session + */ + public function save(): void + { + $json = []; + /** @var SetCookie $cookie */ + foreach ($this as $cookie) { + if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { + $json[] = $cookie->toArray(); + } + } + + $_SESSION[$this->sessionKey] = \json_encode($json); + } + + /** + * Load the contents of the client session into the data array + */ + protected function load(): void + { + if (!isset($_SESSION[$this->sessionKey])) { + return; + } + $data = \json_decode($_SESSION[$this->sessionKey], true); + if (\is_array($data)) { + foreach ($data as $cookie) { + $this->setCookie(new SetCookie($cookie)); + } + } elseif (\strlen($data)) { + throw new \RuntimeException("Invalid cookie data"); + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/Cookie/SetCookie.php b/lib/guzzlehttp/guzzle/src/Cookie/SetCookie.php new file mode 100644 index 00000000..7c04034d --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Cookie/SetCookie.php @@ -0,0 +1,444 @@ + null, + 'Value' => null, + 'Domain' => null, + 'Path' => '/', + 'Max-Age' => null, + 'Expires' => null, + 'Secure' => false, + 'Discard' => false, + 'HttpOnly' => false + ]; + + /** + * @var array Cookie data + */ + private $data; + + /** + * Create a new SetCookie object from a string. + * + * @param string $cookie Set-Cookie header string + */ + public static function fromString(string $cookie): self + { + // Create the default return array + $data = self::$defaults; + // Explode the cookie string using a series of semicolons + $pieces = \array_filter(\array_map('trim', \explode(';', $cookie))); + // The name of the cookie (first kvp) must exist and include an equal sign. + if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) { + return new self($data); + } + + // Add the cookie pieces into the parsed data array + foreach ($pieces as $part) { + $cookieParts = \explode('=', $part, 2); + $key = \trim($cookieParts[0]); + $value = isset($cookieParts[1]) + ? \trim($cookieParts[1], " \n\r\t\0\x0B") + : true; + + // Only check for non-cookies when cookies have been found + if (!isset($data['Name'])) { + $data['Name'] = $key; + $data['Value'] = $value; + } else { + foreach (\array_keys(self::$defaults) as $search) { + if (!\strcasecmp($search, $key)) { + $data[$search] = $value; + continue 2; + } + } + $data[$key] = $value; + } + } + + return new self($data); + } + + /** + * @param array $data Array of cookie data provided by a Cookie parser + */ + public function __construct(array $data = []) + { + /** @var array|null $replaced will be null in case of replace error */ + $replaced = \array_replace(self::$defaults, $data); + if ($replaced === null) { + throw new \InvalidArgumentException('Unable to replace the default values for the Cookie.'); + } + + $this->data = $replaced; + // Extract the Expires value and turn it into a UNIX timestamp if needed + if (!$this->getExpires() && $this->getMaxAge()) { + // Calculate the Expires date + $this->setExpires(\time() + $this->getMaxAge()); + } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) { + $this->setExpires($expires); + } + } + + public function __toString() + { + $str = $this->data['Name'] . '=' . ($this->data['Value'] ?? '') . '; '; + foreach ($this->data as $k => $v) { + if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) { + if ($k === 'Expires') { + $str .= 'Expires=' . \gmdate('D, d M Y H:i:s \G\M\T', $v) . '; '; + } else { + $str .= ($v === true ? $k : "{$k}={$v}") . '; '; + } + } + } + + return \rtrim($str, '; '); + } + + public function toArray(): array + { + return $this->data; + } + + /** + * Get the cookie name. + * + * @return string + */ + public function getName() + { + return $this->data['Name']; + } + + /** + * Set the cookie name. + * + * @param string $name Cookie name + */ + public function setName($name): void + { + if (!is_string($name)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Name'] = (string) $name; + } + + /** + * Get the cookie value. + * + * @return string|null + */ + public function getValue() + { + return $this->data['Value']; + } + + /** + * Set the cookie value. + * + * @param string $value Cookie value + */ + public function setValue($value): void + { + if (!is_string($value)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Value'] = (string) $value; + } + + /** + * Get the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->data['Domain']; + } + + /** + * Set the domain of the cookie. + * + * @param string|null $domain + */ + public function setDomain($domain): void + { + if (!is_string($domain) && null !== $domain) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Domain'] = null === $domain ? null : (string) $domain; + } + + /** + * Get the path. + * + * @return string + */ + public function getPath() + { + return $this->data['Path']; + } + + /** + * Set the path of the cookie. + * + * @param string $path Path of the cookie + */ + public function setPath($path): void + { + if (!is_string($path)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Path'] = (string) $path; + } + + /** + * Maximum lifetime of the cookie in seconds. + * + * @return int|null + */ + public function getMaxAge() + { + return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age']; + } + + /** + * Set the max-age of the cookie. + * + * @param int|null $maxAge Max age of the cookie in seconds + */ + public function setMaxAge($maxAge): void + { + if (!is_int($maxAge) && null !== $maxAge) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge; + } + + /** + * The UNIX timestamp when the cookie Expires. + * + * @return string|int|null + */ + public function getExpires() + { + return $this->data['Expires']; + } + + /** + * Set the unix timestamp for which the cookie will expire. + * + * @param int|string|null $timestamp Unix timestamp or any English textual datetime description. + */ + public function setExpires($timestamp): void + { + if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp)); + } + + /** + * Get whether or not this is a secure cookie. + * + * @return bool + */ + public function getSecure() + { + return $this->data['Secure']; + } + + /** + * Set whether or not the cookie is secure. + * + * @param bool $secure Set to true or false if secure + */ + public function setSecure($secure): void + { + if (!is_bool($secure)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Secure'] = (bool) $secure; + } + + /** + * Get whether or not this is a session cookie. + * + * @return bool|null + */ + public function getDiscard() + { + return $this->data['Discard']; + } + + /** + * Set whether or not this is a session cookie. + * + * @param bool $discard Set to true or false if this is a session cookie + */ + public function setDiscard($discard): void + { + if (!is_bool($discard)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['Discard'] = (bool) $discard; + } + + /** + * Get whether or not this is an HTTP only cookie. + * + * @return bool + */ + public function getHttpOnly() + { + return $this->data['HttpOnly']; + } + + /** + * Set whether or not this is an HTTP only cookie. + * + * @param bool $httpOnly Set to true or false if this is HTTP only + */ + public function setHttpOnly($httpOnly): void + { + if (!is_bool($httpOnly)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->data['HttpOnly'] = (bool) $httpOnly; + } + + /** + * Check if the cookie matches a path value. + * + * A request-path path-matches a given cookie-path if at least one of + * the following conditions holds: + * + * - The cookie-path and the request-path are identical. + * - The cookie-path is a prefix of the request-path, and the last + * character of the cookie-path is %x2F ("/"). + * - The cookie-path is a prefix of the request-path, and the first + * character of the request-path that is not included in the cookie- + * path is a %x2F ("/") character. + * + * @param string $requestPath Path to check against + */ + public function matchesPath(string $requestPath): bool + { + $cookiePath = $this->getPath(); + + // Match on exact matches or when path is the default empty "/" + if ($cookiePath === '/' || $cookiePath == $requestPath) { + return true; + } + + // Ensure that the cookie-path is a prefix of the request path. + if (0 !== \strpos($requestPath, $cookiePath)) { + return false; + } + + // Match if the last character of the cookie-path is "/" + if (\substr($cookiePath, -1, 1) === '/') { + return true; + } + + // Match if the first character not included in cookie path is "/" + return \substr($requestPath, \strlen($cookiePath), 1) === '/'; + } + + /** + * Check if the cookie matches a domain value. + * + * @param string $domain Domain to check against + */ + public function matchesDomain(string $domain): bool + { + $cookieDomain = $this->getDomain(); + if (null === $cookieDomain) { + return true; + } + + // Remove the leading '.' as per spec in RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.2.3 + $cookieDomain = \ltrim($cookieDomain, '.'); + + // Domain not set or exact match. + if (!$cookieDomain || !\strcasecmp($domain, $cookieDomain)) { + return true; + } + + // Matching the subdomain according to RFC 6265. + // https://tools.ietf.org/html/rfc6265#section-5.1.3 + if (\filter_var($domain, \FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain); + } + + /** + * Check if the cookie is expired. + */ + public function isExpired(): bool + { + return $this->getExpires() !== null && \time() > $this->getExpires(); + } + + /** + * Check if the cookie is valid according to RFC 6265. + * + * @return bool|string Returns true if valid or an error message if invalid + */ + public function validate() + { + $name = $this->getName(); + if ($name === '') { + return 'The cookie name must not be empty'; + } + + // Check if any of the invalid characters are present in the cookie name + if (\preg_match( + '/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', + $name + )) { + return 'Cookie name must not contain invalid characters: ASCII ' + . 'Control characters (0-31;127), space, tab and the ' + . 'following characters: ()<>@,;:\"/?={}'; + } + + // Value must not be null. 0 and empty string are valid. Empty strings + // are technically against RFC 6265, but known to happen in the wild. + $value = $this->getValue(); + if ($value === null) { + return 'The cookie value must not be empty'; + } + + // Domains must not be empty, but can be 0. "0" is not a valid internet + // domain, but may be used as server name in a private network. + $domain = $this->getDomain(); + if ($domain === null || $domain === '') { + return 'The cookie domain must not be empty'; + } + + return true; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Exception/BadResponseException.php b/lib/guzzlehttp/guzzle/src/Exception/BadResponseException.php new file mode 100644 index 00000000..a80956c9 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Exception/BadResponseException.php @@ -0,0 +1,39 @@ +request = $request; + $this->handlerContext = $handlerContext; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Exception/GuzzleException.php b/lib/guzzlehttp/guzzle/src/Exception/GuzzleException.php new file mode 100644 index 00000000..fa3ed699 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Exception/GuzzleException.php @@ -0,0 +1,9 @@ +getStatusCode() : 0; + parent::__construct($message, $code, $previous); + $this->request = $request; + $this->response = $response; + $this->handlerContext = $handlerContext; + } + + /** + * Wrap non-RequestExceptions with a RequestException + */ + public static function wrapException(RequestInterface $request, \Throwable $e): RequestException + { + return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e); + } + + /** + * Factory method to create a new exception with a normalized error message + * + * @param RequestInterface $request Request sent + * @param ResponseInterface $response Response received + * @param \Throwable|null $previous Previous exception + * @param array $handlerContext Optional handler context + * @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer + */ + public static function create( + RequestInterface $request, + ResponseInterface $response = null, + \Throwable $previous = null, + array $handlerContext = [], + BodySummarizerInterface $bodySummarizer = null + ): self { + if (!$response) { + return new self( + 'Error completing request', + $request, + null, + $previous, + $handlerContext + ); + } + + $level = (int) \floor($response->getStatusCode() / 100); + if ($level === 4) { + $label = 'Client error'; + $className = ClientException::class; + } elseif ($level === 5) { + $label = 'Server error'; + $className = ServerException::class; + } else { + $label = 'Unsuccessful request'; + $className = __CLASS__; + } + + $uri = $request->getUri(); + $uri = static::obfuscateUri($uri); + + // Client Error: `GET /` resulted in a `404 Not Found` response: + // ... (truncated) + $message = \sprintf( + '%s: `%s %s` resulted in a `%s %s` response', + $label, + $request->getMethod(), + $uri, + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + $summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response); + + if ($summary !== null) { + $message .= ":\n{$summary}\n"; + } + + return new $className($message, $request, $response, $previous, $handlerContext); + } + + /** + * Obfuscates URI if there is a username and a password present + */ + private static function obfuscateUri(UriInterface $uri): UriInterface + { + $userInfo = $uri->getUserInfo(); + + if (false !== ($pos = \strpos($userInfo, ':'))) { + return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***'); + } + + return $uri; + } + + /** + * Get the request that caused the exception + */ + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Get the associated response + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Check if a response was received + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Get contextual information about the error from the underlying handler. + * + * The contents of this array will vary depending on which handler you are + * using. It may also be just an empty array. Relying on this data will + * couple you to a specific handler, but can give more debug information + * when needed. + */ + public function getHandlerContext(): array + { + return $this->handlerContext; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Exception/ServerException.php b/lib/guzzlehttp/guzzle/src/Exception/ServerException.php new file mode 100644 index 00000000..8055e067 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Exception/ServerException.php @@ -0,0 +1,10 @@ +maxHandles = $maxHandles; + } + + public function create(RequestInterface $request, array $options): EasyHandle + { + if (isset($options['curl']['body_as_string'])) { + $options['_body_as_string'] = $options['curl']['body_as_string']; + unset($options['curl']['body_as_string']); + } + + $easy = new EasyHandle; + $easy->request = $request; + $easy->options = $options; + $conf = $this->getDefaultConf($easy); + $this->applyMethod($easy, $conf); + $this->applyHandlerOptions($easy, $conf); + $this->applyHeaders($easy, $conf); + unset($conf['_headers']); + + // Add handler options from the request configuration options + if (isset($options['curl'])) { + $conf = \array_replace($conf, $options['curl']); + } + + $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy); + $easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init(); + curl_setopt_array($easy->handle, $conf); + + return $easy; + } + + public function release(EasyHandle $easy): void + { + $resource = $easy->handle; + unset($easy->handle); + + if (\count($this->handles) >= $this->maxHandles) { + \curl_close($resource); + } else { + // Remove all callback functions as they can hold onto references + // and are not cleaned up by curl_reset. Using curl_setopt_array + // does not work for some reason, so removing each one + // individually. + \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null); + \curl_setopt($resource, \CURLOPT_READFUNCTION, null); + \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null); + \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null); + \curl_reset($resource); + $this->handles[] = $resource; + } + } + + /** + * Completes a cURL transaction, either returning a response promise or a + * rejected promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + * @param CurlFactoryInterface $factory Dictates how the handle is released + */ + public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + if (isset($easy->options['on_stats'])) { + self::invokeStats($easy); + } + + if (!$easy->response || $easy->errno) { + return self::finishError($handler, $easy, $factory); + } + + // Return the response if it is present and there is no error. + $factory->release($easy); + + // Rewind the body of the response if possible. + $body = $easy->response->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + + return new FulfilledPromise($easy->response); + } + + private static function invokeStats(EasyHandle $easy): void + { + $curlStats = \curl_getinfo($easy->handle); + $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME); + $stats = new TransferStats( + $easy->request, + $easy->response, + $curlStats['total_time'], + $easy->errno, + $curlStats + ); + ($easy->options['on_stats'])($stats); + } + + /** + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface + { + // Get error information and release the handle to the factory. + $ctx = [ + 'errno' => $easy->errno, + 'error' => \curl_error($easy->handle), + 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME), + ] + \curl_getinfo($easy->handle); + $ctx[self::CURL_VERSION_STR] = \curl_version()['version']; + $factory->release($easy); + + // Retry when nothing is present or when curl failed to rewind. + if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) { + return self::retryFailedRewind($handler, $easy, $ctx); + } + + return self::createRejection($easy, $ctx); + } + + private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface + { + static $connectionErrors = [ + \CURLE_OPERATION_TIMEOUTED => true, + \CURLE_COULDNT_RESOLVE_HOST => true, + \CURLE_COULDNT_CONNECT => true, + \CURLE_SSL_CONNECT_ERROR => true, + \CURLE_GOT_NOTHING => true, + ]; + + if ($easy->createResponseException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered while creating the response', + $easy->request, + $easy->response, + $easy->createResponseException, + $ctx + ) + ); + } + + // If an exception was encountered during the onHeaders event, then + // return a rejected promise that wraps that exception. + if ($easy->onHeadersException) { + return P\Create::rejectionFor( + new RequestException( + 'An error was encountered during the on_headers event', + $easy->request, + $easy->response, + $easy->onHeadersException, + $ctx + ) + ); + } + + $message = \sprintf( + 'cURL error %s: %s (%s)', + $ctx['errno'], + $ctx['error'], + 'see https://curl.haxx.se/libcurl/c/libcurl-errors.html' + ); + $uriString = (string) $easy->request->getUri(); + if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) { + $message .= \sprintf(' for %s', $uriString); + } + + // Create a connection exception if it was a specific error code. + $error = isset($connectionErrors[$easy->errno]) + ? new ConnectException($message, $easy->request, null, $ctx) + : new RequestException($message, $easy->request, $easy->response, null, $ctx); + + return P\Create::rejectionFor($error); + } + + /** + * @return array + */ + private function getDefaultConf(EasyHandle $easy): array + { + $conf = [ + '_headers' => $easy->request->getHeaders(), + \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(), + \CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''), + \CURLOPT_RETURNTRANSFER => false, + \CURLOPT_HEADER => false, + \CURLOPT_CONNECTTIMEOUT => 150, + ]; + + if (\defined('CURLOPT_PROTOCOLS')) { + $conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS; + } + + $version = $easy->request->getProtocolVersion(); + if ($version == 1.1) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1; + } elseif ($version == 2.0) { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0; + } else { + $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0; + } + + return $conf; + } + + private function applyMethod(EasyHandle $easy, array &$conf): void + { + $body = $easy->request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size > 0) { + $this->applyBody($easy->request, $easy->options, $conf); + return; + } + + $method = $easy->request->getMethod(); + if ($method === 'PUT' || $method === 'POST') { + // See https://tools.ietf.org/html/rfc7230#section-3.3.2 + if (!$easy->request->hasHeader('Content-Length')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0'; + } + } elseif ($method === 'HEAD') { + $conf[\CURLOPT_NOBODY] = true; + unset( + $conf[\CURLOPT_WRITEFUNCTION], + $conf[\CURLOPT_READFUNCTION], + $conf[\CURLOPT_FILE], + $conf[\CURLOPT_INFILE] + ); + } + } + + private function applyBody(RequestInterface $request, array $options, array &$conf): void + { + $size = $request->hasHeader('Content-Length') + ? (int) $request->getHeaderLine('Content-Length') + : null; + + // Send the body as a string if the size is less than 1MB OR if the + // [curl][body_as_string] request value is set. + if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) { + $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody(); + // Don't duplicate the Content-Length header + $this->removeHeader('Content-Length', $conf); + $this->removeHeader('Transfer-Encoding', $conf); + } else { + $conf[\CURLOPT_UPLOAD] = true; + if ($size !== null) { + $conf[\CURLOPT_INFILESIZE] = $size; + $this->removeHeader('Content-Length', $conf); + } + $body = $request->getBody(); + if ($body->isSeekable()) { + $body->rewind(); + } + $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { + return $body->read($length); + }; + } + + // If the Expect header is not present, prevent curl from adding it + if (!$request->hasHeader('Expect')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Expect:'; + } + + // cURL sometimes adds a content-type by default. Prevent this. + if (!$request->hasHeader('Content-Type')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:'; + } + } + + private function applyHeaders(EasyHandle $easy, array &$conf): void + { + foreach ($conf['_headers'] as $name => $values) { + foreach ($values as $value) { + $value = (string) $value; + if ($value === '') { + // cURL requires a special format for empty headers. + // See https://github.com/guzzle/guzzle/issues/1882 for more details. + $conf[\CURLOPT_HTTPHEADER][] = "$name;"; + } else { + $conf[\CURLOPT_HTTPHEADER][] = "$name: $value"; + } + } + } + + // Remove the Accept header if one was not set + if (!$easy->request->hasHeader('Accept')) { + $conf[\CURLOPT_HTTPHEADER][] = 'Accept:'; + } + } + + /** + * Remove a header from the options array. + * + * @param string $name Case-insensitive header to remove + * @param array $options Array of options to modify + */ + private function removeHeader(string $name, array &$options): void + { + foreach (\array_keys($options['_headers']) as $key) { + if (!\strcasecmp($key, $name)) { + unset($options['_headers'][$key]); + return; + } + } + } + + private function applyHandlerOptions(EasyHandle $easy, array &$conf): void + { + $options = $easy->options; + if (isset($options['verify'])) { + if ($options['verify'] === false) { + unset($conf[\CURLOPT_CAINFO]); + $conf[\CURLOPT_SSL_VERIFYHOST] = 0; + $conf[\CURLOPT_SSL_VERIFYPEER] = false; + } else { + $conf[\CURLOPT_SSL_VERIFYHOST] = 2; + $conf[\CURLOPT_SSL_VERIFYPEER] = true; + if (\is_string($options['verify'])) { + // Throw an error if the file/folder/link path is not valid or doesn't exist. + if (!\file_exists($options['verify'])) { + throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}"); + } + // If it's a directory or a link to a directory use CURLOPT_CAPATH. + // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO. + if ( + \is_dir($options['verify']) || + ( + \is_link($options['verify']) === true && + ($verifyLink = \readlink($options['verify'])) !== false && + \is_dir($verifyLink) + ) + ) { + $conf[\CURLOPT_CAPATH] = $options['verify']; + } else { + $conf[\CURLOPT_CAINFO] = $options['verify']; + } + } + } + } + + if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) { + $accept = $easy->request->getHeaderLine('Accept-Encoding'); + if ($accept) { + $conf[\CURLOPT_ENCODING] = $accept; + } else { + // The empty string enables all available decoders and implicitly + // sets a matching 'Accept-Encoding' header. + $conf[\CURLOPT_ENCODING] = ''; + // But as the user did not specify any acceptable encodings we need + // to overwrite this implicit header with an empty one. + $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:'; + } + } + + if (!isset($options['sink'])) { + // Use a default temp stream if no sink was set. + $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+'); + } + $sink = $options['sink']; + if (!\is_string($sink)) { + $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink); + } elseif (!\is_dir(\dirname($sink))) { + // Ensure that the directory exists before failing in curl. + throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink)); + } else { + $sink = new LazyOpenStream($sink, 'w+'); + } + $easy->sink = $sink; + $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int { + return $sink->write($write); + }; + + $timeoutRequiresNoSignal = false; + if (isset($options['timeout'])) { + $timeoutRequiresNoSignal |= $options['timeout'] < 1; + $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000; + } + + // CURL default value is CURL_IPRESOLVE_WHATEVER + if (isset($options['force_ip_resolve'])) { + if ('v4' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4; + } elseif ('v6' === $options['force_ip_resolve']) { + $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6; + } + } + + if (isset($options['connect_timeout'])) { + $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1; + $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000; + } + + if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') { + $conf[\CURLOPT_NOSIGNAL] = true; + } + + if (isset($options['proxy'])) { + if (!\is_array($options['proxy'])) { + $conf[\CURLOPT_PROXY] = $options['proxy']; + } else { + $scheme = $easy->request->getUri()->getScheme(); + if (isset($options['proxy'][$scheme])) { + $host = $easy->request->getUri()->getHost(); + if (!isset($options['proxy']['no']) || !Utils::isHostInNoProxy($host, $options['proxy']['no'])) { + $conf[\CURLOPT_PROXY] = $options['proxy'][$scheme]; + } + } + } + } + + if (isset($options['cert'])) { + $cert = $options['cert']; + if (\is_array($cert)) { + $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1]; + $cert = $cert[0]; + } + if (!\file_exists($cert)) { + throw new \InvalidArgumentException("SSL certificate not found: {$cert}"); + } + # OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files. + # see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html + $ext = pathinfo($cert, \PATHINFO_EXTENSION); + if (preg_match('#^(der|p12)$#i', $ext)) { + $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext); + } + $conf[\CURLOPT_SSLCERT] = $cert; + } + + if (isset($options['ssl_key'])) { + if (\is_array($options['ssl_key'])) { + if (\count($options['ssl_key']) === 2) { + [$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key']; + } else { + [$sslKey] = $options['ssl_key']; + } + } + + $sslKey = $sslKey ?? $options['ssl_key']; + + if (!\file_exists($sslKey)) { + throw new \InvalidArgumentException("SSL private key not found: {$sslKey}"); + } + $conf[\CURLOPT_SSLKEY] = $sslKey; + } + + if (isset($options['progress'])) { + $progress = $options['progress']; + if (!\is_callable($progress)) { + throw new \InvalidArgumentException('progress client option must be callable'); + } + $conf[\CURLOPT_NOPROGRESS] = false; + $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) { + $progress($downloadSize, $downloaded, $uploadSize, $uploaded); + }; + } + + if (!empty($options['debug'])) { + $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_VERBOSE] = true; + } + } + + /** + * This function ensures that a response was set on a transaction. If one + * was not set, then the request is retried if possible. This error + * typically means you are sending a payload, curl encountered a + * "Connection died, retrying a fresh connect" error, tried to rewind the + * stream, and then encountered a "necessary data rewind wasn't possible" + * error, causing the request to be sent through curl_multi_info_read() + * without an error status. + * + * @param callable(RequestInterface, array): PromiseInterface $handler + */ + private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface + { + try { + // Only rewind if the body has been read from. + $body = $easy->request->getBody(); + if ($body->tell() > 0) { + $body->rewind(); + } + } catch (\RuntimeException $e) { + $ctx['error'] = 'The connection unexpectedly failed without ' + . 'providing an error. The request would have been retried, ' + . 'but attempting to rewind the request body failed. ' + . 'Exception: ' . $e; + return self::createRejection($easy, $ctx); + } + + // Retry no more than 3 times before giving up. + if (!isset($easy->options['_curl_retries'])) { + $easy->options['_curl_retries'] = 1; + } elseif ($easy->options['_curl_retries'] == 2) { + $ctx['error'] = 'The cURL request was retried 3 times ' + . 'and did not succeed. The most likely reason for the failure ' + . 'is that cURL was unable to rewind the body of the request ' + . 'and subsequent retries resulted in the same error. Turn on ' + . 'the debug option to see what went wrong. See ' + . 'https://bugs.php.net/bug.php?id=47204 for more information.'; + return self::createRejection($easy, $ctx); + } else { + $easy->options['_curl_retries']++; + } + + return $handler($easy->request, $easy->options); + } + + private function createHeaderFn(EasyHandle $easy): callable + { + if (isset($easy->options['on_headers'])) { + $onHeaders = $easy->options['on_headers']; + + if (!\is_callable($onHeaders)) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + } else { + $onHeaders = null; + } + + return static function ($ch, $h) use ( + $onHeaders, + $easy, + &$startingResponse + ) { + $value = \trim($h); + if ($value === '') { + $startingResponse = true; + try { + $easy->createResponse(); + } catch (\Exception $e) { + $easy->createResponseException = $e; + return -1; + } + if ($onHeaders !== null) { + try { + $onHeaders($easy->response); + } catch (\Exception $e) { + // Associate the exception with the handle and trigger + // a curl header write error by returning 0. + $easy->onHeadersException = $e; + return -1; + } + } + } elseif ($startingResponse) { + $startingResponse = false; + $easy->headers = [$value]; + } else { + $easy->headers[] = $value; + } + return \strlen($h); + }; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php b/lib/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php new file mode 100644 index 00000000..fe57ed5d --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Handler/CurlFactoryInterface.php @@ -0,0 +1,25 @@ +factory = $options['handle_factory'] + ?? new CurlFactory(3); + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (isset($options['delay'])) { + \usleep($options['delay'] * 1000); + } + + $easy = $this->factory->create($request, $options); + \curl_exec($easy->handle); + $easy->errno = \curl_errno($easy->handle); + + return CurlFactory::finish($this, $easy, $this->factory); + } +} diff --git a/lib/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php b/lib/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php new file mode 100644 index 00000000..ace0d840 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php @@ -0,0 +1,257 @@ + An array of delay times, indexed by handle id in `addRequest`. + * + * @see CurlMultiHandler::addRequest + */ + private $delays = []; + + /** + * @var array An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt() + */ + private $options = []; + + /** + * This handler accepts the following options: + * + * - handle_factory: An optional factory used to create curl handles + * - select_timeout: Optional timeout (in seconds) to block before timing + * out while selecting curl handles. Defaults to 1 second. + * - options: An associative array of CURLMOPT_* options and + * corresponding values for curl_multi_setopt() + */ + public function __construct(array $options = []) + { + $this->factory = $options['handle_factory'] ?? new CurlFactory(50); + + if (isset($options['select_timeout'])) { + $this->selectTimeout = $options['select_timeout']; + } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) { + @trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED); + $this->selectTimeout = (int) $selectTimeout; + } else { + $this->selectTimeout = 1; + } + + $this->options = $options['options'] ?? []; + } + + /** + * @param string $name + * + * @return resource|\CurlMultiHandle + * + * @throws \BadMethodCallException when another field as `_mh` will be gotten + * @throws \RuntimeException when curl can not initialize a multi handle + */ + public function __get($name) + { + if ($name !== '_mh') { + throw new \BadMethodCallException("Can not get other property as '_mh'."); + } + + $multiHandle = \curl_multi_init(); + + if (false === $multiHandle) { + throw new \RuntimeException('Can not initialize curl multi handle.'); + } + + $this->_mh = $multiHandle; + + foreach ($this->options as $option => $value) { + // A warning is raised in case of a wrong option. + curl_multi_setopt($this->_mh, $option, $value); + } + + return $this->_mh; + } + + public function __destruct() + { + if (isset($this->_mh)) { + \curl_multi_close($this->_mh); + unset($this->_mh); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $easy = $this->factory->create($request, $options); + $id = (int) $easy->handle; + + $promise = new Promise( + [$this, 'execute'], + function () use ($id) { + return $this->cancel($id); + } + ); + + $this->addRequest(['easy' => $easy, 'deferred' => $promise]); + + return $promise; + } + + /** + * Ticks the curl event loop. + */ + public function tick(): void + { + // Add any delayed handles if needed. + if ($this->delays) { + $currentTime = Utils::currentTime(); + foreach ($this->delays as $id => $delay) { + if ($currentTime >= $delay) { + unset($this->delays[$id]); + \curl_multi_add_handle( + $this->_mh, + $this->handles[$id]['easy']->handle + ); + } + } + } + + // Step through the task queue which may add additional requests. + P\Utils::queue()->run(); + + if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) { + // Perform a usleep if a select returns -1. + // See: https://bugs.php.net/bug.php?id=61141 + \usleep(250); + } + + while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM); + + $this->processMessages(); + } + + /** + * Runs until all outstanding connections have completed. + */ + public function execute(): void + { + $queue = P\Utils::queue(); + + while ($this->handles || !$queue->isEmpty()) { + // If there are no transfers, then sleep for the next delay + if (!$this->active && $this->delays) { + \usleep($this->timeToNext()); + } + $this->tick(); + } + } + + private function addRequest(array $entry): void + { + $easy = $entry['easy']; + $id = (int) $easy->handle; + $this->handles[$id] = $entry; + if (empty($easy->options['delay'])) { + \curl_multi_add_handle($this->_mh, $easy->handle); + } else { + $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000); + } + } + + /** + * Cancels a handle from sending and removes references to it. + * + * @param int $id Handle ID to cancel and remove. + * + * @return bool True on success, false on failure. + */ + private function cancel($id): bool + { + if (!is_int($id)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + // Cannot cancel if it has been processed. + if (!isset($this->handles[$id])) { + return false; + } + + $handle = $this->handles[$id]['easy']->handle; + unset($this->delays[$id], $this->handles[$id]); + \curl_multi_remove_handle($this->_mh, $handle); + \curl_close($handle); + + return true; + } + + private function processMessages(): void + { + while ($done = \curl_multi_info_read($this->_mh)) { + $id = (int) $done['handle']; + \curl_multi_remove_handle($this->_mh, $done['handle']); + + if (!isset($this->handles[$id])) { + // Probably was cancelled. + continue; + } + + $entry = $this->handles[$id]; + unset($this->handles[$id], $this->delays[$id]); + $entry['easy']->errno = $done['result']; + $entry['deferred']->resolve( + CurlFactory::finish($this, $entry['easy'], $this->factory) + ); + } + } + + private function timeToNext(): int + { + $currentTime = Utils::currentTime(); + $nextTime = \PHP_INT_MAX; + foreach ($this->delays as $time) { + if ($time < $nextTime) { + $nextTime = $time; + } + } + + return ((int) \max(0, $nextTime - $currentTime)) * 1000000; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Handler/EasyHandle.php b/lib/guzzlehttp/guzzle/src/Handler/EasyHandle.php new file mode 100644 index 00000000..224344d7 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Handler/EasyHandle.php @@ -0,0 +1,112 @@ +headers); + + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + + if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) { + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + unset($headers[$normalizedKeys['content-encoding']]); + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + + $bodyLength = (int) $this->sink->getSize(); + if ($bodyLength) { + $headers[$normalizedKeys['content-length']] = $bodyLength; + } else { + unset($headers[$normalizedKeys['content-length']]); + } + } + } + + // Attach a response to the easy handle with the parsed headers. + $this->response = new Response( + $status, + $headers, + $this->sink, + $ver, + $reason + ); + } + + /** + * @param string $name + * + * @return void + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + $msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name; + throw new \BadMethodCallException($msg); + } +} diff --git a/lib/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php b/lib/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php new file mode 100644 index 00000000..a0988845 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php @@ -0,0 +1,42 @@ +|null $queue The parameters to be passed to the append function, as an indexed array. + * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled. + * @param callable|null $onRejected Callback to invoke when the return value is rejected. + */ + public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null) + { + $this->onFulfilled = $onFulfilled; + $this->onRejected = $onRejected; + + if ($queue) { + // array_values included for BC + $this->append(...array_values($queue)); + } + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!$this->queue) { + throw new \OutOfBoundsException('Mock queue is empty'); + } + + if (isset($options['delay']) && \is_numeric($options['delay'])) { + \usleep((int) $options['delay'] * 1000); + } + + $this->lastRequest = $request; + $this->lastOptions = $options; + $response = \array_shift($this->queue); + + if (isset($options['on_headers'])) { + if (!\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + try { + $options['on_headers']($response); + } catch (\Exception $e) { + $msg = 'An error was encountered during the on_headers event'; + $response = new RequestException($msg, $request, $response, $e); + } + } + + if (\is_callable($response)) { + $response = $response($request, $options); + } + + $response = $response instanceof \Throwable + ? P\Create::rejectionFor($response) + : P\Create::promiseFor($response); + + return $response->then( + function (?ResponseInterface $value) use ($request, $options) { + $this->invokeStats($request, $options, $value); + if ($this->onFulfilled) { + ($this->onFulfilled)($value); + } + + if ($value !== null && isset($options['sink'])) { + $contents = (string) $value->getBody(); + $sink = $options['sink']; + + if (\is_resource($sink)) { + \fwrite($sink, $contents); + } elseif (\is_string($sink)) { + \file_put_contents($sink, $contents); + } elseif ($sink instanceof StreamInterface) { + $sink->write($contents); + } + } + + return $value; + }, + function ($reason) use ($request, $options) { + $this->invokeStats($request, $options, null, $reason); + if ($this->onRejected) { + ($this->onRejected)($reason); + } + return P\Create::rejectionFor($reason); + } + ); + } + + /** + * Adds one or more variadic requests, exceptions, callables, or promises + * to the queue. + * + * @param mixed ...$values + */ + public function append(...$values): void + { + foreach ($values as $value) { + if ($value instanceof ResponseInterface + || $value instanceof \Throwable + || $value instanceof PromiseInterface + || \is_callable($value) + ) { + $this->queue[] = $value; + } else { + throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found ' . Utils::describeType($value)); + } + } + } + + /** + * Get the last received request. + */ + public function getLastRequest(): ?RequestInterface + { + return $this->lastRequest; + } + + /** + * Get the last received request options. + */ + public function getLastOptions(): array + { + return $this->lastOptions; + } + + /** + * Returns the number of remaining items in the queue. + */ + public function count(): int + { + return \count($this->queue); + } + + public function reset(): void + { + $this->queue = []; + } + + /** + * @param mixed $reason Promise or reason. + */ + private function invokeStats( + RequestInterface $request, + array $options, + ResponseInterface $response = null, + $reason = null + ): void { + if (isset($options['on_stats'])) { + $transferTime = $options['transfer_time'] ?? 0; + $stats = new TransferStats($request, $response, $transferTime, $reason); + ($options['on_stats'])($stats); + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/Handler/Proxy.php b/lib/guzzlehttp/guzzle/src/Handler/Proxy.php new file mode 100644 index 00000000..f045b526 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Handler/Proxy.php @@ -0,0 +1,51 @@ +withoutHeader('Expect'); + + // Append a content-length header if body size is zero to match + // cURL's behavior. + if (0 === $request->getBody()->getSize()) { + $request = $request->withHeader('Content-Length', '0'); + } + + return $this->createResponse( + $request, + $options, + $this->createStream($request, $options), + $startTime + ); + } catch (\InvalidArgumentException $e) { + throw $e; + } catch (\Exception $e) { + // Determine if the error was a networking error. + $message = $e->getMessage(); + // This list can probably get more comprehensive. + if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed + || false !== \strpos($message, 'Connection refused') + || false !== \strpos($message, "couldn't connect to host") // error on HHVM + || false !== \strpos($message, "connection attempt failed") + ) { + $e = new ConnectException($e->getMessage(), $request, $e); + } else { + $e = RequestException::wrapException($request, $e); + } + $this->invokeStats($options, $request, $startTime, null, $e); + + return P\Create::rejectionFor($e); + } + } + + private function invokeStats( + array $options, + RequestInterface $request, + ?float $startTime, + ResponseInterface $response = null, + \Throwable $error = null + ): void { + if (isset($options['on_stats'])) { + $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []); + ($options['on_stats'])($stats); + } + } + + /** + * @param resource $stream + */ + private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface + { + $hdrs = $this->lastHeaders; + $this->lastHeaders = []; + + try { + [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + [$stream, $headers] = $this->checkDecode($options, $headers, $stream); + $stream = Psr7\Utils::streamFor($stream); + $sink = $stream; + + if (\strcasecmp('HEAD', $request->getMethod())) { + $sink = $this->createSink($stream, $options); + } + + try { + $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered while creating the response', $request, null, $e) + ); + } + + if (isset($options['on_headers'])) { + try { + $options['on_headers']($response); + } catch (\Exception $e) { + return P\Create::rejectionFor( + new RequestException('An error was encountered during the on_headers event', $request, $response, $e) + ); + } + } + + // Do not drain when the request is a HEAD request because they have + // no body. + if ($sink !== $stream) { + $this->drain($stream, $sink, $response->getHeaderLine('Content-Length')); + } + + $this->invokeStats($options, $request, $startTime, $response, null); + + return new FulfilledPromise($response); + } + + private function createSink(StreamInterface $stream, array $options): StreamInterface + { + if (!empty($options['stream'])) { + return $stream; + } + + $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+'); + + return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink); + } + + /** + * @param resource $stream + */ + private function checkDecode(array $options, array $headers, $stream): array + { + // Automatically decode responses when instructed. + if (!empty($options['decode_content'])) { + $normalizedKeys = Utils::normalizeHeaderKeys($headers); + if (isset($normalizedKeys['content-encoding'])) { + $encoding = $headers[$normalizedKeys['content-encoding']]; + if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { + $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream)); + $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; + + // Remove content-encoding header + unset($headers[$normalizedKeys['content-encoding']]); + + // Fix content-length header + if (isset($normalizedKeys['content-length'])) { + $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; + $length = (int) $stream->getSize(); + if ($length === 0) { + unset($headers[$normalizedKeys['content-length']]); + } else { + $headers[$normalizedKeys['content-length']] = [$length]; + } + } + } + } + } + + return [$stream, $headers]; + } + + /** + * Drains the source stream into the "sink" client option. + * + * @param string $contentLength Header specifying the amount of + * data to read. + * + * @throws \RuntimeException when the sink option is invalid. + */ + private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface + { + // If a content-length header is provided, then stop reading once + // that number of bytes has been read. This can prevent infinitely + // reading from a stream when dealing with servers that do not honor + // Connection: Close headers. + Psr7\Utils::copyToStream( + $source, + $sink, + (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 + ); + + $sink->seek(0); + $source->close(); + + return $sink; + } + + /** + * Create a resource and check to ensure it was created successfully + * + * @param callable $callback Callable that returns stream resource + * + * @return resource + * + * @throws \RuntimeException on error + */ + private function createResource(callable $callback) + { + $errors = []; + \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { + $errors[] = [ + 'message' => $msg, + 'file' => $file, + 'line' => $line + ]; + return true; + }); + + try { + $resource = $callback(); + } finally { + \restore_error_handler(); + } + + if (!$resource) { + $message = 'Error creating resource: '; + foreach ($errors as $err) { + foreach ($err as $key => $value) { + $message .= "[$key] $value" . \PHP_EOL; + } + } + throw new \RuntimeException(\trim($message)); + } + + return $resource; + } + + /** + * @return resource + */ + private function createStream(RequestInterface $request, array $options) + { + static $methods; + if (!$methods) { + $methods = \array_flip(\get_class_methods(__CLASS__)); + } + + // HTTP/1.1 streams using the PHP stream wrapper require a + // Connection: close header + if ($request->getProtocolVersion() == '1.1' + && !$request->hasHeader('Connection') + ) { + $request = $request->withHeader('Connection', 'close'); + } + + // Ensure SSL is verified by default + if (!isset($options['verify'])) { + $options['verify'] = true; + } + + $params = []; + $context = $this->getDefaultContext($request); + + if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { + throw new \InvalidArgumentException('on_headers must be callable'); + } + + if (!empty($options)) { + foreach ($options as $key => $value) { + $method = "add_{$key}"; + if (isset($methods[$method])) { + $this->{$method}($request, $context, $value, $params); + } + } + } + + if (isset($options['stream_context'])) { + if (!\is_array($options['stream_context'])) { + throw new \InvalidArgumentException('stream_context must be an array'); + } + $context = \array_replace_recursive($context, $options['stream_context']); + } + + // Microsoft NTLM authentication only supported with curl handler + if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { + throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); + } + + $uri = $this->resolveHost($request, $options); + + $contextResource = $this->createResource( + static function () use ($context, $params) { + return \stream_context_create($context, $params); + } + ); + + return $this->createResource( + function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { + $resource = @\fopen((string) $uri, 'r', false, $contextResource); + $this->lastHeaders = $http_response_header; + + if (false === $resource) { + throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context); + } + + if (isset($options['read_timeout'])) { + $readTimeout = $options['read_timeout']; + $sec = (int) $readTimeout; + $usec = ($readTimeout - $sec) * 100000; + \stream_set_timeout($resource, $sec, $usec); + } + + return $resource; + } + ); + } + + private function resolveHost(RequestInterface $request, array $options): UriInterface + { + $uri = $request->getUri(); + + if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { + if ('v4' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_A); + if (false === $records || !isset($records[0]['ip'])) { + throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost($records[0]['ip']); + } + if ('v6' === $options['force_ip_resolve']) { + $records = \dns_get_record($uri->getHost(), \DNS_AAAA); + if (false === $records || !isset($records[0]['ipv6'])) { + throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request); + } + return $uri->withHost('[' . $records[0]['ipv6'] . ']'); + } + } + + return $uri; + } + + private function getDefaultContext(RequestInterface $request): array + { + $headers = ''; + foreach ($request->getHeaders() as $name => $value) { + foreach ($value as $val) { + $headers .= "$name: $val\r\n"; + } + } + + $context = [ + 'http' => [ + 'method' => $request->getMethod(), + 'header' => $headers, + 'protocol_version' => $request->getProtocolVersion(), + 'ignore_errors' => true, + 'follow_location' => 0, + ], + ]; + + $body = (string) $request->getBody(); + + if (!empty($body)) { + $context['http']['content'] = $body; + // Prevent the HTTP handler from adding a Content-Type header. + if (!$request->hasHeader('Content-Type')) { + $context['http']['header'] .= "Content-Type:\r\n"; + } + } + + $context['http']['header'] = \rtrim($context['http']['header']); + + return $context; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void + { + $uri = null; + + if (!\is_array($value)) { + $uri = $value; + } else { + $scheme = $request->getUri()->getScheme(); + if (isset($value[$scheme])) { + if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) { + $uri = $value[$scheme]; + } + } + } + + if (!$uri) { + return; + } + + $parsed = $this->parse_proxy($uri); + $options['http']['proxy'] = $parsed['proxy']; + + if ($parsed['auth']) { + if (!isset($options['http']['header'])) { + $options['http']['header'] = []; + } + $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}"; + } + } + + /** + * Parses the given proxy URL to make it compatible with the format PHP's stream context expects. + */ + private function parse_proxy(string $url): array + { + $parsed = \parse_url($url); + + if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') { + if (isset($parsed['host']) && isset($parsed['port'])) { + $auth = null; + if (isset($parsed['user']) && isset($parsed['pass'])) { + $auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}"); + } + + return [ + 'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}", + 'auth' => $auth ? "Basic {$auth}" : null, + ]; + } + } + + // Return proxy as-is. + return [ + 'proxy' => $url, + 'auth' => null, + ]; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value > 0) { + $options['http']['timeout'] = $value; + } + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + $options['ssl']['verify_peer'] = false; + $options['ssl']['verify_peer_name'] = false; + + return; + } + + if (\is_string($value)) { + $options['ssl']['cafile'] = $value; + if (!\file_exists($value)) { + throw new \RuntimeException("SSL CA bundle not found: $value"); + } + } elseif ($value !== true) { + throw new \InvalidArgumentException('Invalid verify request option'); + } + + $options['ssl']['verify_peer'] = true; + $options['ssl']['verify_peer_name'] = true; + $options['ssl']['allow_self_signed'] = false; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void + { + if (\is_array($value)) { + $options['ssl']['passphrase'] = $value[1]; + $value = $value[0]; + } + + if (!\file_exists($value)) { + throw new \RuntimeException("SSL certificate not found: {$value}"); + } + + $options['ssl']['local_cert'] = $value; + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void + { + self::addNotification( + $params, + static function ($code, $a, $b, $c, $transferred, $total) use ($value) { + if ($code == \STREAM_NOTIFY_PROGRESS) { + // The upload progress cannot be determined. Use 0 for cURL compatibility: + // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html + $value($total, $transferred, 0, 0); + } + } + ); + } + + /** + * @param mixed $value as passed via Request transfer options. + */ + private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void + { + if ($value === false) { + return; + } + + static $map = [ + \STREAM_NOTIFY_CONNECT => 'CONNECT', + \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', + \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', + \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', + \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', + \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', + \STREAM_NOTIFY_PROGRESS => 'PROGRESS', + \STREAM_NOTIFY_FAILURE => 'FAILURE', + \STREAM_NOTIFY_COMPLETED => 'COMPLETED', + \STREAM_NOTIFY_RESOLVE => 'RESOLVE', + ]; + static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; + + $value = Utils::debugResource($value); + $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); + self::addNotification( + $params, + static function (int $code, ...$passed) use ($ident, $value, $map, $args): void { + \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); + foreach (\array_filter($passed) as $i => $v) { + \fwrite($value, $args[$i] . ': "' . $v . '" '); + } + \fwrite($value, "\n"); + } + ); + } + + private static function addNotification(array &$params, callable $notify): void + { + // Wrap the existing function if needed. + if (!isset($params['notification'])) { + $params['notification'] = $notify; + } else { + $params['notification'] = self::callArray([ + $params['notification'], + $notify + ]); + } + } + + private static function callArray(array $functions): callable + { + return static function (...$args) use ($functions) { + foreach ($functions as $fn) { + $fn(...$args); + } + }; + } +} diff --git a/lib/guzzlehttp/guzzle/src/HandlerStack.php b/lib/guzzlehttp/guzzle/src/HandlerStack.php new file mode 100644 index 00000000..e0a1d119 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/HandlerStack.php @@ -0,0 +1,275 @@ +push(Middleware::httpErrors(), 'http_errors'); + $stack->push(Middleware::redirect(), 'allow_redirects'); + $stack->push(Middleware::cookies(), 'cookies'); + $stack->push(Middleware::prepareBody(), 'prepare_body'); + + return $stack; + } + + /** + * @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler. + */ + public function __construct(callable $handler = null) + { + $this->handler = $handler; + } + + /** + * Invokes the handler stack as a composed handler + * + * @return ResponseInterface|PromiseInterface + */ + public function __invoke(RequestInterface $request, array $options) + { + $handler = $this->resolve(); + + return $handler($request, $options); + } + + /** + * Dumps a string representation of the stack. + * + * @return string + */ + public function __toString() + { + $depth = 0; + $stack = []; + + if ($this->handler !== null) { + $stack[] = "0) Handler: " . $this->debugCallable($this->handler); + } + + $result = ''; + foreach (\array_reverse($this->stack) as $tuple) { + $depth++; + $str = "{$depth}) Name: '{$tuple[1]}', "; + $str .= "Function: " . $this->debugCallable($tuple[0]); + $result = "> {$str}\n{$result}"; + $stack[] = $str; + } + + foreach (\array_keys($stack) as $k) { + $result .= "< {$stack[$k]}\n"; + } + + return $result; + } + + /** + * Set the HTTP handler that actually returns a promise. + * + * @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and + * returns a Promise. + */ + public function setHandler(callable $handler): void + { + $this->handler = $handler; + $this->cached = null; + } + + /** + * Returns true if the builder has a handler. + */ + public function hasHandler(): bool + { + return $this->handler !== null ; + } + + /** + * Unshift a middleware to the bottom of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function unshift(callable $middleware, ?string $name = null): void + { + \array_unshift($this->stack, [$middleware, $name]); + $this->cached = null; + } + + /** + * Push a middleware to the top of the stack. + * + * @param callable(callable): callable $middleware Middleware function + * @param string $name Name to register for this middleware. + */ + public function push(callable $middleware, string $name = ''): void + { + $this->stack[] = [$middleware, $name]; + $this->cached = null; + } + + /** + * Add a middleware before another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function before(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, true); + } + + /** + * Add a middleware after another middleware by name. + * + * @param string $findName Middleware to find + * @param callable(callable): callable $middleware Middleware function + * @param string $withName Name to register for this middleware. + */ + public function after(string $findName, callable $middleware, string $withName = ''): void + { + $this->splice($findName, $withName, $middleware, false); + } + + /** + * Remove a middleware by instance or name from the stack. + * + * @param callable|string $remove Middleware to remove by instance or name. + */ + public function remove($remove): void + { + if (!is_string($remove) && !is_callable($remove)) { + trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__); + } + + $this->cached = null; + $idx = \is_callable($remove) ? 0 : 1; + $this->stack = \array_values(\array_filter( + $this->stack, + static function ($tuple) use ($idx, $remove) { + return $tuple[$idx] !== $remove; + } + )); + } + + /** + * Compose the middleware and handler into a single callable function. + * + * @return callable(RequestInterface, array): PromiseInterface + */ + public function resolve(): callable + { + if ($this->cached === null) { + if (($prev = $this->handler) === null) { + throw new \LogicException('No handler has been specified'); + } + + foreach (\array_reverse($this->stack) as $fn) { + /** @var callable(RequestInterface, array): PromiseInterface $prev */ + $prev = $fn[0]($prev); + } + + $this->cached = $prev; + } + + return $this->cached; + } + + private function findByName(string $name): int + { + foreach ($this->stack as $k => $v) { + if ($v[1] === $name) { + return $k; + } + } + + throw new \InvalidArgumentException("Middleware not found: $name"); + } + + /** + * Splices a function into the middleware list at a specific position. + */ + private function splice(string $findName, string $withName, callable $middleware, bool $before): void + { + $this->cached = null; + $idx = $this->findByName($findName); + $tuple = [$middleware, $withName]; + + if ($before) { + if ($idx === 0) { + \array_unshift($this->stack, $tuple); + } else { + $replacement = [$tuple, $this->stack[$idx]]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } elseif ($idx === \count($this->stack) - 1) { + $this->stack[] = $tuple; + } else { + $replacement = [$this->stack[$idx], $tuple]; + \array_splice($this->stack, $idx, 1, $replacement); + } + } + + /** + * Provides a debug string for a given callable. + * + * @param callable|string $fn Function to write as a string. + */ + private function debugCallable($fn): string + { + if (\is_string($fn)) { + return "callable({$fn})"; + } + + if (\is_array($fn)) { + return \is_string($fn[0]) + ? "callable({$fn[0]}::{$fn[1]})" + : "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])"; + } + + /** @var object $fn */ + return 'callable(' . \spl_object_hash($fn) . ')'; + } +} diff --git a/lib/guzzlehttp/guzzle/src/MessageFormatter.php b/lib/guzzlehttp/guzzle/src/MessageFormatter.php new file mode 100644 index 00000000..238770f8 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/MessageFormatter.php @@ -0,0 +1,198 @@ +>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}"; + public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}'; + + /** + * @var string Template used to format log messages + */ + private $template; + + /** + * @param string $template Log message template + */ + public function __construct(?string $template = self::CLF) + { + $this->template = $template ?: self::CLF; + } + + /** + * Returns a formatted message string. + * + * @param RequestInterface $request Request that was sent + * @param ResponseInterface|null $response Response that was received + * @param \Throwable|null $error Exception that was received + */ + public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string + { + $cache = []; + + /** @var string */ + return \preg_replace_callback( + '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', + function (array $matches) use ($request, $response, $error, &$cache) { + if (isset($cache[$matches[1]])) { + return $cache[$matches[1]]; + } + + $result = ''; + switch ($matches[1]) { + case 'request': + $result = Psr7\Message::toString($request); + break; + case 'response': + $result = $response ? Psr7\Message::toString($response) : ''; + break; + case 'req_headers': + $result = \trim($request->getMethod() + . ' ' . $request->getRequestTarget()) + . ' HTTP/' . $request->getProtocolVersion() . "\r\n" + . $this->headers($request); + break; + case 'res_headers': + $result = $response ? + \sprintf( + 'HTTP/%s %d %s', + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ) . "\r\n" . $this->headers($response) + : 'NULL'; + break; + case 'req_body': + $result = $request->getBody()->__toString(); + break; + case 'res_body': + if (!$response instanceof ResponseInterface) { + $result = 'NULL'; + break; + } + + $body = $response->getBody(); + + if (!$body->isSeekable()) { + $result = 'RESPONSE_NOT_LOGGEABLE'; + break; + } + + $result = $response->getBody()->__toString(); + break; + case 'ts': + case 'date_iso_8601': + $result = \gmdate('c'); + break; + case 'date_common_log': + $result = \date('d/M/Y:H:i:s O'); + break; + case 'method': + $result = $request->getMethod(); + break; + case 'version': + $result = $request->getProtocolVersion(); + break; + case 'uri': + case 'url': + $result = $request->getUri(); + break; + case 'target': + $result = $request->getRequestTarget(); + break; + case 'req_version': + $result = $request->getProtocolVersion(); + break; + case 'res_version': + $result = $response + ? $response->getProtocolVersion() + : 'NULL'; + break; + case 'host': + $result = $request->getHeaderLine('Host'); + break; + case 'hostname': + $result = \gethostname(); + break; + case 'code': + $result = $response ? $response->getStatusCode() : 'NULL'; + break; + case 'phrase': + $result = $response ? $response->getReasonPhrase() : 'NULL'; + break; + case 'error': + $result = $error ? $error->getMessage() : 'NULL'; + break; + default: + // handle prefixed dynamic headers + if (\strpos($matches[1], 'req_header_') === 0) { + $result = $request->getHeaderLine(\substr($matches[1], 11)); + } elseif (\strpos($matches[1], 'res_header_') === 0) { + $result = $response + ? $response->getHeaderLine(\substr($matches[1], 11)) + : 'NULL'; + } + } + + $cache[$matches[1]] = $result; + return $result; + }, + $this->template + ); + } + + /** + * Get headers from message as string + */ + private function headers(MessageInterface $message): string + { + $result = ''; + foreach ($message->getHeaders() as $name => $values) { + $result .= $name . ': ' . \implode(', ', $values) . "\r\n"; + } + + return \trim($result); + } +} diff --git a/lib/guzzlehttp/guzzle/src/MessageFormatterInterface.php b/lib/guzzlehttp/guzzle/src/MessageFormatterInterface.php new file mode 100644 index 00000000..a39ac248 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/MessageFormatterInterface.php @@ -0,0 +1,18 @@ +withCookieHeader($request); + return $handler($request, $options) + ->then( + static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface { + $cookieJar->extractCookies($request, $response); + return $response; + } + ); + }; + }; + } + + /** + * Middleware that throws exceptions for 4xx or 5xx responses when the + * "http_errors" request option is set to true. + * + * @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages. + * + * @return callable(callable): callable Returns a function that accepts the next handler. + */ + public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable + { + return static function (callable $handler) use ($bodySummarizer): callable { + return static function ($request, array $options) use ($handler, $bodySummarizer) { + if (empty($options['http_errors'])) { + return $handler($request, $options); + } + return $handler($request, $options)->then( + static function (ResponseInterface $response) use ($request, $bodySummarizer) { + $code = $response->getStatusCode(); + if ($code < 400) { + return $response; + } + throw RequestException::create($request, $response, null, [], $bodySummarizer); + } + ); + }; + }; + } + + /** + * Middleware that pushes history data to an ArrayAccess container. + * + * @param array|\ArrayAccess $container Container to hold the history (by reference). + * + * @return callable(callable): callable Returns a function that accepts the next handler. + * + * @throws \InvalidArgumentException if container is not an array or ArrayAccess. + */ + public static function history(&$container): callable + { + if (!\is_array($container) && !$container instanceof \ArrayAccess) { + throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess'); + } + + return static function (callable $handler) use (&$container): callable { + return static function (RequestInterface $request, array $options) use ($handler, &$container) { + return $handler($request, $options)->then( + static function ($value) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => $value, + 'error' => null, + 'options' => $options + ]; + return $value; + }, + static function ($reason) use ($request, &$container, $options) { + $container[] = [ + 'request' => $request, + 'response' => null, + 'error' => $reason, + 'options' => $options + ]; + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * Middleware that invokes a callback before and after sending a request. + * + * The provided listener cannot modify or alter the response. It simply + * "taps" into the chain to be notified before returning the promise. The + * before listener accepts a request and options array, and the after + * listener accepts a request, options array, and response promise. + * + * @param callable $before Function to invoke before forwarding the request. + * @param callable $after Function invoked after forwarding. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function tap(callable $before = null, callable $after = null): callable + { + return static function (callable $handler) use ($before, $after): callable { + return static function (RequestInterface $request, array $options) use ($handler, $before, $after) { + if ($before) { + $before($request, $options); + } + $response = $handler($request, $options); + if ($after) { + $after($request, $options, $response); + } + return $response; + }; + }; + } + + /** + * Middleware that handles request redirects. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function redirect(): callable + { + return static function (callable $handler): RedirectMiddleware { + return new RedirectMiddleware($handler); + }; + } + + /** + * Middleware that retries requests based on the boolean result of + * invoking the provided "decider" function. + * + * If no delay function is provided, a simple implementation of exponential + * backoff will be utilized. + * + * @param callable $decider Function that accepts the number of retries, + * a request, [response], and [exception] and + * returns true if the request is to be retried. + * @param callable $delay Function that accepts the number of retries and + * returns the number of milliseconds to delay. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function retry(callable $decider, callable $delay = null): callable + { + return static function (callable $handler) use ($decider, $delay): RetryMiddleware { + return new RetryMiddleware($decider, $handler, $delay); + }; + } + + /** + * Middleware that logs requests, responses, and errors using a message + * formatter. + * + * @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests. + * + * @param LoggerInterface $logger Logs messages. + * @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings. + * @param string $logLevel Level at which to log requests. + * + * @return callable Returns a function that accepts the next handler. + */ + public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable + { + // To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter + if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) { + throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class)); + } + + return static function (callable $handler) use ($logger, $formatter, $logLevel): callable { + return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) { + return $handler($request, $options)->then( + static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface { + $message = $formatter->format($request, $response); + $logger->log($logLevel, $message); + return $response; + }, + static function ($reason) use ($logger, $request, $formatter): PromiseInterface { + $response = $reason instanceof RequestException ? $reason->getResponse() : null; + $message = $formatter->format($request, $response, P\Create::exceptionFor($reason)); + $logger->error($message); + return P\Create::rejectionFor($reason); + } + ); + }; + }; + } + + /** + * This middleware adds a default content-type if possible, a default + * content-length or transfer-encoding header, and the expect header. + */ + public static function prepareBody(): callable + { + return static function (callable $handler): PrepareBodyMiddleware { + return new PrepareBodyMiddleware($handler); + }; + } + + /** + * Middleware that applies a map function to the request before passing to + * the next handler. + * + * @param callable $fn Function that accepts a RequestInterface and returns + * a RequestInterface. + */ + public static function mapRequest(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($fn($request), $options); + }; + }; + } + + /** + * Middleware that applies a map function to the resolved promise's + * response. + * + * @param callable $fn Function that accepts a ResponseInterface and + * returns a ResponseInterface. + */ + public static function mapResponse(callable $fn): callable + { + return static function (callable $handler) use ($fn): callable { + return static function (RequestInterface $request, array $options) use ($handler, $fn) { + return $handler($request, $options)->then($fn); + }; + }; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Pool.php b/lib/guzzlehttp/guzzle/src/Pool.php new file mode 100644 index 00000000..6277c61f --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Pool.php @@ -0,0 +1,125 @@ + $rfn) { + if ($rfn instanceof RequestInterface) { + yield $key => $client->sendAsync($rfn, $opts); + } elseif (\is_callable($rfn)) { + yield $key => $rfn($opts); + } else { + throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.'); + } + } + }; + + $this->each = new EachPromise($requests(), $config); + } + + /** + * Get promise + */ + public function promise(): PromiseInterface + { + return $this->each->promise(); + } + + /** + * Sends multiple requests concurrently and returns an array of responses + * and exceptions that uses the same ordering as the provided requests. + * + * IMPORTANT: This method keeps every request and response in memory, and + * as such, is NOT recommended when sending a large number or an + * indeterminate number of requests concurrently. + * + * @param ClientInterface $client Client used to send the requests + * @param array|\Iterator $requests Requests to send concurrently. + * @param array $options Passes through the options available in + * {@see \GuzzleHttp\Pool::__construct} + * + * @return array Returns an array containing the response or an exception + * in the same order that the requests were sent. + * + * @throws \InvalidArgumentException if the event format is incorrect. + */ + public static function batch(ClientInterface $client, $requests, array $options = []): array + { + $res = []; + self::cmpCallback($options, 'fulfilled', $res); + self::cmpCallback($options, 'rejected', $res); + $pool = new static($client, $requests, $options); + $pool->promise()->wait(); + \ksort($res); + + return $res; + } + + /** + * Execute callback(s) + */ + private static function cmpCallback(array &$options, string $name, array &$results): void + { + if (!isset($options[$name])) { + $options[$name] = static function ($v, $k) use (&$results) { + $results[$k] = $v; + }; + } else { + $currentFn = $options[$name]; + $options[$name] = static function ($v, $k) use (&$results, $currentFn) { + $currentFn($v, $k); + $results[$k] = $v; + }; + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php b/lib/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php new file mode 100644 index 00000000..7ca62833 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php @@ -0,0 +1,104 @@ +nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + // Don't do anything if the request has no body. + if ($request->getBody()->getSize() === 0) { + return $fn($request, $options); + } + + $modify = []; + + // Add a default content-type if possible. + if (!$request->hasHeader('Content-Type')) { + if ($uri = $request->getBody()->getMetadata('uri')) { + if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) { + $modify['set_headers']['Content-Type'] = $type; + } + } + } + + // Add a default content-length or transfer-encoding header. + if (!$request->hasHeader('Content-Length') + && !$request->hasHeader('Transfer-Encoding') + ) { + $size = $request->getBody()->getSize(); + if ($size !== null) { + $modify['set_headers']['Content-Length'] = $size; + } else { + $modify['set_headers']['Transfer-Encoding'] = 'chunked'; + } + } + + // Add the expect header if needed. + $this->addExpectHeader($request, $options, $modify); + + return $fn(Psr7\Utils::modifyRequest($request, $modify), $options); + } + + /** + * Add expect header + */ + private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void + { + // Determine if the Expect header should be used + if ($request->hasHeader('Expect')) { + return; + } + + $expect = $options['expect'] ?? null; + + // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0 + if ($expect === false || $request->getProtocolVersion() < 1.1) { + return; + } + + // The expect header is unconditionally enabled + if ($expect === true) { + $modify['set_headers']['Expect'] = '100-Continue'; + return; + } + + // By default, send the expect header when the payload is > 1mb + if ($expect === null) { + $expect = 1048576; + } + + // Always add if the body cannot be rewound, the size cannot be + // determined, or the size is greater than the cutoff threshold + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { + $modify['set_headers']['Expect'] = '100-Continue'; + } + } +} diff --git a/lib/guzzlehttp/guzzle/src/RedirectMiddleware.php b/lib/guzzlehttp/guzzle/src/RedirectMiddleware.php new file mode 100644 index 00000000..1dd38614 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/RedirectMiddleware.php @@ -0,0 +1,216 @@ + 5, + 'protocols' => ['http', 'https'], + 'strict' => false, + 'referer' => false, + 'track_redirects' => false, + ]; + + /** + * @var callable(RequestInterface, array): PromiseInterface + */ + private $nextHandler; + + /** + * @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke. + */ + public function __construct(callable $nextHandler) + { + $this->nextHandler = $nextHandler; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + $fn = $this->nextHandler; + + if (empty($options['allow_redirects'])) { + return $fn($request, $options); + } + + if ($options['allow_redirects'] === true) { + $options['allow_redirects'] = self::$defaultSettings; + } elseif (!\is_array($options['allow_redirects'])) { + throw new \InvalidArgumentException('allow_redirects must be true, false, or array'); + } else { + // Merge the default settings with the provided settings + $options['allow_redirects'] += self::$defaultSettings; + } + + if (empty($options['allow_redirects']['max'])) { + return $fn($request, $options); + } + + return $fn($request, $options) + ->then(function (ResponseInterface $response) use ($request, $options) { + return $this->checkRedirect($request, $options, $response); + }); + } + + /** + * @return ResponseInterface|PromiseInterface + */ + public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response) + { + if (\strpos((string) $response->getStatusCode(), '3') !== 0 + || !$response->hasHeader('Location') + ) { + return $response; + } + + $this->guardMax($request, $response, $options); + $nextRequest = $this->modifyRequest($request, $options, $response); + + if (isset($options['allow_redirects']['on_redirect'])) { + ($options['allow_redirects']['on_redirect'])( + $request, + $response, + $nextRequest->getUri() + ); + } + + $promise = $this($nextRequest, $options); + + // Add headers to be able to track history of redirects. + if (!empty($options['allow_redirects']['track_redirects'])) { + return $this->withTracking( + $promise, + (string) $nextRequest->getUri(), + $response->getStatusCode() + ); + } + + return $promise; + } + + /** + * Enable tracking on promise. + */ + private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface + { + return $promise->then( + static function (ResponseInterface $response) use ($uri, $statusCode) { + // Note that we are pushing to the front of the list as this + // would be an earlier response than what is currently present + // in the history header. + $historyHeader = $response->getHeader(self::HISTORY_HEADER); + $statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER); + \array_unshift($historyHeader, $uri); + \array_unshift($statusHeader, (string) $statusCode); + + return $response->withHeader(self::HISTORY_HEADER, $historyHeader) + ->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader); + } + ); + } + + /** + * Check for too many redirects + * + * @throws TooManyRedirectsException Too many redirects. + */ + private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void + { + $current = $options['__redirect_count'] + ?? 0; + $options['__redirect_count'] = $current + 1; + $max = $options['allow_redirects']['max']; + + if ($options['__redirect_count'] > $max) { + throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response); + } + } + + public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface + { + // Request modifications to apply. + $modify = []; + $protocols = $options['allow_redirects']['protocols']; + + // Use a GET request if this is an entity enclosing request and we are + // not forcing RFC compliance, but rather emulating what all browsers + // would do. + $statusCode = $response->getStatusCode(); + if ($statusCode == 303 || + ($statusCode <= 302 && !$options['allow_redirects']['strict']) + ) { + $safeMethods = ['GET', 'HEAD', 'OPTIONS']; + $requestMethod = $request->getMethod(); + + $modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET'; + $modify['body'] = ''; + } + + $uri = $this->redirectUri($request, $response, $protocols); + if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) { + $idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion']; + $uri = Utils::idnUriConvert($uri, $idnOptions); + } + + $modify['uri'] = $uri; + Psr7\Message::rewindBody($request); + + // Add the Referer header if it is told to do so and only + // add the header if we are not redirecting from https to http. + if ($options['allow_redirects']['referer'] + && $modify['uri']->getScheme() === $request->getUri()->getScheme() + ) { + $uri = $request->getUri()->withUserInfo(''); + $modify['set_headers']['Referer'] = (string) $uri; + } else { + $modify['remove_headers'][] = 'Referer'; + } + + // Remove Authorization header if host is different. + if ($request->getUri()->getHost() !== $modify['uri']->getHost()) { + $modify['remove_headers'][] = 'Authorization'; + } + + return Psr7\Utils::modifyRequest($request, $modify); + } + + /** + * Set the appropriate URL on the request based on the location header + */ + private function redirectUri(RequestInterface $request, ResponseInterface $response, array $protocols): UriInterface + { + $location = Psr7\UriResolver::resolve( + $request->getUri(), + new Psr7\Uri($response->getHeaderLine('Location')) + ); + + // Ensure that the redirect URI is allowed based on the protocols. + if (!\in_array($location->getScheme(), $protocols)) { + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response); + } + + return $location; + } +} diff --git a/lib/guzzlehttp/guzzle/src/RequestOptions.php b/lib/guzzlehttp/guzzle/src/RequestOptions.php new file mode 100644 index 00000000..20b31bc2 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/RequestOptions.php @@ -0,0 +1,264 @@ +decider = $decider; + $this->nextHandler = $nextHandler; + $this->delay = $delay ?: __CLASS__ . '::exponentialDelay'; + } + + /** + * Default exponential backoff delay function. + * + * @return int milliseconds. + */ + public static function exponentialDelay(int $retries): int + { + return (int) \pow(2, $retries - 1) * 1000; + } + + public function __invoke(RequestInterface $request, array $options): PromiseInterface + { + if (!isset($options['retries'])) { + $options['retries'] = 0; + } + + $fn = $this->nextHandler; + return $fn($request, $options) + ->then( + $this->onFulfilled($request, $options), + $this->onRejected($request, $options) + ); + } + + /** + * Execute fulfilled closure + */ + private function onFulfilled(RequestInterface $request, array $options): callable + { + return function ($value) use ($request, $options) { + if (!($this->decider)( + $options['retries'], + $request, + $value, + null + )) { + return $value; + } + return $this->doRetry($request, $options, $value); + }; + } + + /** + * Execute rejected closure + */ + private function onRejected(RequestInterface $req, array $options): callable + { + return function ($reason) use ($req, $options) { + if (!($this->decider)( + $options['retries'], + $req, + null, + $reason + )) { + return P\Create::rejectionFor($reason); + } + return $this->doRetry($req, $options); + }; + } + + private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface + { + $options['delay'] = ($this->delay)(++$options['retries'], $response); + + return $this($request, $options); + } +} diff --git a/lib/guzzlehttp/guzzle/src/TransferStats.php b/lib/guzzlehttp/guzzle/src/TransferStats.php new file mode 100644 index 00000000..93fa334c --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/TransferStats.php @@ -0,0 +1,133 @@ +request = $request; + $this->response = $response; + $this->transferTime = $transferTime; + $this->handlerErrorData = $handlerErrorData; + $this->handlerStats = $handlerStats; + } + + public function getRequest(): RequestInterface + { + return $this->request; + } + + /** + * Returns the response that was received (if any). + */ + public function getResponse(): ?ResponseInterface + { + return $this->response; + } + + /** + * Returns true if a response was received. + */ + public function hasResponse(): bool + { + return $this->response !== null; + } + + /** + * Gets handler specific error data. + * + * This might be an exception, a integer representing an error code, or + * anything else. Relying on this value assumes that you know what handler + * you are using. + * + * @return mixed + */ + public function getHandlerErrorData() + { + return $this->handlerErrorData; + } + + /** + * Get the effective URI the request was sent to. + */ + public function getEffectiveUri(): UriInterface + { + return $this->request->getUri(); + } + + /** + * Get the estimated time the request was being transferred by the handler. + * + * @return float|null Time in seconds. + */ + public function getTransferTime(): ?float + { + return $this->transferTime; + } + + /** + * Gets an array of all of the handler specific transfer data. + */ + public function getHandlerStats(): array + { + return $this->handlerStats; + } + + /** + * Get a specific handler statistic from the handler by name. + * + * @param string $stat Handler specific transfer stat to retrieve. + * + * @return mixed|null + */ + public function getHandlerStat(string $stat) + { + return $this->handlerStats[$stat] ?? null; + } +} diff --git a/lib/guzzlehttp/guzzle/src/Utils.php b/lib/guzzlehttp/guzzle/src/Utils.php new file mode 100644 index 00000000..91591da2 --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/Utils.php @@ -0,0 +1,382 @@ +getHost()) { + $asciiHost = self::idnToAsci($uri->getHost(), $options, $info); + if ($asciiHost === false) { + $errorBitSet = $info['errors'] ?? 0; + + $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool { + return substr($name, 0, 11) === 'IDNA_ERROR_'; + }); + + $errors = []; + foreach ($errorConstants as $errorConstant) { + if ($errorBitSet & constant($errorConstant)) { + $errors[] = $errorConstant; + } + } + + $errorMessage = 'IDN conversion failed'; + if ($errors) { + $errorMessage .= ' (errors: ' . implode(', ', $errors) . ')'; + } + + throw new InvalidArgumentException($errorMessage); + } + if ($uri->getHost() !== $asciiHost) { + // Replace URI only if the ASCII version is different + $uri = $uri->withHost($asciiHost); + } + } + + return $uri; + } + + /** + * @internal + */ + public static function getenv(string $name): ?string + { + if (isset($_SERVER[$name])) { + return (string) $_SERVER[$name]; + } + + if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) { + return (string) $value; + } + + return null; + } + + /** + * @return string|false + */ + private static function idnToAsci(string $domain, int $options, ?array &$info = []) + { + if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) { + return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info); + } + + throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old'); + } +} diff --git a/lib/guzzlehttp/guzzle/src/functions.php b/lib/guzzlehttp/guzzle/src/functions.php new file mode 100644 index 00000000..a70d2cbf --- /dev/null +++ b/lib/guzzlehttp/guzzle/src/functions.php @@ -0,0 +1,167 @@ + +Copyright (c) 2015 Graham Campbell +Copyright (c) 2017 Tobias Schultze +Copyright (c) 2020 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/lib/guzzlehttp/promises/Makefile b/lib/guzzlehttp/promises/Makefile new file mode 100644 index 00000000..8d5b3ef9 --- /dev/null +++ b/lib/guzzlehttp/promises/Makefile @@ -0,0 +1,13 @@ +all: clean test + +test: + vendor/bin/phpunit + +coverage: + vendor/bin/phpunit --coverage-html=artifacts/coverage + +view-coverage: + open artifacts/coverage/index.html + +clean: + rm -rf artifacts/* diff --git a/lib/guzzlehttp/promises/README.md b/lib/guzzlehttp/promises/README.md new file mode 100644 index 00000000..c175fec7 --- /dev/null +++ b/lib/guzzlehttp/promises/README.md @@ -0,0 +1,547 @@ +# Guzzle Promises + +[Promises/A+](https://promisesaplus.com/) implementation that handles promise +chaining and resolution iteratively, allowing for "infinite" promise chaining +while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/) +for a general introduction to promises. + +- [Features](#features) +- [Quick start](#quick-start) +- [Synchronous wait](#synchronous-wait) +- [Cancellation](#cancellation) +- [API](#api) + - [Promise](#promise) + - [FulfilledPromise](#fulfilledpromise) + - [RejectedPromise](#rejectedpromise) +- [Promise interop](#promise-interop) +- [Implementation notes](#implementation-notes) + + +# Features + +- [Promises/A+](https://promisesaplus.com/) implementation. +- Promise resolution and chaining is handled iteratively, allowing for + "infinite" promise chaining. +- Promises have a synchronous `wait` method. +- Promises can be cancelled. +- Works with any object that has a `then` function. +- C# style async/await coroutine promises using + `GuzzleHttp\Promise\Coroutine::of()`. + + +# Quick start + +A *promise* represents the eventual result of an asynchronous operation. The +primary way of interacting with a promise is through its `then` method, which +registers callbacks to receive either a promise's eventual value or the reason +why the promise cannot be fulfilled. + + +## Callbacks + +Callbacks are registered with the `then` method by providing an optional +`$onFulfilled` followed by an optional `$onRejected` function. + + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then( + // $onFulfilled + function ($value) { + echo 'The promise was fulfilled.'; + }, + // $onRejected + function ($reason) { + echo 'The promise was rejected.'; + } +); +``` + +*Resolving* a promise means that you either fulfill a promise with a *value* or +reject a promise with a *reason*. Resolving a promises triggers callbacks +registered with the promises's `then` method. These callbacks are triggered +only once and in the order in which they were added. + + +## Resolving a promise + +Promises are fulfilled using the `resolve($value)` method. Resolving a promise +with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger +all of the onFulfilled callbacks (resolving a promise with a rejected promise +will reject the promise and trigger the `$onRejected` callbacks). + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(function ($value) { + // Return a value and don't break the chain + return "Hello, " . $value; + }) + // This then is executed after the first then and receives the value + // returned from the first then. + ->then(function ($value) { + echo $value; + }); + +// Resolving the promise triggers the $onFulfilled callbacks and outputs +// "Hello, reader." +$promise->resolve('reader.'); +``` + + +## Promise forwarding + +Promises can be chained one after the other. Each then in the chain is a new +promise. The return value of a promise is what's forwarded to the next +promise in the chain. Returning a promise in a `then` callback will cause the +subsequent promises in the chain to only be fulfilled when the returned promise +has been fulfilled. The next promise in the chain will be invoked with the +resolved value of the promise. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$nextPromise = new Promise(); + +$promise + ->then(function ($value) use ($nextPromise) { + echo $value; + return $nextPromise; + }) + ->then(function ($value) { + echo $value; + }); + +// Triggers the first callback and outputs "A" +$promise->resolve('A'); +// Triggers the second callback and outputs "B" +$nextPromise->resolve('B'); +``` + +## Promise rejection + +When a promise is rejected, the `$onRejected` callbacks are invoked with the +rejection reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + echo $reason; +}); + +$promise->reject('Error!'); +// Outputs "Error!" +``` + +## Rejection forwarding + +If an exception is thrown in an `$onRejected` callback, subsequent +`$onRejected` callbacks are invoked with the thrown exception as the reason. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + throw new Exception($reason); +})->then(null, function ($reason) { + assert($reason->getMessage() === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +You can also forward a rejection down the promise chain by returning a +`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or +`$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new Promise(); +$promise->then(null, function ($reason) { + return new RejectedPromise($reason); +})->then(null, function ($reason) { + assert($reason === 'Error!'); +}); + +$promise->reject('Error!'); +``` + +If an exception is not thrown in a `$onRejected` callback and the callback +does not return a rejected promise, downstream `$onFulfilled` callbacks are +invoked using the value returned from the `$onRejected` callback. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise(); +$promise + ->then(null, function ($reason) { + return "It's ok"; + }) + ->then(function ($value) { + assert($value === "It's ok"); + }); + +$promise->reject('Error!'); +``` + +# Synchronous wait + +You can synchronously force promises to complete using a promise's `wait` +method. When creating a promise, you can provide a wait function that is used +to synchronously force a promise to complete. When a wait function is invoked +it is expected to deliver a value to the promise or reject the promise. If the +wait function does not deliver a value, then an exception is thrown. The wait +function provided to a promise constructor is invoked when the `wait` function +of the promise is called. + +```php +$promise = new Promise(function () use (&$promise) { + $promise->resolve('foo'); +}); + +// Calling wait will return the value of the promise. +echo $promise->wait(); // outputs "foo" +``` + +If an exception is encountered while invoking the wait function of a promise, +the promise is rejected with the exception and the exception is thrown. + +```php +$promise = new Promise(function () use (&$promise) { + throw new Exception('foo'); +}); + +$promise->wait(); // throws the exception. +``` + +Calling `wait` on a promise that has been fulfilled will not trigger the wait +function. It will simply return the previously resolved value. + +```php +$promise = new Promise(function () { die('this is not called!'); }); +$promise->resolve('foo'); +echo $promise->wait(); // outputs "foo" +``` + +Calling `wait` on a promise that has been rejected will throw an exception. If +the rejection reason is an instance of `\Exception` the reason is thrown. +Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason +can be obtained by calling the `getReason` method of the exception. + +```php +$promise = new Promise(); +$promise->reject('foo'); +$promise->wait(); +``` + +> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo' + + +## Unwrapping a promise + +When synchronously waiting on a promise, you are joining the state of the +promise into the current state of execution (i.e., return the value of the +promise if it was fulfilled or throw an exception if it was rejected). This is +called "unwrapping" the promise. Waiting on a promise will by default unwrap +the promise state. + +You can force a promise to resolve and *not* unwrap the state of the promise +by passing `false` to the first argument of the `wait` function: + +```php +$promise = new Promise(); +$promise->reject('foo'); +// This will not throw an exception. It simply ensures the promise has +// been resolved. +$promise->wait(false); +``` + +When unwrapping a promise, the resolved value of the promise will be waited +upon until the unwrapped value is not a promise. This means that if you resolve +promise A with a promise B and unwrap promise A, the value returned by the +wait function will be the value delivered to promise B. + +**Note**: when you do not unwrap the promise, no value is returned. + + +# Cancellation + +You can cancel a promise that has not yet been fulfilled using the `cancel()` +method of a promise. When creating a promise you can provide an optional +cancel function that when invoked cancels the action of computing a resolution +of the promise. + + +# API + + +## Promise + +When creating a promise object, you can provide an optional `$waitFn` and +`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is +expected to resolve the promise. `$cancelFn` is a function with no arguments +that is expected to cancel the computation of a promise. It is invoked when the +`cancel()` method of a promise is called. + +```php +use GuzzleHttp\Promise\Promise; + +$promise = new Promise( + function () use (&$promise) { + $promise->resolve('waited'); + }, + function () { + // do something that will cancel the promise computation (e.g., close + // a socket, cancel a database query, etc...) + } +); + +assert('waited' === $promise->wait()); +``` + +A promise has the following methods: + +- `then(callable $onFulfilled, callable $onRejected) : PromiseInterface` + + Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler. + +- `otherwise(callable $onRejected) : PromiseInterface` + + Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. + +- `wait($unwrap = true) : mixed` + + Synchronously waits on the promise to complete. + + `$unwrap` controls whether or not the value of the promise is returned for a + fulfilled promise or if an exception is thrown if the promise is rejected. + This is set to `true` by default. + +- `cancel()` + + Attempts to cancel the promise if possible. The promise being cancelled and + the parent most ancestor that has not yet been resolved will also be + cancelled. Any promises waiting on the cancelled promise to resolve will also + be cancelled. + +- `getState() : string` + + Returns the state of the promise. One of `pending`, `fulfilled`, or + `rejected`. + +- `resolve($value)` + + Fulfills the promise with the given `$value`. + +- `reject($reason)` + + Rejects the promise with the given `$reason`. + + +## FulfilledPromise + +A fulfilled promise can be created to represent a promise that has been +fulfilled. + +```php +use GuzzleHttp\Promise\FulfilledPromise; + +$promise = new FulfilledPromise('value'); + +// Fulfilled callbacks are immediately invoked. +$promise->then(function ($value) { + echo $value; +}); +``` + + +## RejectedPromise + +A rejected promise can be created to represent a promise that has been +rejected. + +```php +use GuzzleHttp\Promise\RejectedPromise; + +$promise = new RejectedPromise('Error'); + +// Rejected callbacks are immediately invoked. +$promise->then(null, function ($reason) { + echo $reason; +}); +``` + + +# Promise interop + +This library works with foreign promises that have a `then` method. This means +you can use Guzzle promises with [React promises](https://github.com/reactphp/promise) +for example. When a foreign promise is returned inside of a then method +callback, promise resolution will occur recursively. + +```php +// Create a React promise +$deferred = new React\Promise\Deferred(); +$reactPromise = $deferred->promise(); + +// Create a Guzzle promise that is fulfilled with a React promise. +$guzzlePromise = new GuzzleHttp\Promise\Promise(); +$guzzlePromise->then(function ($value) use ($reactPromise) { + // Do something something with the value... + // Return the React promise + return $reactPromise; +}); +``` + +Please note that wait and cancel chaining is no longer possible when forwarding +a foreign promise. You will need to wrap a third-party promise with a Guzzle +promise in order to utilize wait and cancel functions with foreign promises. + + +## Event Loop Integration + +In order to keep the stack size constant, Guzzle promises are resolved +asynchronously using a task queue. When waiting on promises synchronously, the +task queue will be automatically run to ensure that the blocking promise and +any forwarded promises are resolved. When using promises asynchronously in an +event loop, you will need to run the task queue on each tick of the loop. If +you do not run the task queue, then promises will not be resolved. + +You can run the task queue using the `run()` method of the global task queue +instance. + +```php +// Get the global task queue +$queue = GuzzleHttp\Promise\Utils::queue(); +$queue->run(); +``` + +For example, you could use Guzzle promises with React using a periodic timer: + +```php +$loop = React\EventLoop\Factory::create(); +$loop->addPeriodicTimer(0, [$queue, 'run']); +``` + +*TODO*: Perhaps adding a `futureTick()` on each tick would be faster? + + +# Implementation notes + + +## Promise resolution and chaining is handled iteratively + +By shuffling pending handlers from one owner to another, promises are +resolved iteratively, allowing for "infinite" then chaining. + +```php +then(function ($v) { + // The stack size remains constant (a good thing) + echo xdebug_get_stack_depth() . ', '; + return $v + 1; + }); +} + +$parent->resolve(0); +var_dump($p->wait()); // int(1000) + +``` + +When a promise is fulfilled or rejected with a non-promise value, the promise +then takes ownership of the handlers of each child promise and delivers values +down the chain without using recursion. + +When a promise is resolved with another promise, the original promise transfers +all of its pending handlers to the new promise. When the new promise is +eventually resolved, all of the pending handlers are delivered the forwarded +value. + + +## A promise is the deferred. + +Some promise libraries implement promises using a deferred object to represent +a computation and a promise object to represent the delivery of the result of +the computation. This is a nice separation of computation and delivery because +consumers of the promise cannot modify the value that will be eventually +delivered. + +One side effect of being able to implement promise resolution and chaining +iteratively is that you need to be able for one promise to reach into the state +of another promise to shuffle around ownership of handlers. In order to achieve +this without making the handlers of a promise publicly mutable, a promise is +also the deferred value, allowing promises of the same parent class to reach +into and modify the private properties of promises of the same type. While this +does allow consumers of the value to modify the resolution or rejection of the +deferred, it is a small price to pay for keeping the stack size constant. + +```php +$promise = new Promise(); +$promise->then(function ($value) { echo $value; }); +// The promise is the deferred value, so you can deliver a value to it. +$promise->resolve('foo'); +// prints "foo" +``` + + +## Upgrading from Function API + +A static API was first introduced in 1.4.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API will be removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `queue` | `Utils::queue` | +| `task` | `Utils::task` | +| `promise_for` | `Create::promiseFor` | +| `rejection_for` | `Create::rejectionFor` | +| `exception_for` | `Create::exceptionFor` | +| `iter_for` | `Create::iterFor` | +| `inspect` | `Utils::inspect` | +| `inspect_all` | `Utils::inspectAll` | +| `unwrap` | `Utils::unwrap` | +| `all` | `Utils::all` | +| `some` | `Utils::some` | +| `any` | `Utils::any` | +| `settle` | `Utils::settle` | +| `each` | `Each::of` | +| `each_limit` | `Each::ofLimit` | +| `each_limit_all` | `Each::ofLimitAll` | +| `!is_fulfilled` | `Is::pending` | +| `is_fulfilled` | `Is::fulfilled` | +| `is_rejected` | `Is::rejected` | +| `is_settled` | `Is::settled` | +| `coroutine` | `Coroutine::of` | + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/lib/guzzlehttp/promises/composer.json b/lib/guzzlehttp/promises/composer.json new file mode 100644 index 00000000..c959fb32 --- /dev/null +++ b/lib/guzzlehttp/promises/composer.json @@ -0,0 +1,58 @@ +{ + "name": "guzzlehttp/promises", + "description": "Guzzle promises library", + "keywords": ["promise"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Promise\\Tests\\": "tests/" + } + }, + "scripts": { + "test": "vendor/bin/simple-phpunit", + "test-ci": "vendor/bin/simple-phpunit --coverage-text" + }, + "extra": { + "branch-alias": { + "dev-master": "1.5-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/lib/guzzlehttp/promises/src/AggregateException.php b/lib/guzzlehttp/promises/src/AggregateException.php new file mode 100644 index 00000000..d2b5712b --- /dev/null +++ b/lib/guzzlehttp/promises/src/AggregateException.php @@ -0,0 +1,17 @@ +then(function ($v) { echo $v; }); + * + * @param callable $generatorFn Generator function to wrap into a promise. + * + * @return Promise + * + * @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration + */ +final class Coroutine implements PromiseInterface +{ + /** + * @var PromiseInterface|null + */ + private $currentPromise; + + /** + * @var Generator + */ + private $generator; + + /** + * @var Promise + */ + private $result; + + public function __construct(callable $generatorFn) + { + $this->generator = $generatorFn(); + $this->result = new Promise(function () { + while (isset($this->currentPromise)) { + $this->currentPromise->wait(); + } + }); + try { + $this->nextCoroutine($this->generator->current()); + } catch (\Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * Create a new coroutine. + * + * @return self + */ + public static function of(callable $generatorFn) + { + return new self($generatorFn); + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + return $this->result->then($onFulfilled, $onRejected); + } + + public function otherwise(callable $onRejected) + { + return $this->result->otherwise($onRejected); + } + + public function wait($unwrap = true) + { + return $this->result->wait($unwrap); + } + + public function getState() + { + return $this->result->getState(); + } + + public function resolve($value) + { + $this->result->resolve($value); + } + + public function reject($reason) + { + $this->result->reject($reason); + } + + public function cancel() + { + $this->currentPromise->cancel(); + $this->result->cancel(); + } + + private function nextCoroutine($yielded) + { + $this->currentPromise = Create::promiseFor($yielded) + ->then([$this, '_handleSuccess'], [$this, '_handleFailure']); + } + + /** + * @internal + */ + public function _handleSuccess($value) + { + unset($this->currentPromise); + try { + $next = $this->generator->send($value); + if ($this->generator->valid()) { + $this->nextCoroutine($next); + } else { + $this->result->resolve($value); + } + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } + + /** + * @internal + */ + public function _handleFailure($reason) + { + unset($this->currentPromise); + try { + $nextYield = $this->generator->throw(Create::exceptionFor($reason)); + // The throw was caught, so keep iterating on the coroutine + $this->nextCoroutine($nextYield); + } catch (Exception $exception) { + $this->result->reject($exception); + } catch (Throwable $throwable) { + $this->result->reject($throwable); + } + } +} diff --git a/lib/guzzlehttp/promises/src/Create.php b/lib/guzzlehttp/promises/src/Create.php new file mode 100644 index 00000000..8d038e9c --- /dev/null +++ b/lib/guzzlehttp/promises/src/Create.php @@ -0,0 +1,84 @@ +then([$promise, 'resolve'], [$promise, 'reject']); + return $promise; + } + + return new FulfilledPromise($value); + } + + /** + * Creates a rejected promise for a reason if the reason is not a promise. + * If the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + */ + public static function rejectionFor($reason) + { + if ($reason instanceof PromiseInterface) { + return $reason; + } + + return new RejectedPromise($reason); + } + + /** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + */ + public static function exceptionFor($reason) + { + if ($reason instanceof \Exception || $reason instanceof \Throwable) { + return $reason; + } + + return new RejectionException($reason); + } + + /** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + */ + public static function iterFor($value) + { + if ($value instanceof \Iterator) { + return $value; + } + + if (is_array($value)) { + return new \ArrayIterator($value); + } + + return new \ArrayIterator([$value]); + } +} diff --git a/lib/guzzlehttp/promises/src/Each.php b/lib/guzzlehttp/promises/src/Each.php new file mode 100644 index 00000000..1dda3549 --- /dev/null +++ b/lib/guzzlehttp/promises/src/Each.php @@ -0,0 +1,90 @@ + $onFulfilled, + 'rejected' => $onRejected + ]))->promise(); + } + + /** + * Like of, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow + * for dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + */ + public static function ofLimit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null + ) { + return (new EachPromise($iterable, [ + 'fulfilled' => $onFulfilled, + 'rejected' => $onRejected, + 'concurrency' => $concurrency + ]))->promise(); + } + + /** + * Like limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + */ + public static function ofLimitAll( + $iterable, + $concurrency, + callable $onFulfilled = null + ) { + return each_limit( + $iterable, + $concurrency, + $onFulfilled, + function ($reason, $idx, PromiseInterface $aggregate) { + $aggregate->reject($reason); + } + ); + } +} diff --git a/lib/guzzlehttp/promises/src/EachPromise.php b/lib/guzzlehttp/promises/src/EachPromise.php new file mode 100644 index 00000000..38ecb59b --- /dev/null +++ b/lib/guzzlehttp/promises/src/EachPromise.php @@ -0,0 +1,255 @@ +iterable = Create::iterFor($iterable); + + if (isset($config['concurrency'])) { + $this->concurrency = $config['concurrency']; + } + + if (isset($config['fulfilled'])) { + $this->onFulfilled = $config['fulfilled']; + } + + if (isset($config['rejected'])) { + $this->onRejected = $config['rejected']; + } + } + + /** @psalm-suppress InvalidNullableReturnType */ + public function promise() + { + if ($this->aggregate) { + return $this->aggregate; + } + + try { + $this->createPromise(); + /** @psalm-assert Promise $this->aggregate */ + $this->iterable->rewind(); + $this->refillPending(); + } catch (\Throwable $e) { + /** + * @psalm-suppress NullReference + * @phpstan-ignore-next-line + */ + $this->aggregate->reject($e); + } catch (\Exception $e) { + /** + * @psalm-suppress NullReference + * @phpstan-ignore-next-line + */ + $this->aggregate->reject($e); + } + + /** + * @psalm-suppress NullableReturnStatement + * @phpstan-ignore-next-line + */ + return $this->aggregate; + } + + private function createPromise() + { + $this->mutex = false; + $this->aggregate = new Promise(function () { + if ($this->checkIfFinished()) { + return; + } + reset($this->pending); + // Consume a potentially fluctuating list of promises while + // ensuring that indexes are maintained (precluding array_shift). + while ($promise = current($this->pending)) { + next($this->pending); + $promise->wait(); + if (Is::settled($this->aggregate)) { + return; + } + } + }); + + // Clear the references when the promise is resolved. + $clearFn = function () { + $this->iterable = $this->concurrency = $this->pending = null; + $this->onFulfilled = $this->onRejected = null; + $this->nextPendingIndex = 0; + }; + + $this->aggregate->then($clearFn, $clearFn); + } + + private function refillPending() + { + if (!$this->concurrency) { + // Add all pending promises. + while ($this->addPending() && $this->advanceIterator()); + return; + } + + // Add only up to N pending promises. + $concurrency = is_callable($this->concurrency) + ? call_user_func($this->concurrency, count($this->pending)) + : $this->concurrency; + $concurrency = max($concurrency - count($this->pending), 0); + // Concurrency may be set to 0 to disallow new promises. + if (!$concurrency) { + return; + } + // Add the first pending promise. + $this->addPending(); + // Note this is special handling for concurrency=1 so that we do + // not advance the iterator after adding the first promise. This + // helps work around issues with generators that might not have the + // next value to yield until promise callbacks are called. + while (--$concurrency + && $this->advanceIterator() + && $this->addPending()); + } + + private function addPending() + { + if (!$this->iterable || !$this->iterable->valid()) { + return false; + } + + $promise = Create::promiseFor($this->iterable->current()); + $key = $this->iterable->key(); + + // Iterable keys may not be unique, so we use a counter to + // guarantee uniqueness + $idx = $this->nextPendingIndex++; + + $this->pending[$idx] = $promise->then( + function ($value) use ($idx, $key) { + if ($this->onFulfilled) { + call_user_func( + $this->onFulfilled, + $value, + $key, + $this->aggregate + ); + } + $this->step($idx); + }, + function ($reason) use ($idx, $key) { + if ($this->onRejected) { + call_user_func( + $this->onRejected, + $reason, + $key, + $this->aggregate + ); + } + $this->step($idx); + } + ); + + return true; + } + + private function advanceIterator() + { + // Place a lock on the iterator so that we ensure to not recurse, + // preventing fatal generator errors. + if ($this->mutex) { + return false; + } + + $this->mutex = true; + + try { + $this->iterable->next(); + $this->mutex = false; + return true; + } catch (\Throwable $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } catch (\Exception $e) { + $this->aggregate->reject($e); + $this->mutex = false; + return false; + } + } + + private function step($idx) + { + // If the promise was already resolved, then ignore this step. + if (Is::settled($this->aggregate)) { + return; + } + + unset($this->pending[$idx]); + + // Only refill pending promises if we are not locked, preventing the + // EachPromise to recursively invoke the provided iterator, which + // cause a fatal error: "Cannot resume an already running generator" + if ($this->advanceIterator() && !$this->checkIfFinished()) { + // Add more pending promises if possible. + $this->refillPending(); + } + } + + private function checkIfFinished() + { + if (!$this->pending && !$this->iterable->valid()) { + // Resolve the promise if there's nothing left to do. + $this->aggregate->resolve(null); + return true; + } + + return false; + } +} diff --git a/lib/guzzlehttp/promises/src/FulfilledPromise.php b/lib/guzzlehttp/promises/src/FulfilledPromise.php new file mode 100644 index 00000000..98f72a62 --- /dev/null +++ b/lib/guzzlehttp/promises/src/FulfilledPromise.php @@ -0,0 +1,84 @@ +value = $value; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // Return itself if there is no onFulfilled function. + if (!$onFulfilled) { + return $this; + } + + $queue = Utils::queue(); + $p = new Promise([$queue, 'run']); + $value = $this->value; + $queue->add(static function () use ($p, $value, $onFulfilled) { + if (Is::pending($p)) { + try { + $p->resolve($onFulfilled($value)); + } catch (\Throwable $e) { + $p->reject($e); + } catch (\Exception $e) { + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + return $unwrap ? $this->value : null; + } + + public function getState() + { + return self::FULFILLED; + } + + public function resolve($value) + { + if ($value !== $this->value) { + throw new \LogicException("Cannot resolve a fulfilled promise"); + } + } + + public function reject($reason) + { + throw new \LogicException("Cannot reject a fulfilled promise"); + } + + public function cancel() + { + // pass + } +} diff --git a/lib/guzzlehttp/promises/src/Is.php b/lib/guzzlehttp/promises/src/Is.php new file mode 100644 index 00000000..c3ed8d01 --- /dev/null +++ b/lib/guzzlehttp/promises/src/Is.php @@ -0,0 +1,46 @@ +getState() === PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + */ + public static function settled(PromiseInterface $promise) + { + return $promise->getState() !== PromiseInterface::PENDING; + } + + /** + * Returns true if a promise is fulfilled. + * + * @return bool + */ + public static function fulfilled(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::FULFILLED; + } + + /** + * Returns true if a promise is rejected. + * + * @return bool + */ + public static function rejected(PromiseInterface $promise) + { + return $promise->getState() === PromiseInterface::REJECTED; + } +} diff --git a/lib/guzzlehttp/promises/src/Promise.php b/lib/guzzlehttp/promises/src/Promise.php new file mode 100644 index 00000000..75939057 --- /dev/null +++ b/lib/guzzlehttp/promises/src/Promise.php @@ -0,0 +1,278 @@ +waitFn = $waitFn; + $this->cancelFn = $cancelFn; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + if ($this->state === self::PENDING) { + $p = new Promise(null, [$this, 'cancel']); + $this->handlers[] = [$p, $onFulfilled, $onRejected]; + $p->waitList = $this->waitList; + $p->waitList[] = $this; + return $p; + } + + // Return a fulfilled promise and immediately invoke any callbacks. + if ($this->state === self::FULFILLED) { + $promise = Create::promiseFor($this->result); + return $onFulfilled ? $promise->then($onFulfilled) : $promise; + } + + // It's either cancelled or rejected, so return a rejected promise + // and immediately invoke any callbacks. + $rejection = Create::rejectionFor($this->result); + return $onRejected ? $rejection->then(null, $onRejected) : $rejection; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true) + { + $this->waitIfPending(); + + if ($this->result instanceof PromiseInterface) { + return $this->result->wait($unwrap); + } + if ($unwrap) { + if ($this->state === self::FULFILLED) { + return $this->result; + } + // It's rejected so "unwrap" and throw an exception. + throw Create::exceptionFor($this->result); + } + } + + public function getState() + { + return $this->state; + } + + public function cancel() + { + if ($this->state !== self::PENDING) { + return; + } + + $this->waitFn = $this->waitList = null; + + if ($this->cancelFn) { + $fn = $this->cancelFn; + $this->cancelFn = null; + try { + $fn(); + } catch (\Throwable $e) { + $this->reject($e); + } catch (\Exception $e) { + $this->reject($e); + } + } + + // Reject the promise only if it wasn't rejected in a then callback. + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject(new CancellationException('Promise has been cancelled')); + } + } + + public function resolve($value) + { + $this->settle(self::FULFILLED, $value); + } + + public function reject($reason) + { + $this->settle(self::REJECTED, $reason); + } + + private function settle($state, $value) + { + if ($this->state !== self::PENDING) { + // Ignore calls with the same resolution. + if ($state === $this->state && $value === $this->result) { + return; + } + throw $this->state === $state + ? new \LogicException("The promise is already {$state}.") + : new \LogicException("Cannot change a {$this->state} promise to {$state}"); + } + + if ($value === $this) { + throw new \LogicException('Cannot fulfill or reject a promise with itself'); + } + + // Clear out the state of the promise but stash the handlers. + $this->state = $state; + $this->result = $value; + $handlers = $this->handlers; + $this->handlers = null; + $this->waitList = $this->waitFn = null; + $this->cancelFn = null; + + if (!$handlers) { + return; + } + + // If the value was not a settled promise or a thenable, then resolve + // it in the task queue using the correct ID. + if (!is_object($value) || !method_exists($value, 'then')) { + $id = $state === self::FULFILLED ? 1 : 2; + // It's a success, so resolve the handlers in the queue. + Utils::queue()->add(static function () use ($id, $value, $handlers) { + foreach ($handlers as $handler) { + self::callHandler($id, $value, $handler); + } + }); + } elseif ($value instanceof Promise && Is::pending($value)) { + // We can just merge our handlers onto the next promise. + $value->handlers = array_merge($value->handlers, $handlers); + } else { + // Resolve the handlers when the forwarded promise is resolved. + $value->then( + static function ($value) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(1, $value, $handler); + } + }, + static function ($reason) use ($handlers) { + foreach ($handlers as $handler) { + self::callHandler(2, $reason, $handler); + } + } + ); + } + } + + /** + * Call a stack of handlers using a specific callback index and value. + * + * @param int $index 1 (resolve) or 2 (reject). + * @param mixed $value Value to pass to the callback. + * @param array $handler Array of handler data (promise and callbacks). + */ + private static function callHandler($index, $value, array $handler) + { + /** @var PromiseInterface $promise */ + $promise = $handler[0]; + + // The promise may have been cancelled or resolved before placing + // this thunk in the queue. + if (Is::settled($promise)) { + return; + } + + try { + if (isset($handler[$index])) { + /* + * If $f throws an exception, then $handler will be in the exception + * stack trace. Since $handler contains a reference to the callable + * itself we get a circular reference. We clear the $handler + * here to avoid that memory leak. + */ + $f = $handler[$index]; + unset($handler); + $promise->resolve($f($value)); + } elseif ($index === 1) { + // Forward resolution values as-is. + $promise->resolve($value); + } else { + // Forward rejections down the chain. + $promise->reject($value); + } + } catch (\Throwable $reason) { + $promise->reject($reason); + } catch (\Exception $reason) { + $promise->reject($reason); + } + } + + private function waitIfPending() + { + if ($this->state !== self::PENDING) { + return; + } elseif ($this->waitFn) { + $this->invokeWaitFn(); + } elseif ($this->waitList) { + $this->invokeWaitList(); + } else { + // If there's no wait function, then reject the promise. + $this->reject('Cannot wait on a promise that has ' + . 'no internal wait function. You must provide a wait ' + . 'function when constructing the promise to be able to ' + . 'wait on a promise.'); + } + + Utils::queue()->run(); + + /** @psalm-suppress RedundantCondition */ + if ($this->state === self::PENDING) { + $this->reject('Invoking the wait callback did not resolve the promise'); + } + } + + private function invokeWaitFn() + { + try { + $wfn = $this->waitFn; + $this->waitFn = null; + $wfn(true); + } catch (\Exception $reason) { + if ($this->state === self::PENDING) { + // The promise has not been resolved yet, so reject the promise + // with the exception. + $this->reject($reason); + } else { + // The promise was already resolved, so there's a problem in + // the application. + throw $reason; + } + } + } + + private function invokeWaitList() + { + $waitList = $this->waitList; + $this->waitList = null; + + foreach ($waitList as $result) { + do { + $result->waitIfPending(); + $result = $result->result; + } while ($result instanceof Promise); + + if ($result instanceof PromiseInterface) { + $result->wait(false); + } + } + } +} diff --git a/lib/guzzlehttp/promises/src/PromiseInterface.php b/lib/guzzlehttp/promises/src/PromiseInterface.php new file mode 100644 index 00000000..e5983314 --- /dev/null +++ b/lib/guzzlehttp/promises/src/PromiseInterface.php @@ -0,0 +1,97 @@ +reason = $reason; + } + + public function then( + callable $onFulfilled = null, + callable $onRejected = null + ) { + // If there's no onRejected callback then just return self. + if (!$onRejected) { + return $this; + } + + $queue = Utils::queue(); + $reason = $this->reason; + $p = new Promise([$queue, 'run']); + $queue->add(static function () use ($p, $reason, $onRejected) { + if (Is::pending($p)) { + try { + // Return a resolved promise if onRejected does not throw. + $p->resolve($onRejected($reason)); + } catch (\Throwable $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } catch (\Exception $e) { + // onRejected threw, so return a rejected promise. + $p->reject($e); + } + } + }); + + return $p; + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, $onRejected); + } + + public function wait($unwrap = true, $defaultDelivery = null) + { + if ($unwrap) { + throw Create::exceptionFor($this->reason); + } + + return null; + } + + public function getState() + { + return self::REJECTED; + } + + public function resolve($value) + { + throw new \LogicException("Cannot resolve a rejected promise"); + } + + public function reject($reason) + { + if ($reason !== $this->reason) { + throw new \LogicException("Cannot reject a rejected promise"); + } + } + + public function cancel() + { + // pass + } +} diff --git a/lib/guzzlehttp/promises/src/RejectionException.php b/lib/guzzlehttp/promises/src/RejectionException.php new file mode 100644 index 00000000..e2f13770 --- /dev/null +++ b/lib/guzzlehttp/promises/src/RejectionException.php @@ -0,0 +1,48 @@ +reason = $reason; + + $message = 'The promise was rejected'; + + if ($description) { + $message .= ' with reason: ' . $description; + } elseif (is_string($reason) + || (is_object($reason) && method_exists($reason, '__toString')) + ) { + $message .= ' with reason: ' . $this->reason; + } elseif ($reason instanceof \JsonSerializable) { + $message .= ' with reason: ' + . json_encode($this->reason, JSON_PRETTY_PRINT); + } + + parent::__construct($message); + } + + /** + * Returns the rejection reason. + * + * @return mixed + */ + public function getReason() + { + return $this->reason; + } +} diff --git a/lib/guzzlehttp/promises/src/TaskQueue.php b/lib/guzzlehttp/promises/src/TaskQueue.php new file mode 100644 index 00000000..f0fba2c5 --- /dev/null +++ b/lib/guzzlehttp/promises/src/TaskQueue.php @@ -0,0 +1,67 @@ +run(); + */ +class TaskQueue implements TaskQueueInterface +{ + private $enableShutdown = true; + private $queue = []; + + public function __construct($withShutdown = true) + { + if ($withShutdown) { + register_shutdown_function(function () { + if ($this->enableShutdown) { + // Only run the tasks if an E_ERROR didn't occur. + $err = error_get_last(); + if (!$err || ($err['type'] ^ E_ERROR)) { + $this->run(); + } + } + }); + } + } + + public function isEmpty() + { + return !$this->queue; + } + + public function add(callable $task) + { + $this->queue[] = $task; + } + + public function run() + { + while ($task = array_shift($this->queue)) { + /** @var callable $task */ + $task(); + } + } + + /** + * The task queue will be run and exhausted by default when the process + * exits IFF the exit is not the result of a PHP E_ERROR error. + * + * You can disable running the automatic shutdown of the queue by calling + * this function. If you disable the task queue shutdown process, then you + * MUST either run the task queue (as a result of running your event loop + * or manually using the run() method) or wait on each outstanding promise. + * + * Note: This shutdown will occur before any destructors are triggered. + */ + public function disableShutdown() + { + $this->enableShutdown = false; + } +} diff --git a/lib/guzzlehttp/promises/src/TaskQueueInterface.php b/lib/guzzlehttp/promises/src/TaskQueueInterface.php new file mode 100644 index 00000000..723d4d54 --- /dev/null +++ b/lib/guzzlehttp/promises/src/TaskQueueInterface.php @@ -0,0 +1,24 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\Utils::queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + */ + public static function queue(TaskQueueInterface $assign = null) + { + static $queue; + + if ($assign) { + $queue = $assign; + } elseif (!$queue) { + $queue = new TaskQueue(); + } + + return $queue; + } + + /** + * Adds a function to run in the task queue when it is next `run()` and + * returns a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + */ + public static function task(callable $task) + { + $queue = self::queue(); + $promise = new Promise([$queue, 'run']); + $queue->add(function () use ($task, $promise) { + try { + if (Is::pending($promise)) { + $promise->resolve($task()); + } + } catch (\Throwable $e) { + $promise->reject($e); + } catch (\Exception $e) { + $promise->reject($e); + } + }); + + return $promise; + } + + /** + * Synchronously waits on a promise to resolve and returns an inspection + * state array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the + * array will contain a "value" key mapping to the fulfilled value of the + * promise. If the promise is rejected, the array will contain a "reason" + * key mapping to the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + */ + public static function inspect(PromiseInterface $promise) + { + try { + return [ + 'state' => PromiseInterface::FULFILLED, + 'value' => $promise->wait() + ]; + } catch (RejectionException $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()]; + } catch (\Throwable $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } catch (\Exception $e) { + return ['state' => PromiseInterface::REJECTED, 'reason' => $e]; + } + } + + /** + * Waits on all of the provided promises, but does not unwrap rejected + * promises as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + */ + public static function inspectAll($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = inspect($promise); + } + + return $results; + } + + /** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same + * order the promises were provided). An exception is thrown if any of the + * promises are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + */ + public static function unwrap($promises) + { + $results = []; + foreach ($promises as $key => $promise) { + $results[$key] = $promise->wait(); + } + + return $results; + } + + /** + * Given an array of promises, return a promise that is fulfilled when all + * the items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + */ + public static function all($promises, $recursive = false) + { + $results = []; + $promise = Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = $value; + }, + function ($reason, $idx, Promise $aggregate) { + $aggregate->reject($reason); + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + + if (true === $recursive) { + $promise = $promise->then(function ($results) use ($recursive, &$promises) { + foreach ($promises as $promise) { + if (Is::pending($promise)) { + return self::all($promises, $recursive); + } + } + return $results; + }); + } + + return $promise; + } + + /** + * Initiate a competitive race between multiple promises or values (values + * will become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise + * is fulfilled with an array that contains the fulfillment values of the + * winners in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number + * of fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function some($count, $promises) + { + $results = []; + $rejections = []; + + return Each::of( + $promises, + function ($value, $idx, PromiseInterface $p) use (&$results, $count) { + if (Is::settled($p)) { + return; + } + $results[$idx] = $value; + if (count($results) >= $count) { + $p->resolve(null); + } + }, + function ($reason) use (&$rejections) { + $rejections[] = $reason; + } + )->then( + function () use (&$results, &$rejections, $count) { + if (count($results) !== $count) { + throw new AggregateException( + 'Not enough promises to fulfill count', + $rejections + ); + } + ksort($results); + return array_values($results); + } + ); + } + + /** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function any($promises) + { + return self::some(1, $promises)->then(function ($values) { + return $values[0]; + }); + } + + /** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + */ + public static function settle($promises) + { + $results = []; + + return Each::of( + $promises, + function ($value, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value]; + }, + function ($reason, $idx) use (&$results) { + $results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason]; + } + )->then(function () use (&$results) { + ksort($results); + return $results; + }); + } +} diff --git a/lib/guzzlehttp/promises/src/functions.php b/lib/guzzlehttp/promises/src/functions.php new file mode 100644 index 00000000..c03d39d0 --- /dev/null +++ b/lib/guzzlehttp/promises/src/functions.php @@ -0,0 +1,363 @@ + + * while ($eventLoop->isRunning()) { + * GuzzleHttp\Promise\queue()->run(); + * } + * + * + * @param TaskQueueInterface $assign Optionally specify a new queue instance. + * + * @return TaskQueueInterface + * + * @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead. + */ +function queue(TaskQueueInterface $assign = null) +{ + return Utils::queue($assign); +} + +/** + * Adds a function to run in the task queue when it is next `run()` and returns + * a promise that is fulfilled or rejected with the result. + * + * @param callable $task Task function to run. + * + * @return PromiseInterface + * + * @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead. + */ +function task(callable $task) +{ + return Utils::task($task); +} + +/** + * Creates a promise for a value if the value is not a promise. + * + * @param mixed $value Promise or value. + * + * @return PromiseInterface + * + * @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead. + */ +function promise_for($value) +{ + return Create::promiseFor($value); +} + +/** + * Creates a rejected promise for a reason if the reason is not a promise. If + * the provided reason is a promise, then it is returned as-is. + * + * @param mixed $reason Promise or reason. + * + * @return PromiseInterface + * + * @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead. + */ +function rejection_for($reason) +{ + return Create::rejectionFor($reason); +} + +/** + * Create an exception for a rejected promise value. + * + * @param mixed $reason + * + * @return \Exception|\Throwable + * + * @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead. + */ +function exception_for($reason) +{ + return Create::exceptionFor($reason); +} + +/** + * Returns an iterator for the given value. + * + * @param mixed $value + * + * @return \Iterator + * + * @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead. + */ +function iter_for($value) +{ + return Create::iterFor($value); +} + +/** + * Synchronously waits on a promise to resolve and returns an inspection state + * array. + * + * Returns a state associative array containing a "state" key mapping to a + * valid promise state. If the state of the promise is "fulfilled", the array + * will contain a "value" key mapping to the fulfilled value of the promise. If + * the promise is rejected, the array will contain a "reason" key mapping to + * the rejection reason of the promise. + * + * @param PromiseInterface $promise Promise or value. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead. + */ +function inspect(PromiseInterface $promise) +{ + return Utils::inspect($promise); +} + +/** + * Waits on all of the provided promises, but does not unwrap rejected promises + * as thrown exception. + * + * Returns an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param PromiseInterface[] $promises Traversable of promises to wait upon. + * + * @return array + * + * @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead. + */ +function inspect_all($promises) +{ + return Utils::inspectAll($promises); +} + +/** + * Waits on all of the provided promises and returns the fulfilled values. + * + * Returns an array that contains the value of each promise (in the same order + * the promises were provided). An exception is thrown if any of the promises + * are rejected. + * + * @param iterable $promises Iterable of PromiseInterface objects to wait on. + * + * @return array + * + * @throws \Exception on error + * @throws \Throwable on error in PHP >=7 + * + * @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead. + */ +function unwrap($promises) +{ + return Utils::unwrap($promises); +} + +/** + * Given an array of promises, return a promise that is fulfilled when all the + * items in the array are fulfilled. + * + * The promise's fulfillment value is an array with fulfillment values at + * respective positions to the original array. If any promise in the array + * rejects, the returned promise is rejected with the rejection reason. + * + * @param mixed $promises Promises or values. + * @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution. + * + * @return PromiseInterface + * + * @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead. + */ +function all($promises, $recursive = false) +{ + return Utils::all($promises, $recursive); +} + +/** + * Initiate a competitive race between multiple promises or values (values will + * become immediately fulfilled promises). + * + * When count amount of promises have been fulfilled, the returned promise is + * fulfilled with an array that contains the fulfillment values of the winners + * in order of resolution. + * + * This promise is rejected with a {@see AggregateException} if the number of + * fulfilled promises is less than the desired $count. + * + * @param int $count Total number of promises. + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead. + */ +function some($count, $promises) +{ + return Utils::some($count, $promises); +} + +/** + * Like some(), with 1 as count. However, if the promise fulfills, the + * fulfillment value is not an array of 1 but the value directly. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead. + */ +function any($promises) +{ + return Utils::any($promises); +} + +/** + * Returns a promise that is fulfilled when all of the provided promises have + * been fulfilled or rejected. + * + * The returned promise is fulfilled with an array of inspection state arrays. + * + * @see inspect for the inspection state array format. + * + * @param mixed $promises Promises or values. + * + * @return PromiseInterface + * + * @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead. + */ +function settle($promises) +{ + return Utils::settle($promises); +} + +/** + * Given an iterator that yields promises or values, returns a promise that is + * fulfilled with a null value when the iterator has been consumed or the + * aggregate promise has been fulfilled or rejected. + * + * $onFulfilled is a function that accepts the fulfilled value, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * $onRejected is a function that accepts the rejection reason, iterator index, + * and the aggregate promise. The callback can invoke any necessary side + * effects and choose to resolve or reject the aggregate if needed. + * + * @param mixed $iterable Iterator or array to iterate over. + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead. + */ +function each( + $iterable, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::of($iterable, $onFulfilled, $onRejected); +} + +/** + * Like each, but only allows a certain number of outstanding promises at any + * given time. + * + * $concurrency may be an integer or a function that accepts the number of + * pending promises and returns a numeric concurrency limit value to allow for + * dynamic a concurrency size. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * @param callable $onRejected + * + * @return PromiseInterface + * + * @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead. + */ +function each_limit( + $iterable, + $concurrency, + callable $onFulfilled = null, + callable $onRejected = null +) { + return Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected); +} + +/** + * Like each_limit, but ensures that no promise in the given $iterable argument + * is rejected. If any promise is rejected, then the aggregate promise is + * rejected with the encountered rejection. + * + * @param mixed $iterable + * @param int|callable $concurrency + * @param callable $onFulfilled + * + * @return PromiseInterface + * + * @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead. + */ +function each_limit_all( + $iterable, + $concurrency, + callable $onFulfilled = null +) { + return Each::ofLimitAll($iterable, $concurrency, $onFulfilled); +} + +/** + * Returns true if a promise is fulfilled. + * + * @return bool + * + * @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead. + */ +function is_fulfilled(PromiseInterface $promise) +{ + return Is::fulfilled($promise); +} + +/** + * Returns true if a promise is rejected. + * + * @return bool + * + * @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead. + */ +function is_rejected(PromiseInterface $promise) +{ + return Is::rejected($promise); +} + +/** + * Returns true if a promise is fulfilled or rejected. + * + * @return bool + * + * @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead. + */ +function is_settled(PromiseInterface $promise) +{ + return Is::settled($promise); +} + +/** + * Create a new coroutine. + * + * @see Coroutine + * + * @return PromiseInterface + * + * @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead. + */ +function coroutine(callable $generatorFn) +{ + return Coroutine::of($generatorFn); +} diff --git a/lib/guzzlehttp/promises/src/functions_include.php b/lib/guzzlehttp/promises/src/functions_include.php new file mode 100644 index 00000000..34cd1710 --- /dev/null +++ b/lib/guzzlehttp/promises/src/functions_include.php @@ -0,0 +1,6 @@ +withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/lib/guzzlehttp/psr7/LICENSE b/lib/guzzlehttp/psr7/LICENSE new file mode 100644 index 00000000..51c7ec81 --- /dev/null +++ b/lib/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/lib/guzzlehttp/psr7/README.md b/lib/guzzlehttp/psr7/README.md new file mode 100644 index 00000000..ed81c927 --- /dev/null +++ b/lib/guzzlehttp/psr7/README.md @@ -0,0 +1,823 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](http://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + +![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg) +![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg) + + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content. + +This stream decorator converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::normalize` + +`public static function normalize(string|array $header): array` + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called +manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](http://php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers +do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/lib/guzzlehttp/psr7/composer.json b/lib/guzzlehttp/psr7/composer.json new file mode 100644 index 00000000..885aa1da --- /dev/null +++ b/lib/guzzlehttp/psr7/composer.json @@ -0,0 +1,89 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "request", + "response", + "message", + "stream", + "http", + "uri", + "url", + "psr-7" + ], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.0", + "ralouphie/getallheaders": "^3.0" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.4.1", + "http-interop/http-factory-tests": "^0.9", + "phpunit/phpunit": "^8.5.8 || ^9.3.10" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.1-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/lib/guzzlehttp/psr7/src/AppendStream.php b/lib/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 00000000..967925f3 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,249 @@ +addStream($stream); + } + } + + public function __toString(): string + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream): void + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + */ + public function close(): void + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell(): int + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + */ + public function getSize(): ?int + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof(): bool + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind(): void + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + */ + public function read($length): string + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + if ($result === '') { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return false; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/lib/guzzlehttp/psr7/src/BufferStream.php b/lib/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 00000000..21be8c0a --- /dev/null +++ b/lib/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,149 @@ +hwm = $hwm; + } + + public function __toString(): string + { + return $this->getContents(); + } + + public function getContents(): string + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close(): void + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize(): ?int + { + return strlen($this->buffer); + } + + public function isReadable(): bool + { + return true; + } + + public function isWritable(): bool + { + return true; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof(): bool + { + return strlen($this->buffer) === 0; + } + + public function tell(): int + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length): string + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string): int + { + $this->buffer .= $string; + + if (strlen($this->buffer) >= $this->hwm) { + return 0; + } + + return strlen($string); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if ($key === 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/lib/guzzlehttp/psr7/src/CachingStream.php b/lib/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 00000000..7a70ee94 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,148 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize(): ?int + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence === SEEK_SET) { + $byte = $offset; + } elseif ($whence === SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence === SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length): string + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string): int + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof(): bool + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close(): void + { + $this->remoteStream->close(); + $this->stream->close(); + } + + private function cacheEntireStream(): int + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/lib/guzzlehttp/psr7/src/DroppingStream.php b/lib/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 00000000..d78070ae --- /dev/null +++ b/lib/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,46 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string): int + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/lib/guzzlehttp/psr7/src/Exception/MalformedUriException.php b/lib/guzzlehttp/psr7/src/Exception/MalformedUriException.php new file mode 100644 index 00000000..3a084779 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Exception/MalformedUriException.php @@ -0,0 +1,14 @@ + */ + private $methods; + + /** + * @param array $methods Hash of method name to a callable. + */ + public function __construct(array $methods) + { + $this->methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get(string $name): void + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup(): void + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::SLOTS, array_keys($methods)) as $diff) { + /** @var callable $callable */ + $callable = [$stream, $diff]; + $methods[$diff] = $callable; + } + + return new self($methods); + } + + public function __toString(): string + { + try { + return call_user_func($this->_fn___toString); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize(): ?int + { + return call_user_func($this->_fn_getSize); + } + + public function tell(): int + { + return call_user_func($this->_fn_tell); + } + + public function eof(): bool + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable(): bool + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind(): void + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET): void + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable(): bool + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string): int + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable(): bool + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length): string + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents(): string + { + return call_user_func($this->_fn_getContents); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/lib/guzzlehttp/psr7/src/Header.php b/lib/guzzlehttp/psr7/src/Header.php new file mode 100644 index 00000000..0e79a71a --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,69 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + */ + public static function normalize($header): array + { + if (!is_array($header)) { + return array_map('trim', explode(',', $header)); + } + + $result = []; + foreach ($header as $value) { + foreach ((array) $value as $v) { + if (strpos($v, ',') === false) { + $result[] = $v; + continue; + } + foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { + $result[] = trim($vv); + } + } + } + + return $result; + } +} diff --git a/lib/guzzlehttp/psr7/src/HttpFactory.php b/lib/guzzlehttp/psr7/src/HttpFactory.php new file mode 100644 index 00000000..30be222f --- /dev/null +++ b/lib/guzzlehttp/psr7/src/HttpFactory.php @@ -0,0 +1,100 @@ +getSize(); + } + + return new UploadedFile($stream, $size, $error, $clientFilename, $clientMediaType); + } + + public function createStream(string $content = ''): StreamInterface + { + return Utils::streamFor($content); + } + + public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface + { + try { + $resource = Utils::tryFopen($file, $mode); + } catch (\RuntimeException $e) { + if ('' === $mode || false === \in_array($mode[0], ['r', 'w', 'a', 'x', 'c'], true)) { + throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e); + } + + throw $e; + } + + return Utils::streamFor($resource); + } + + public function createStreamFromResource($resource): StreamInterface + { + return Utils::streamFor($resource); + } + + public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface + { + if (empty($method)) { + if (!empty($serverParams['REQUEST_METHOD'])) { + $method = $serverParams['REQUEST_METHOD']; + } else { + throw new \InvalidArgumentException('Cannot determine HTTP method'); + } + } + + return new ServerRequest($method, $uri, [], null, '1.1', $serverParams); + } + + public function createResponse(int $code = 200, string $reasonPhrase = ''): ResponseInterface + { + return new Response($code, [], null, '1.1', $reasonPhrase); + } + + public function createRequest(string $method, $uri): RequestInterface + { + return new Request($method, $uri); + } + + public function createUri(string $uri = ''): UriInterface + { + return new Uri($uri); + } +} diff --git a/lib/guzzlehttp/psr7/src/InflateStream.php b/lib/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 00000000..8e3cf171 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,34 @@ + 15 + 32]); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } +} diff --git a/lib/guzzlehttp/psr7/src/LazyOpenStream.php b/lib/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 00000000..6b604296 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,40 @@ +filename = $filename; + $this->mode = $mode; + } + + /** + * Creates the underlying stream lazily when required. + */ + protected function createStream(): StreamInterface + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/lib/guzzlehttp/psr7/src/LimitStream.php b/lib/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 00000000..9762d38a --- /dev/null +++ b/lib/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,154 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof(): bool + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit === -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + */ + public function getSize(): ?int + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit === -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + */ + public function seek($offset, $whence = SEEK_SET): void + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + */ + public function tell(): int + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset(int $offset): void + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + } + + public function read($length): string + { + if ($this->limit === -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/lib/guzzlehttp/psr7/src/Message.php b/lib/guzzlehttp/psr7/src/Message.php new file mode 100644 index 00000000..9b825b30 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,242 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: " . $value; + } + } else { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n" . $message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + */ + public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message): void + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + */ + public static function parseMessage(string $message): array + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + [$rawHeaders, $body] = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + [$startLine, $rawHeaders] = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + */ + public static function parseRequestUri(string $path, array $headers): string + { + $hostKey = array_filter(array_keys($headers), function ($k) { + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + */ + public static function parseRequest(string $message): RequestInterface + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + */ + public static function parseResponse(string $message): ResponseInterface + { + $data = self::parseMessage($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + $parts[2] ?? null + ); + } +} diff --git a/lib/guzzlehttp/psr7/src/MessageTrait.php b/lib/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 00000000..503c280b --- /dev/null +++ b/lib/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,235 @@ + Map of all registered headers, as original name => array of values */ + private $headers = []; + + /** @var array Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion(): string + { + return $this->protocol; + } + + public function withProtocolVersion($version): MessageInterface + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders(): array + { + return $this->headers; + } + + public function hasHeader($header): bool + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header): array + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header): string + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value): MessageInterface + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header): MessageInterface + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody(): StreamInterface + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body): MessageInterface + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + /** + * @param array $headers + */ + private function setHeaders(array $headers): void + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + if (is_int($header)) { + // Numeric array keys are converted to int by PHP but having a header name '123' is not forbidden by the spec + // and also allowed in withHeader(). So we need to cast it to string again for the following assertion to pass. + $header = (string) $header; + } + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + /** + * @param mixed $value + * + * @return string[] + */ + private function normalizeHeaderValue($value): array + { + if (!is_array($value)) { + return $this->trimHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param mixed[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + */ + private function trimHeaderValues(array $values): array + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + return trim((string) $value, " \t"); + }, array_values($values)); + } + + /** + * @see https://tools.ietf.org/html/rfc7230#section-3.2 + * + * @param mixed $header + */ + private function assertHeader($header): void + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $header)) { + throw new \InvalidArgumentException( + sprintf( + '"%s" is not valid header name', + $header + ) + ); + } + } +} diff --git a/lib/guzzlehttp/psr7/src/MimeType.php b/lib/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 00000000..dfa94251 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,130 @@ + 'video/3gpp', + '7z' => 'application/x-7z-compressed', + 'aac' => 'audio/x-aac', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'asc' => 'text/plain', + 'asf' => 'video/x-ms-asf', + 'atom' => 'application/atom+xml', + 'avi' => 'video/x-msvideo', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bzip2', + 'cer' => 'application/pkix-cert', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'css' => 'text/css', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'deb' => 'application/x-debian-package', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dvi' => 'application/x-dvi', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'etx' => 'text/x-setext', + 'flac' => 'audio/flac', + 'flv' => 'video/x-flv', + 'gif' => 'image/gif', + 'gz' => 'application/gzip', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ini' => 'text/plain', + 'iso' => 'application/x-iso9660-image', + 'jar' => 'application/java-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'latex' => 'application/x-latex', + 'log' => 'text/plain', + 'm4a' => 'audio/mp4', + 'm4v' => 'video/mp4', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mkv' => 'video/x-matroska', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4v' => 'video/mp4', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'pbm' => 'image/x-portable-bitmap', + 'pdf' => 'application/pdf', + 'pgm' => 'image/x-portable-graymap', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'ppm' => 'image/x-portable-pixmap', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'qt' => 'video/quicktime', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'svg' => 'image/svg+xml', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'torrent' => 'application/x-bittorrent', + 'ttf' => 'application/x-font-ttf', + 'txt' => 'text/plain', + 'wav' => 'audio/x-wav', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'video/x-ms-wmv', + 'woff' => 'application/x-font-woff', + 'wsdl' => 'application/wsdl+xml', + 'xbm' => 'image/x-xbitmap', + 'xls' => 'application/vnd.ms-excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'yaml' => 'text/yaml', + 'yml' => 'text/yaml', + 'zip' => 'application/zip', + ]; + + /** + * Determines the mimetype of a file by looking at its extension. + */ + public static function fromFilename(string $filename): ?string + { + return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); + } + + /** + * Maps a file extensions to a mimetype. + * + * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types + */ + public static function fromExtension(string $extension): ?string + { + return self::MIME_TYPES[strtolower($extension)] ?? null; + } +} diff --git a/lib/guzzlehttp/psr7/src/MultipartStream.php b/lib/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 00000000..f76d7c61 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,153 @@ +boundary = $boundary ?: sha1(uniqid('', true)); + $this->stream = $this->createStream($elements); + } + + public function getBoundary(): string + { + return $this->boundary; + } + + public function isWritable(): bool + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + * + * @param array $headers + */ + private function getHeaders(array $headers): string + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements = []): StreamInterface + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element): void + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if (substr($uri, 0, 6) !== 'php://') { + $element['filename'] = $uri; + } + } + + [$body, $headers] = $this->createElement( + $element['name'], + $element['contents'], + $element['filename'] ?? null, + $element['headers'] ?? [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + if ($type = MimeType::fromFilename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return [$stream, $headers]; + } + + private function getHeader(array $headers, string $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/lib/guzzlehttp/psr7/src/NoSeekStream.php b/lib/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 00000000..99e25b9e --- /dev/null +++ b/lib/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,25 @@ +source = $source; + $this->size = $options['size'] ?? null; + $this->metadata = $options['metadata'] ?? []; + $this->buffer = new BufferStream(); + } + + public function __toString(): string + { + try { + return Utils::copyToString($this); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function close(): void + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = 0; + $this->source = null; + + return null; + } + + public function getSize(): ?int + { + return $this->size; + } + + public function tell(): int + { + return $this->tellPos; + } + + public function eof(): bool + { + return $this->source === null; + } + + public function isSeekable(): bool + { + return false; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable(): bool + { + return false; + } + + public function write($string): int + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable(): bool + { + return true; + } + + public function read($length): string + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents(): string + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return $this->metadata[$key] ?? null; + } + + private function pump(int $length): void + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/lib/guzzlehttp/psr7/src/Query.php b/lib/guzzlehttp/psr7/src/Query.php new file mode 100644 index 00000000..4fd0ca96 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + */ + public static function parse(string $str, $urlEncoding = true): array + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', (string) $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!isset($result[$key])) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? (int) $v : $v; + if ($v !== null) { + $qs .= '=' . $encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? (int) $vv : $vv; + if ($vv !== null) { + $qs .= '=' . $encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/lib/guzzlehttp/psr7/src/Request.php b/lib/guzzlehttp/psr7/src/Request.php new file mode 100644 index 00000000..b17af66a --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,157 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1' + ) { + $this->assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget(): string + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target === '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget): RequestInterface + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod(): string + { + return $this->method; + } + + public function withMethod($method): RequestInterface + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri(): UriInterface + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false): RequestInterface + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri(): void + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':' . $port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + /** + * @param mixed $method + */ + private function assertMethod($method): void + { + if (!is_string($method) || $method === '') { + throw new InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/lib/guzzlehttp/psr7/src/Response.php b/lib/guzzlehttp/psr7/src/Response.php new file mode 100644 index 00000000..4c6ee6f0 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,160 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 510 => 'Not Extended', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase; + + /** @var int */ + private $statusCode; + + /** + * @param int $status Status code + * @param array $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + int $status = 200, + array $headers = [], + $body = null, + string $version = '1.1', + string $reason = null + ) { + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::PHRASES[$this->statusCode])) { + $this->reasonPhrase = self::PHRASES[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode(): int + { + return $this->statusCode; + } + + public function getReasonPhrase(): string + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = ''): ResponseInterface + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::PHRASES[$new->statusCode])) { + $reasonPhrase = self::PHRASES[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + return $new; + } + + /** + * @param mixed $statusCode + */ + private function assertStatusCodeIsInteger($statusCode): void + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange(int $statusCode): void + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/lib/guzzlehttp/psr7/src/Rfc7230.php b/lib/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 00000000..30224018 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,23 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/lib/guzzlehttp/psr7/src/ServerRequest.php b/lib/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 00000000..6ae3f9be --- /dev/null +++ b/lib/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,344 @@ + $headers Request headers + * @param string|resource|StreamInterface|null $body Request body + * @param string $version Protocol version + * @param array $serverParams Typically the $_SERVER superglobal + */ + public function __construct( + string $method, + $uri, + array $headers = [], + $body = null, + string $version = '1.1', + array $serverParams = [] + ) { + $this->serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files A array which respect $_FILES structure + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files): array + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return UploadedFileInterface|UploadedFileInterface[] + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []): array + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key], + 'error' => $files['error'][$key], + 'name' => $files['name'][$key], + 'type' => $files['type'][$key], + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + */ + public static function fromGlobals(): ServerRequestInterface + { + $method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority(string $authority): array + { + $uri = 'http://' . $authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = $parts['host'] ?? null; + $port = $parts['port'] ?? null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + */ + public static function getUriFromGlobals(): UriInterface + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + [$host, $port] = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + public function getServerParams(): array + { + return $this->serverParams; + } + + public function getUploadedFiles(): array + { + return $this->uploadedFiles; + } + + public function withUploadedFiles(array $uploadedFiles): ServerRequestInterface + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + public function getCookieParams(): array + { + return $this->cookieParams; + } + + public function withCookieParams(array $cookies): ServerRequestInterface + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + public function getQueryParams(): array + { + return $this->queryParams; + } + + public function withQueryParams(array $query): ServerRequestInterface + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * {@inheritdoc} + * + * @return array|object|null + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data): ServerRequestInterface + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + public function getAttributes(): array + { + return $this->attributes; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + public function withAttribute($attribute, $value): ServerRequestInterface + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + public function withoutAttribute($attribute): ServerRequestInterface + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/lib/guzzlehttp/psr7/src/Stream.php b/lib/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 00000000..d389427c --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,279 @@ +size = $options['size']; + } + + $this->customMetadata = $options['metadata'] ?? []; + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $contents = stream_get_contents($this->stream); + + if ($contents === false) { + throw new \RuntimeException('Unable to read stream contents'); + } + + return $contents; + } + + public function close(): void + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize(): ?int + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (is_array($stats) && isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable(): bool + { + return $this->readable; + } + + public function isWritable(): bool + { + return $this->writable; + } + + public function isSeekable(): bool + { + return $this->seekable; + } + + public function eof(): bool + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell(): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length): string + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + $string = fread($this->stream, $length); + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string): int + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return $meta[$key] ?? null; + } +} diff --git a/lib/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/lib/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 00000000..56d4104d --- /dev/null +++ b/lib/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,155 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @return StreamInterface + */ + public function __get(string $name) + { + if ($name === 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString(): string + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR); + return ''; + } + } + + public function getContents(): string + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @return mixed + */ + public function __call(string $method, array $args) + { + /** @var callable $callable */ + $callable = [$this->stream, $method]; + $result = call_user_func_array($callable, $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close(): void + { + $this->stream->close(); + } + + /** + * {@inheritdoc} + * + * @return mixed + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int + { + return $this->stream->getSize(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function rewind(): void + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @throws \BadMethodCallException + */ + protected function createStream(): StreamInterface + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/lib/guzzlehttp/psr7/src/StreamWrapper.php b/lib/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 00000000..2a934640 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,175 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream] + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register(): void + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read(int $count): string + { + return $this->stream->read($count); + } + + public function stream_write(string $data): int + { + return $this->stream->write($data); + } + + public function stream_tell(): int + { + return $this->stream->tell(); + } + + public function stream_eof(): bool + { + return $this->stream->eof(); + } + + public function stream_seek(int $offset, int $whence): bool + { + $this->stream->seek($offset, $whence); + + return true; + } + + /** + * @return resource|false + */ + public function stream_cast(int $cast_as) + { + $stream = clone($this->stream); + $resource = $stream->detach(); + + return $resource ?? false; + } + + /** + * @return array + */ + public function stream_stat(): array + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188 + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } + + /** + * @return array + */ + public function url_stat(string $path, int $flags): array + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } +} diff --git a/lib/guzzlehttp/psr7/src/UploadedFile.php b/lib/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 00000000..b1521bcf --- /dev/null +++ b/lib/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,211 @@ +setError($errorStatus); + $this->size = $size; + $this->clientFilename = $clientFilename; + $this->clientMediaType = $clientMediaType; + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param StreamInterface|string|resource $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile): void + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @throws InvalidArgumentException + */ + private function setError(int $error): void + { + if (false === in_array($error, UploadedFile::ERRORS, true)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + private function isStringNotEmpty($param): bool + { + return is_string($param) && false === empty($param); + } + + /** + * Return true if there is no upload error + */ + private function isOk(): bool + { + return $this->error === UPLOAD_ERR_OK; + } + + public function isMoved(): bool + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive(): void + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + public function getStream(): StreamInterface + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + /** @var string $file */ + $file = $this->file; + + return new LazyOpenStream($file, 'r+'); + } + + public function moveTo($targetPath): void + { + $this->validateActive(); + + if (false === $this->isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = PHP_SAPI === 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + public function getSize(): ?int + { + return $this->size; + } + + public function getError(): int + { + return $this->error; + } + + public function getClientFilename(): ?string + { + return $this->clientFilename; + } + + public function getClientMediaType(): ?string + { + return $this->clientMediaType; + } +} diff --git a/lib/guzzlehttp/psr7/src/Uri.php b/lib/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 00000000..3898f783 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,733 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + /** + * Unreserved characters for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.3 + */ + private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~'; + + /** + * Sub-delims for use in a regex. + * + * @link https://tools.ietf.org/html/rfc3986#section-2.2 + */ + private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;='; + private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** @var string|null String representation */ + private $composedComponents; + + public function __construct(string $uri = '') + { + if ($uri !== '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new MalformedUriException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @return array|false + */ + private static function parse(string $url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + /** @var array{0:string, 1:string, 2:string} $matches */ + $prefix = $matches[1]; + $url = $matches[2]; + } + + /** @var string */ + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix . $encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString(): string + { + if ($this->composedComponents === null) { + $this->composedComponents = self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + return $this->composedComponents; + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @link https://tools.ietf.org/html/rfc3986#section-5.3 + */ + public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme . ':'; + } + + if ($authority != ''|| $scheme === 'file') { + $uri .= '//' . $authority; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?' . $query; + } + + if ($fragment != '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + */ + public static function isDefaultPort(UriInterface $uri): bool + { + return $uri->getPort() === null + || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri): bool + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri): bool + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + */ + public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + */ + public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param array $keyValueArray Associative array of key and values + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @link http://php.net/manual/en/function.parse-url.php + * + * @throws MalformedUriException If the components do not form a valid URI. + */ + public static function fromParts(array $parts): UriInterface + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme(): string + { + return $this->scheme; + } + + public function getAuthority(): string + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo(): string + { + return $this->userInfo; + } + + public function getHost(): string + { + return $this->host; + } + + public function getPort(): ?int + { + return $this->port; + } + + public function getPath(): string + { + return $this->path; + } + + public function getQuery(): string + { + return $this->query; + } + + public function getFragment(): string + { + return $this->fragment; + } + + public function withScheme($scheme): UriInterface + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null): UriInterface + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':' . $this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withHost($host): UriInterface + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withPort($port): UriInterface + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->composedComponents = null; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path): UriInterface + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->composedComponents = null; + $new->validateState(); + + return $new; + } + + public function withQuery($query): UriInterface + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + $new->composedComponents = null; + + return $new; + } + + public function withFragment($fragment): UriInterface + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + $new->composedComponents = null; + + return $new; + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts): void + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param mixed $scheme + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme): string + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $component + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component): string + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param mixed $host + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host): string + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param mixed $port + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port): ?int + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param string[] $keys + * + * @return string[] + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys): array + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map('rawurldecode', $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + private static function generateQueryString(string $key, ?string $value): string + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT); + + if ($value !== null) { + $queryString .= '=' . strtr($value, self::QUERY_SEPARATORS_REPLACEMENT); + } + + return $queryString; + } + + private function removeDefaultPort(): void + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param mixed $path + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path): string + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param mixed $str + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str): string + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match): string + { + return rawurlencode($match[0]); + } + + private function validateState(): void + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } elseif (isset($this->path[0]) && $this->path[0] !== '/') { + throw new MalformedUriException('The path of a URI with an authority must start with a slash "/" or be empty'); + } + } +} diff --git a/lib/guzzlehttp/psr7/src/UriNormalizer.php b/lib/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 00000000..e12971ed --- /dev/null +++ b/lib/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,220 @@ +getPath() === '' && + ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @link https://tools.ietf.org/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri): UriInterface + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match) { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match) { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/lib/guzzlehttp/psr7/src/UriResolver.php b/lib/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 00000000..426e5c9a --- /dev/null +++ b/lib/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,211 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/' . $rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + */ + public static function relativize(UriInterface $base, UriInterface $target): UriInterface + { + if ($target->getScheme() !== '' && + ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + /** @var string $lastSegment */ + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target): string + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/lib/guzzlehttp/psr7/src/Utils.php b/lib/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 00000000..6cc04ee4 --- /dev/null +++ b/lib/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,412 @@ + $v) { + if (!is_string($k) || !in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, int $maxLen = -1): string + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + if ($buf === '') { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + if ($buf === '') { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, (bool) $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + */ + public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':' . $port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + $changes['method'] ?? $request->getMethod(), + $uri, + $headers, + $changes['body'] ?? $request->getBody(), + $changes['version'] ?? $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + */ + public static function readLine(StreamInterface $stream, ?int $maxLength = null): string + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + if ('' === ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array{size?: int, metadata?: array} $options Additional options + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []): StreamInterface + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, (string) $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + + /** @var resource $resource */ + if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + fwrite($stream, stream_get_contents($resource)); + fseek($stream, 0); + $resource = $stream; + } + return new Stream($resource, $options); + case 'object': + /** @var object $resource */ + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return self::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen(string $filename, string $mode) + { + $ex = null; + set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $errstr + )); + + return true; + }); + + try { + /** @var resource $handle */ + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri): UriInterface + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/lib/guzzlehttp/psr7/vendor-bin/php-cs-fixer/composer.json b/lib/guzzlehttp/psr7/vendor-bin/php-cs-fixer/composer.json new file mode 100644 index 00000000..d69a683b --- /dev/null +++ b/lib/guzzlehttp/psr7/vendor-bin/php-cs-fixer/composer.json @@ -0,0 +1,9 @@ +{ + "require": { + "php": "^7.2.5 || ^8.0", + "friendsofphp/php-cs-fixer": "3.2.1" + }, + "config": { + "preferred-install": "dist" + } +} diff --git a/lib/guzzlehttp/psr7/vendor-bin/phpstan/composer.json b/lib/guzzlehttp/psr7/vendor-bin/phpstan/composer.json new file mode 100644 index 00000000..bfbc7273 --- /dev/null +++ b/lib/guzzlehttp/psr7/vendor-bin/phpstan/composer.json @@ -0,0 +1,10 @@ +{ + "require": { + "php": "^7.2.5 || ^8.0", + "phpstan/phpstan": "0.12.81", + "phpstan/phpstan-deprecation-rules": "0.12.6" + }, + "config": { + "preferred-install": "dist" + } +} diff --git a/lib/guzzlehttp/psr7/vendor-bin/psalm/composer.json b/lib/guzzlehttp/psr7/vendor-bin/psalm/composer.json new file mode 100644 index 00000000..535a0797 --- /dev/null +++ b/lib/guzzlehttp/psr7/vendor-bin/psalm/composer.json @@ -0,0 +1,9 @@ +{ + "require": { + "php": "^7.2.5 || ^8.0", + "psalm/phar": "4.6.2" + }, + "config": { + "preferred-install": "dist" + } +} diff --git a/lib/http_request.inc.php b/lib/http_request.inc.php index c533b5c8..04c79da4 100755 --- a/lib/http_request.inc.php +++ b/lib/http_request.inc.php @@ -146,7 +146,7 @@ public function send_http_request($url, $referer, $data, $method = 'POST', $cont // parse the given URL $url = parse_url($url); - if ($url['scheme'] != 'http') { + if (!in_array($url['scheme'], ['http', 'https'])) { return false; } diff --git a/lib/lang/locale/id_ID/LC_MESSAGES/messages.mo b/lib/lang/locale/id_ID/LC_MESSAGES/messages.mo index 39f5d6bf..ffbb7aef 100644 Binary files a/lib/lang/locale/id_ID/LC_MESSAGES/messages.mo and b/lib/lang/locale/id_ID/LC_MESSAGES/messages.mo differ diff --git a/lib/lang/locale/id_ID/LC_MESSAGES/messages.po b/lib/lang/locale/id_ID/LC_MESSAGES/messages.po index 06484e3c..716d24f1 100755 --- a/lib/lang/locale/id_ID/LC_MESSAGES/messages.po +++ b/lib/lang/locale/id_ID/LC_MESSAGES/messages.po @@ -5,8 +5,8 @@ msgid "" msgstr "" "Project-Id-Version: Senayan3\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2021-06-21 11:10+0700\n" -"PO-Revision-Date: 2021-06-21 11:15+0700\n" +"POT-Creation-Date: 2022-03-18 21:10+0700\n" +"PO-Revision-Date: 2022-03-18 21:10+0700\n" "Last-Translator: Arif Syamsudin Budi W. \n" "Language-Team: Arie Nugraha; Hendro Wicaksono; Wardiyono \n" @@ -18,7 +18,7 @@ msgstr "" "X-Poedit-SourceCharset: utf-8\n" "X-Poedit-KeywordsList: __;_ngettext:1,2\n" "X-Poedit-Basepath: ../../../../..\n" -"X-Generator: Poedit 3.0\n" +"X-Generator: Poedit 3.0.1\n" "X-Poedit-SearchPath-0: .\n" #: admin/AJAX_check_id.php:21 @@ -40,7 +40,7 @@ msgstr "Tambah Baru" #: admin/admin_template/akasia-dz/function.php:55 #: admin/admin_template/akasia/function.php:59 msgid "Shortcut" -msgstr "Pemintas" +msgstr "Jalan pintas" #: admin/admin_template/akasia-dz/function.php:64 #: admin/admin_template/akasia/function.php:68 @@ -58,8 +58,8 @@ msgstr "OPAC" msgid "Logout" msgstr "Keluar" -#: admin/admin_template/akasia-dz/index_template.inc.php:104 -#: admin/admin_template/akasia/index_template.inc.php:103 +#: admin/admin_template/akasia-dz/index_template.inc.php:112 +#: admin/admin_template/akasia/index_template.inc.php:111 #: template/default/parts/_navbar.php:23 msgid "Help" msgstr "Bantuan" @@ -77,16 +77,16 @@ msgstr "Daftar Terkendali" #: admin/admin_template/barcodescannermodal.tpl.php:7 msgid "Barcode Reader" -msgstr "Pembaca Barkod" +msgstr "Pembaca Kode batang" #: admin/admin_template/barcodescannermodal.tpl.php:16 #: admin/modules/serial_control/index.php:97 msgid "Close" msgstr "Tutup" -#: admin/admin_template/default/index_template.inc.php:72 -#: admin/admin_template/nightmode/index_template.inc.php:68 admin/chat.php:15 -#: lib/contents/chat.php:89 sysconfig.inc.php:712 +#: admin/admin_template/default/index_template.inc.php:80 +#: admin/admin_template/nightmode/index_template.inc.php:76 admin/chat.php:15 +#: lib/contents/chat.php:89 sysconfig.inc.php:719 #: template/akasia-dz/partials/nav.php:10 template/akasia/partials/nav.php:10 #: template/default/parts/_navbar.php:27 template/default/parts/footer.php:41 #: template/lightweight/partials/nav.php:10 @@ -114,18 +114,18 @@ msgstr "Warna Tema.
        ( Baku : #004db6 )" #: admin/admin_template/default/tinfo.inc.php:13 msgid "Always Show Tracks" -msgstr "Selalu Tunjukkan Jalur Gulung" +msgstr "Selalu Tunjukkan Jalur" #: admin/admin_template/default/tinfo.inc.php:17 #: admin/modules/bibliography/export.php:211 #: admin/modules/bibliography/import.php:288 #: admin/modules/bibliography/item_export.php:188 -#: admin/modules/bibliography/item_import.php:237 +#: admin/modules/bibliography/item_import.php:246 #: admin/modules/membership/export.php:168 #: admin/modules/membership/import.php:229 #: admin/modules/membership/index.php:557 #: admin/modules/stock_take/finish.php:185 admin/modules/system/content.php:221 -#: admin/modules/system/index.php:320 +#: admin/modules/system/index.php:330 msgid "Yes" msgstr "Ya" @@ -144,7 +144,7 @@ msgstr "" "Kepada ()\n" "Surel ini menginformasikan bahwa Anda memiliki KETERLAMBATAN pinjaman perpustakaan,\n" -"koleksi tersebut adalah:" +"koleksi-koleksi tersebut adalah:" #: admin/admin_template/overdue-mail-tpl.php:10 msgid "" @@ -152,7 +152,8 @@ msgid "" "any complaint regarding to this overdue notification,\n" "please contact our circulation desk." msgstr "" -"Segera kembalikan koleksi yang telat ke perpustakaan. Jika Anda memiliki\n" +"Segera kembalikan koleksi yang terlambat ke perpustakaan. Jika Anda " +"memiliki\n" "keluhan tentang pemberitahuan ini,\n" "harap hubungi petugas perpustakaan." @@ -170,11 +171,11 @@ msgstr "" #: admin/chat.php:6 msgid "Chat With Members" -msgstr "Memulai obrolan dengan anggota" +msgstr "Berbincang dengan anggota" #: admin/chat.php:14 lib/contents/chat.php:88 msgid "Please type and hit Enter button to send your messages" -msgstr "Ketik dan tekan tombol Enter untuk berkirim pesan" +msgstr "Tekan tombol ENTER untuk mengirimkan pesan" #: admin/chat.php:15 lib/contents/chat.php:89 msgid "Members" @@ -190,7 +191,7 @@ msgid "" "application won't be able to create image thumbnail and barcode." msgstr "" "Ekstensi PHP GD belum terpasang. Pastikan PHP GD sudah " -"terpasang atau aplikasi tidak dapat membuat gambar mini dan barkod." +"terpasang atau aplikasi tidak dapat membuat gambar mini dan Kode batang." #: admin/default/home.php:57 msgid "" @@ -199,7 +200,7 @@ msgid "" "to create barcode." msgstr "" "Dukungan Freetype pada PHP GD belum ada. Bangun-ulang PHP " -"GD dengan dukungan Freetype atau aplikasi tidak dapat membuat barkod." +"GD dengan dukungan Freetype atau aplikasi tidak dapat membuat Kode batang." #: admin/default/home.php:64 msgid "" @@ -219,7 +220,7 @@ msgid "" msgstr "" "Direktori Images dan direktori-direktori di bawahnya tidak " "dapat ditulis. Pastikan direktori-direktori ini bisa ditulis atau aplikasi " -"tidak dapat mengunggah gambar dan membuat barkod" +"tidak dapat mengunggah gambar dan membuat Kode batang" #: admin/default/home.php:73 msgid "" @@ -282,10 +283,10 @@ msgstr "Total Eksemplar" msgid "Lent" msgstr "Dipinjamkan" -#: admin/default/home.php:186 admin/modules/bibliography/index.php:805 +#: admin/default/home.php:186 admin/modules/bibliography/index.php:813 #: admin/modules/bibliography/item.php:323 #: admin/modules/circulation/reserve_list.php:110 -#: admin/modules/reporting/customs/item_titles_list.php:257 +#: admin/modules/reporting/customs/item_titles_list.php:263 #: lib/detail.inc.php:248 msgid "Available" msgstr "Tersedia" @@ -333,7 +334,7 @@ msgstr "Perpanjang" #: admin/default/home.php:240 admin/default/home.php:303 #: admin/modules/membership/member_base_lib.inc.php:208 -#: admin/modules/reporting/customs/overdued_list.php:196 +#: admin/modules/reporting/customs/overdued_list.php:209 msgid "Overdue" msgstr "Keterlambatan" @@ -350,7 +351,7 @@ msgstr "Keterlambatan" #: admin/modules/bibliography/iframe_topic.php:43 #: admin/modules/bibliography/import.php:46 #: admin/modules/bibliography/index.php:59 -#: admin/modules/bibliography/index.php:671 +#: admin/modules/bibliography/index.php:679 #: admin/modules/bibliography/item.php:54 #: admin/modules/bibliography/item.php:226 #: admin/modules/bibliography/item_barcode_generator.php:44 @@ -388,7 +389,7 @@ msgstr "Klik di sini untuk Masuk kembali" msgid "SHORTCUT" msgstr "PEMINTAS" -#: admin/default/submenu.php:22 admin/modules/system/app_user.php:409 +#: admin/default/submenu.php:22 admin/modules/system/app_user.php:415 msgid "Change User Profiles" msgstr "Ubah Profil Pengguna" @@ -396,15 +397,15 @@ msgstr "Ubah Profil Pengguna" msgid "Change Current User Profiles and Password" msgstr "Ubah Profil dan Kata Sandi Pengguna Saat Ini" -#: admin/default/submenu.php:23 admin/modules/system/submenu.php:51 +#: admin/default/submenu.php:23 admin/modules/system/submenu.php:53 msgid "Shortcut Setting" msgstr "Pengaturan Pemintas" -#: admin/default/submenu.php:24 admin/modules/system/submenu.php:34 +#: admin/default/submenu.php:24 admin/modules/system/submenu.php:35 msgid "Theme" msgstr "Tema" -#: admin/default/submenu.php:24 admin/modules/system/submenu.php:34 +#: admin/default/submenu.php:24 admin/modules/system/submenu.php:35 msgid "Configure theme Preferences" msgstr "Konfigurasi Tema" @@ -445,8 +446,8 @@ msgstr "Daftar Eksemplar Keluar" #: admin/modules/bibliography/checkout_item.php:56 #: admin/modules/bibliography/dl_print.php:228 #: admin/modules/bibliography/dl_print.php:230 -#: admin/modules/bibliography/index.php:572 -#: admin/modules/bibliography/index.php:582 +#: admin/modules/bibliography/index.php:580 +#: admin/modules/bibliography/index.php:590 #: admin/modules/bibliography/item.php:212 #: admin/modules/bibliography/item.php:215 #: admin/modules/bibliography/item_barcode_generator.php:221 @@ -508,8 +509,8 @@ msgstr "Daftar Eksemplar Keluar" #: admin/modules/stock_take/current.php:130 #: admin/modules/stock_take/index.php:58 admin/modules/stock_take/index.php:60 #: admin/modules/stock_take/st_log.php:59 -#: admin/modules/stock_take/st_log.php:61 admin/modules/system/app_user.php:269 -#: admin/modules/system/app_user.php:271 admin/modules/system/backup.php:128 +#: admin/modules/stock_take/st_log.php:61 admin/modules/system/app_user.php:275 +#: admin/modules/system/app_user.php:277 admin/modules/system/backup.php:128 #: admin/modules/system/backup.php:130 admin/modules/system/content.php:176 #: admin/modules/system/content.php:178 #: admin/modules/system/custom_field.php:173 @@ -544,8 +545,9 @@ msgstr "Cari" #: admin/modules/circulation/member_loan_hist.php:62 #: admin/modules/circulation/reserve_list.php:96 #: admin/modules/membership/member_base_lib.inc.php:208 -#: admin/modules/reporting/customs/item_titles_list.php:74 -#: admin/modules/reporting/customs/item_titles_list.php:157 +#: admin/modules/reporting/customs/item_titles_list.php:75 +#: admin/modules/reporting/customs/item_titles_list.php:161 +#: admin/modules/reporting/customs/item_titles_list.php:288 #: admin/modules/reporting/customs/item_usage.php:73 #: admin/modules/reporting/customs/item_usage.php:107 #: admin/modules/reporting/customs/loan_history.php:91 @@ -564,7 +566,7 @@ msgstr "Cari" #: admin/modules/stock_take/st_report_detail.php:103 #: lib/contents/download_current_loan.inc.php:61 #: lib/contents/download_loan_history.inc.php:61 -#: lib/contents/member.inc.php:359 lib/contents/member.inc.php:405 +#: lib/contents/member.inc.php:364 lib/contents/member.inc.php:410 #: plugins/label_barcode/index.php:332 plugins/label_barcode/index.php:340 #: plugins/read_counter/index.php:82 msgid "Item Code" @@ -597,19 +599,19 @@ msgstr "Kode Eksemplar" #: admin/modules/reporting/customs/reserve_list.php:115 #: admin/modules/reporting/customs/visitor_list.php:125 #: admin/modules/reporting/customs/visitor_list.php:170 -#: files/membercard/old/membercard.php:293 lib/contents/member.inc.php:244 -#: lib/contents/member.inc.php:906 template/default/visitor_template.php:38 +#: files/membercard/old/membercard.php:293 lib/contents/member.inc.php:249 +#: lib/contents/member.inc.php:911 template/default/visitor_template.php:38 msgid "Member ID" msgstr "ID Anggota" #: admin/modules/bibliography/checkout_item.php:73 #: admin/modules/bibliography/dl_print.php:263 #: admin/modules/bibliography/dl_print.php:271 -#: admin/modules/bibliography/index.php:733 -#: admin/modules/bibliography/index.php:1208 -#: admin/modules/bibliography/index.php:1215 -#: admin/modules/bibliography/index.php:1235 -#: admin/modules/bibliography/index.php:1241 +#: admin/modules/bibliography/index.php:741 +#: admin/modules/bibliography/index.php:1216 +#: admin/modules/bibliography/index.php:1223 +#: admin/modules/bibliography/index.php:1243 +#: admin/modules/bibliography/index.php:1249 #: admin/modules/bibliography/item.php:287 #: admin/modules/bibliography/item.php:406 #: admin/modules/bibliography/item.php:415 @@ -622,7 +624,7 @@ msgstr "ID Anggota" #: admin/modules/bibliography/marcsru.php:343 #: admin/modules/bibliography/p2p.php:313 #: admin/modules/bibliography/p2p.php:369 -#: admin/modules/bibliography/pop_attach.php:204 +#: admin/modules/bibliography/pop_attach.php:211 #: admin/modules/bibliography/pop_author_edit.php:89 #: admin/modules/bibliography/pop_biblio_rel.php:90 #: admin/modules/bibliography/pop_biblio_rel.php:92 @@ -640,7 +642,8 @@ msgstr "ID Anggota" #: admin/modules/reporting/customs/dl_counter.php:200 #: admin/modules/reporting/customs/dl_detail.php:120 #: admin/modules/reporting/customs/dl_detail.php:182 -#: admin/modules/reporting/customs/item_titles_list.php:158 +#: admin/modules/reporting/customs/item_titles_list.php:162 +#: admin/modules/reporting/customs/item_titles_list.php:289 #: admin/modules/reporting/customs/item_usage.php:108 #: admin/modules/reporting/customs/loan_history.php:85 #: admin/modules/reporting/customs/loan_history.php:152 @@ -658,11 +661,11 @@ msgstr "ID Anggota" #: admin/modules/stock_take/lost_item_list.php:140 #: admin/modules/stock_take/st_report_detail.php:87 #: admin/modules/stock_take/st_report_detail.php:104 -#: files/membercard/classic/tinfo.inc.php:117 lib/contents/default.inc.php:162 +#: files/membercard/classic/tinfo.inc.php:117 #: lib/contents/download_current_loan.inc.php:62 #: lib/contents/download_loan_history.inc.php:62 -#: lib/contents/member.inc.php:360 lib/contents/member.inc.php:406 -#: lib/contents/member.inc.php:441 lib/detail.inc.php:267 +#: lib/contents/member.inc.php:365 lib/contents/member.inc.php:411 +#: lib/contents/member.inc.php:446 lib/detail.inc.php:267 #: plugins/label_barcode/index.php:331 plugins/label_barcode/index.php:339 #: plugins/read_counter/index.php:82 template/akasia/partials/advsearch.php:16 #: template/default/parts/_modal_advanced.php:24 @@ -680,10 +683,10 @@ msgstr "Judul" #: admin/modules/reporting/customs/loan_history.php:153 #: admin/modules/reporting/customs/loan_history.php:238 #: admin/modules/reporting/customs/member_loan_list.php:191 -#: admin/modules/reporting/customs/overdued_list.php:197 +#: admin/modules/reporting/customs/overdued_list.php:210 #: lib/contents/download_current_loan.inc.php:63 #: lib/contents/download_loan_history.inc.php:63 -#: lib/contents/member.inc.php:361 lib/contents/member.inc.php:407 +#: lib/contents/member.inc.php:366 lib/contents/member.inc.php:412 msgid "Loan Date" msgstr "Tanggal Pinjam" @@ -696,15 +699,15 @@ msgstr "Tanggal Pinjam" #: admin/modules/reporting/customs/loan_history.php:154 #: admin/modules/reporting/customs/loan_history.php:239 #: admin/modules/reporting/customs/member_loan_list.php:191 -#: admin/modules/reporting/customs/overdued_list.php:197 +#: admin/modules/reporting/customs/overdued_list.php:210 #: lib/contents/download_current_loan.inc.php:64 -#: lib/contents/member.inc.php:362 +#: lib/contents/member.inc.php:367 msgid "Due Date" msgstr "Tanggal Kembali" #: admin/modules/bibliography/checkout_item.php:116 #: admin/modules/bibliography/dl_print.php:309 -#: admin/modules/bibliography/index.php:1301 +#: admin/modules/bibliography/index.php:1309 #: admin/modules/bibliography/item.php:502 #: admin/modules/bibliography/item_barcode_generator.php:300 #: admin/modules/bibliography/marcexport.php:265 @@ -733,10 +736,10 @@ msgstr "Tanggal Kembali" #: admin/modules/stock_take/current.php:194 #: admin/modules/stock_take/index.php:170 #: admin/modules/stock_take/st_log.php:112 -#: admin/modules/system/app_user.php:469 admin/modules/system/backup.php:193 +#: admin/modules/system/app_user.php:475 admin/modules/system/backup.php:185 #: admin/modules/system/content.php:298 #: admin/modules/system/custom_field.php:291 -#: admin/modules/system/holiday.php:267 admin/modules/system/module.php:226 +#: admin/modules/system/holiday.php:296 admin/modules/system/module.php:226 #: admin/modules/system/sys_log.php:142 admin/modules/system/user_group.php:276 #: plugins/label_barcode/index.php:379 msgid "Found {result->num_rows} from your keywords" @@ -828,7 +831,7 @@ msgstr "Ubah setelan cetak label" #: admin/modules/bibliography/item_barcode_generator.php:228 #: admin/modules/bibliography/printed_card.php:320 #: admin/modules/membership/member_card_generator.php:207 -#: admin/modules/system/app_user.php:356 plugins/label_barcode/index.php:301 +#: admin/modules/system/app_user.php:362 plugins/label_barcode/index.php:301 msgid "Maximum" msgstr "Maksimum" @@ -850,18 +853,18 @@ msgstr "dalam antrian menunggu untuk dicetak." #: admin/modules/bibliography/dl_print.php:264 #: admin/modules/bibliography/dl_print.php:272 -#: admin/modules/bibliography/index.php:932 +#: admin/modules/bibliography/index.php:940 #: admin/modules/bibliography/item.php:299 #: admin/modules/bibliography/item.php:451 #: admin/modules/bibliography/item.php:463 #: admin/modules/bibliography/pop_p2p.php:63 -#: admin/modules/reporting/customs/item_titles_list.php:161 +#: admin/modules/reporting/customs/item_titles_list.php:165 +#: admin/modules/reporting/customs/item_titles_list.php:292 #: admin/modules/reporting/customs/titles_list.php:132 #: admin/modules/reporting/customs/titles_list.php:259 #: admin/modules/stock_take/current.php:150 #: admin/modules/stock_take/lost_item_list.php:144 -#: lib/contents/default.inc.php:170 plugins/label_barcode/index.php:332 -#: plugins/label_barcode/index.php:340 +#: plugins/label_barcode/index.php:332 plugins/label_barcode/index.php:340 #: template/akasia-dz/custom_frontpage_record.inc.php:10 #: template/akasia-dz/detail_template.php:57 #: template/akasia/custom_frontpage_record.inc.php:10 @@ -902,22 +905,22 @@ msgid "Add to print queue?" msgstr "Tambahkan dalam antrian cetak?" #: admin/modules/bibliography/dl_print.php:310 -#: admin/modules/bibliography/index.php:1302 +#: admin/modules/bibliography/index.php:1310 #: admin/modules/bibliography/item.php:503 #: admin/modules/bibliography/item_barcode_generator.php:301 #: admin/modules/bibliography/marcexport.php:266 #: admin/modules/bibliography/printed_card.php:403 -#: lib/contents/default.inc.php:209 plugins/label_barcode/index.php:380 +#: lib/contents/default.inc.php:96 plugins/label_barcode/index.php:380 msgid "Query took" msgstr "Permintaan membutuhkan" #: admin/modules/bibliography/dl_print.php:310 -#: admin/modules/bibliography/index.php:1302 +#: admin/modules/bibliography/index.php:1310 #: admin/modules/bibliography/item.php:503 #: admin/modules/bibliography/item_barcode_generator.php:301 #: admin/modules/bibliography/marcexport.php:266 #: admin/modules/bibliography/printed_card.php:403 -#: lib/contents/default.inc.php:209 plugins/label_barcode/index.php:380 +#: lib/contents/default.inc.php:96 plugins/label_barcode/index.php:380 msgid "second(s) to complete" msgstr "detik untuk selesai" @@ -959,7 +962,7 @@ msgstr "Ekspor Sekarang" #: admin/modules/bibliography/export.php:199 #: admin/modules/bibliography/import.php:280 #: admin/modules/bibliography/item_export.php:176 -#: admin/modules/bibliography/item_import.php:229 +#: admin/modules/bibliography/item_import.php:238 #: admin/modules/membership/export.php:156 #: admin/modules/membership/import.php:221 msgid "Field Separator" @@ -968,7 +971,7 @@ msgstr "Pemisah Ruas" #: admin/modules/bibliography/export.php:201 #: admin/modules/bibliography/import.php:282 #: admin/modules/bibliography/item_export.php:178 -#: admin/modules/bibliography/item_import.php:231 +#: admin/modules/bibliography/item_import.php:240 #: admin/modules/membership/export.php:158 #: admin/modules/membership/import.php:223 msgid "Field Enclosed With" @@ -991,7 +994,7 @@ msgstr "Jumlah Cantuman untuk diekspor (0 untuk semua rekod)" #: admin/modules/bibliography/export.php:209 #: admin/modules/bibliography/import.php:286 #: admin/modules/bibliography/item_export.php:186 -#: admin/modules/bibliography/item_import.php:235 +#: admin/modules/bibliography/item_import.php:244 #: admin/modules/bibliography/marcexport.php:201 #: admin/modules/membership/export.php:166 #: admin/modules/membership/import.php:227 @@ -1029,7 +1032,7 @@ msgid "Delete" msgstr "Hapus" #: admin/modules/bibliography/iframe_attach.php:127 -#: admin/modules/bibliography/index.php:1015 +#: admin/modules/bibliography/index.php:1023 msgid "File Attachments" msgstr "Lampiran Berkas" @@ -1054,7 +1057,7 @@ msgstr "Sunting" #: admin/modules/circulation/reserve_list.php:105 #: admin/modules/master_file/iframe_vocabolary_control.php:73 #: admin/modules/system/custom_field.php:243 -#: admin/modules/system/custom_field.php:312 lib/contents/member.inc.php:441 +#: admin/modules/system/custom_field.php:312 lib/contents/member.inc.php:446 msgid "Remove" msgstr "Hapus" @@ -1100,7 +1103,7 @@ msgstr "Pengarang dihapus!" #: admin/modules/master_file/submenu.php:33 #: admin/modules/reporting/customs/dl_counter.php:75 #: admin/modules/reporting/customs/titles_list.php:75 -#: lib/contents/default.inc.php:163 template/default/parts/_search-form.php:37 +#: template/default/parts/_search-form.php:37 msgid "Author" msgstr "Pengarang" @@ -1141,7 +1144,7 @@ msgid "Item FAILED to removed!" msgstr "Eksemplar GAGAL hapus!" #: admin/modules/bibliography/iframe_item_list.php:123 -#: admin/modules/bibliography/index.php:857 +#: admin/modules/bibliography/index.php:865 msgid "Items/Copies" msgstr "Eksemplar/Kopi" @@ -1172,7 +1175,7 @@ msgstr "Topic berhasil dihapus!" #: admin/modules/master_file/topic.php:181 #: admin/modules/master_file/topic.php:238 #: admin/modules/master_file/topic.php:282 -#: admin/modules/master_file/topic.php:288 lib/contents/default.inc.php:164 +#: admin/modules/master_file/topic.php:288 #: template/default/parts/_search-form.php:39 msgid "Subject" msgstr "Subjek" @@ -1209,46 +1212,46 @@ msgstr "" #: admin/modules/bibliography/import.php:249 msgid "" -"Import for bibliographics data from CSV file. For guide on CVS fields order " +"Import for bibliographics data from CSV file. For guide on CSV fields order " "and format please refer to documentation or visit
        Official Website" msgstr "" -"Impor data bibiliografi dari berkas CSV. Lihat panduan tentang format " -"penulisan dan urutan ruas dalam berkas CSV atau kunjungi Situs Resmi SLiMS" +"Berkas CSV untuk impor data bibliografi. Lihat panduan tentang urutan ruas " +"dalam berkas CSV atau kunjungi Situs Resmi SLiMS" #: admin/modules/bibliography/import.php:258 -#: admin/modules/bibliography/item_import.php:208 +#: admin/modules/bibliography/item_import.php:217 #: admin/modules/bibliography/marcimport.php:403 #: admin/modules/membership/import.php:199 msgid "Import Now" msgstr "Impor Sekarang" #: admin/modules/bibliography/import.php:278 -#: admin/modules/bibliography/item_import.php:227 +#: admin/modules/bibliography/item_import.php:236 #: admin/modules/bibliography/marcimport.php:422 #: admin/modules/membership/import.php:219 msgid "File To Import" msgstr "Berkas untuk di impor" #: admin/modules/bibliography/import.php:284 -#: admin/modules/bibliography/item_import.php:233 +#: admin/modules/bibliography/item_import.php:242 msgid "Number of Records To Import (0 for all records)" msgstr "Jumlah cantuman untuk di impor (0 untuk semua rekod)" #: admin/modules/bibliography/import.php:288 -#: admin/modules/bibliography/item_import.php:237 +#: admin/modules/bibliography/item_import.php:246 msgid "The first row is the columns names" msgstr "Baris pertama adalah nama kolom" #: admin/modules/bibliography/index.php:99 -#: admin/modules/membership/index.php:84 admin/modules/system/app_user.php:80 +#: admin/modules/membership/index.php:84 admin/modules/system/app_user.php:82 msgid "{imageFilename} successfully removed!" msgstr "{imageFilename} berhasil hapus!" #: admin/modules/bibliography/index.php:109 -#: admin/modules/bibliography/index.php:457 -#: admin/modules/system/app_user.php:102 +#: admin/modules/bibliography/index.php:465 +#: admin/modules/system/app_user.php:104 msgid "Invalid form submission token!" msgstr "Invalid form submission token!" @@ -1268,41 +1271,41 @@ msgstr "Ruas %s hanya menggunakan angka" msgid "Field %s is date format, empty not allowed" msgstr "Ruas %s adalah tanggal, tidak boleh kosong" -#: admin/modules/bibliography/index.php:235 +#: admin/modules/bibliography/index.php:242 #: admin/modules/membership/index.php:253 -#: admin/modules/membership/index.php:290 admin/modules/system/app_user.php:182 -#: admin/modules/system/app_user.php:205 +#: admin/modules/membership/index.php:290 admin/modules/system/app_user.php:186 +#: admin/modules/system/app_user.php:211 msgid "Image Uploaded Successfully" msgstr "Gambar Berhasil Diunggah" -#: admin/modules/bibliography/index.php:239 +#: admin/modules/bibliography/index.php:247 msgid "Image Uploaded Failed" msgstr "Unggah Gambar Gagal" -#: admin/modules/bibliography/index.php:292 +#: admin/modules/bibliography/index.php:300 msgid "Bibliography Data Successfully Updated" msgstr "Data bibliografi berhasil diperbaharui" -#: admin/modules/bibliography/index.php:322 +#: admin/modules/bibliography/index.php:330 msgid "" "Bibliography Data FAILED to Updated. Please Contact System Administrator" msgstr "Data bibliografi GAGAL diperbaharui. Hubungi Administrator Sistem" -#: admin/modules/bibliography/index.php:371 +#: admin/modules/bibliography/index.php:379 msgid "New Bibliography Data Successfully Saved" msgstr "Data baru bibliografi berhasil disimpan" -#: admin/modules/bibliography/index.php:394 +#: admin/modules/bibliography/index.php:402 msgid "Bibliography Data FAILED to Save. Please Contact System Administrator" msgstr "Data bibliografi GAGAL disimpan. Hubungi Administrator Sistem" -#: admin/modules/bibliography/index.php:405 +#: admin/modules/bibliography/index.php:413 #, php-format msgid "Item Data FAILED to Save. Insert batch item maximum %s copies" msgstr "" "Data Eksemplar GAGAL disimpan. Jumlah eksemplar massal maksimum %s salinan" -#: admin/modules/bibliography/index.php:536 +#: admin/modules/bibliography/index.php:544 #: admin/modules/master_file/author.php:166 #: admin/modules/master_file/coll_type.php:125 #: admin/modules/master_file/doc_language.php:130 @@ -1319,7 +1322,7 @@ msgstr "" msgid "Below data can not be deleted:" msgstr "Data berikut tidak bisa dihapus :" -#: admin/modules/bibliography/index.php:546 +#: admin/modules/bibliography/index.php:554 #: admin/modules/circulation/loan_rules.php:117 #: admin/modules/master_file/author.php:174 #: admin/modules/master_file/coll_type.php:130 @@ -1338,7 +1341,7 @@ msgstr "Data berikut tidak bisa dihapus :" #: admin/modules/master_file/topic.php:166 #: admin/modules/membership/index.php:368 #: admin/modules/membership/member_type.php:152 -#: admin/modules/system/app_user.php:246 admin/modules/system/backup.php:103 +#: admin/modules/system/app_user.php:252 admin/modules/system/backup.php:103 #: admin/modules/system/content.php:154 #: admin/modules/system/custom_field.php:150 #: admin/modules/system/holiday.php:160 admin/modules/system/module.php:127 @@ -1346,7 +1349,7 @@ msgstr "Data berikut tidak bisa dihapus :" msgid "All Data Successfully Deleted" msgstr "Semua Data Berhasil Dihapus" -#: admin/modules/bibliography/index.php:549 +#: admin/modules/bibliography/index.php:557 #: admin/modules/circulation/loan_rules.php:124 #: admin/modules/master_file/author.php:178 #: admin/modules/master_file/coll_type.php:133 @@ -1365,7 +1368,7 @@ msgstr "Semua Data Berhasil Dihapus" #: admin/modules/master_file/topic.php:169 #: admin/modules/membership/index.php:371 #: admin/modules/membership/member_type.php:160 -#: admin/modules/system/app_user.php:249 admin/modules/system/backup.php:106 +#: admin/modules/system/app_user.php:255 admin/modules/system/backup.php:106 #: admin/modules/system/content.php:157 #: admin/modules/system/custom_field.php:154 #: admin/modules/system/holiday.php:163 admin/modules/system/module.php:130 @@ -1375,37 +1378,37 @@ msgid "" "administrator" msgstr "Sebagian atau semua data GAGAL dihapus!\\nHubungi administrator sistem" -#: admin/modules/bibliography/index.php:562 +#: admin/modules/bibliography/index.php:570 msgid "Bibliographic" msgstr "Bibliografi" -#: admin/modules/bibliography/index.php:567 +#: admin/modules/bibliography/index.php:575 #: admin/modules/bibliography/submenu.php:28 msgid "Bibliographic List" msgstr "Daftar Bibliografi" -#: admin/modules/bibliography/index.php:569 +#: admin/modules/bibliography/index.php:577 #: admin/modules/bibliography/submenu.php:29 msgid "Add New Bibliography" msgstr "Tambah Bibliografi Baru" -#: admin/modules/bibliography/index.php:575 +#: admin/modules/bibliography/index.php:583 msgid "All Fields" msgstr "Semua Ruas" -#: admin/modules/bibliography/index.php:576 +#: admin/modules/bibliography/index.php:584 #: admin/modules/bibliography/marcsru.php:443 #: admin/modules/bibliography/z3950.php:293 #: admin/modules/bibliography/z3950sru.php:321 msgid "Title/Series Title" msgstr "Judul/Judul Seri" -#: admin/modules/bibliography/index.php:577 +#: admin/modules/bibliography/index.php:585 #: admin/modules/bibliography/pop_p2p.php:70 msgid "Topics" msgstr "Topik" -#: admin/modules/bibliography/index.php:578 +#: admin/modules/bibliography/index.php:586 #: admin/modules/bibliography/marcsru.php:444 #: admin/modules/bibliography/pop_p2p.php:54 #: admin/modules/bibliography/z3950.php:293 @@ -1413,12 +1416,12 @@ msgstr "Topik" msgid "Authors" msgstr "Pengarang" -#: admin/modules/bibliography/index.php:579 -#: admin/modules/bibliography/index.php:900 -#: admin/modules/bibliography/index.php:1210 -#: admin/modules/bibliography/index.php:1216 -#: admin/modules/bibliography/index.php:1236 -#: admin/modules/bibliography/index.php:1242 +#: admin/modules/bibliography/index.php:587 +#: admin/modules/bibliography/index.php:908 +#: admin/modules/bibliography/index.php:1218 +#: admin/modules/bibliography/index.php:1224 +#: admin/modules/bibliography/index.php:1244 +#: admin/modules/bibliography/index.php:1250 #: admin/modules/bibliography/marcsru.php:343 #: admin/modules/bibliography/marcsru.php:442 #: admin/modules/bibliography/pop_p2p.php:57 @@ -1427,7 +1430,7 @@ msgstr "Pengarang" #: admin/modules/bibliography/z3950sru.php:320 #: admin/modules/reporting/customs/titles_list.php:131 #: admin/modules/reporting/customs/titles_list.php:259 -#: admin/modules/serial_control/index.php:70 lib/contents/default.inc.php:165 +#: admin/modules/serial_control/index.php:70 #: template/akasia-dz/custom_frontpage_record.inc.php:7 #: template/akasia-dz/detail_template.php:87 #: template/akasia/custom_frontpage_record.inc.php:7 @@ -1445,8 +1448,8 @@ msgstr "Pengarang" msgid "ISBN/ISSN" msgstr "ISBN/ISSN" -#: admin/modules/bibliography/index.php:580 -#: admin/modules/bibliography/index.php:909 +#: admin/modules/bibliography/index.php:588 +#: admin/modules/bibliography/index.php:917 #: admin/modules/bibliography/pop_p2p.php:58 #: admin/modules/bibliography/z3950sru.php:214 #: admin/modules/master_file/publisher.php:57 @@ -1462,31 +1465,31 @@ msgstr "ISBN/ISSN" #: admin/modules/reporting/customs/pop_procurement_list.php:160 #: admin/modules/reporting/customs/titles_list.php:130 #: admin/modules/reporting/customs/titles_list.php:258 -#: lib/contents/default.inc.php:169 template/akasia-dz/detail_template.php:64 +#: template/akasia-dz/detail_template.php:64 #: template/akasia/detail_template.php:64 #: template/default/detail_template.php:46 #: template/lightweight/detail_template.php:64 msgid "Publisher" msgstr "Penerbit" -#: admin/modules/bibliography/index.php:585 +#: admin/modules/bibliography/index.php:593 msgid "Advanced Filter" msgstr "Pencarian Spesifik" -#: admin/modules/bibliography/index.php:588 -#: admin/modules/bibliography/index.php:1066 +#: admin/modules/bibliography/index.php:596 +#: admin/modules/bibliography/index.php:1074 msgid "Hide in OPAC" msgstr "Sembunyikan di OPAC" -#: admin/modules/bibliography/index.php:590 -#: admin/modules/bibliography/index.php:596 +#: admin/modules/bibliography/index.php:598 +#: admin/modules/bibliography/index.php:604 #: admin/modules/bibliography/p2p.php:312 #: admin/modules/circulation/loan_rules.php:201 #: admin/modules/circulation/loan_rules.php:206 -#: admin/modules/reporting/customs/item_titles_list.php:85 -#: admin/modules/reporting/customs/item_titles_list.php:97 -#: admin/modules/reporting/customs/item_titles_list.php:109 -#: admin/modules/reporting/customs/item_titles_list.php:121 +#: admin/modules/reporting/customs/item_titles_list.php:86 +#: admin/modules/reporting/customs/item_titles_list.php:98 +#: admin/modules/reporting/customs/item_titles_list.php:110 +#: admin/modules/reporting/customs/item_titles_list.php:122 #: admin/modules/reporting/customs/loan_by_class.php:69 #: admin/modules/reporting/customs/loan_by_class.php:90 #: admin/modules/reporting/customs/loan_by_class.php:101 @@ -1517,8 +1520,8 @@ msgstr "Sembunyikan di OPAC" msgid "ALL" msgstr "SEMUA" -#: admin/modules/bibliography/index.php:591 -#: admin/modules/bibliography/index.php:1064 +#: admin/modules/bibliography/index.php:599 +#: admin/modules/bibliography/index.php:1072 #: admin/modules/bibliography/print_settings.php:92 #: admin/modules/system/custom_field.php:232 template/default/tinfo.inc.php:52 #: template/default/tinfo.inc.php:103 template/default/tinfo.inc.php:119 @@ -1527,8 +1530,8 @@ msgstr "SEMUA" msgid "Show" msgstr "Tunjukan" -#: admin/modules/bibliography/index.php:592 -#: admin/modules/bibliography/index.php:1065 +#: admin/modules/bibliography/index.php:600 +#: admin/modules/bibliography/index.php:1073 #: admin/modules/bibliography/print_settings.php:91 #: admin/modules/system/custom_field.php:231 template/default/tinfo.inc.php:53 #: template/default/tinfo.inc.php:104 template/default/tinfo.inc.php:120 @@ -1537,26 +1540,26 @@ msgstr "Tunjukan" msgid "Hide" msgstr "Sembunyikan" -#: admin/modules/bibliography/index.php:594 -#: admin/modules/bibliography/index.php:1070 +#: admin/modules/bibliography/index.php:602 +#: admin/modules/bibliography/index.php:1078 msgid "Promote To Homepage" msgstr "Promosikan Ke Beranda" -#: admin/modules/bibliography/index.php:597 -#: admin/modules/bibliography/index.php:1068 +#: admin/modules/bibliography/index.php:605 +#: admin/modules/bibliography/index.php:1076 msgid "Don't Promote" msgstr "Jangan Promosikan" -#: admin/modules/bibliography/index.php:598 -#: admin/modules/bibliography/index.php:1069 +#: admin/modules/bibliography/index.php:606 +#: admin/modules/bibliography/index.php:1077 msgid "Promote" msgstr "Promosikan" -#: admin/modules/bibliography/index.php:607 +#: admin/modules/bibliography/index.php:615 msgid "Upload Selected Bibliographic data to Union Catalog Server*" msgstr "Unggah Data Bibliografi Terpilih ke Peladen Katalog Induk" -#: admin/modules/bibliography/index.php:626 +#: admin/modules/bibliography/index.php:634 #: admin/modules/reporting/customs/dl_detail.php:120 #: admin/modules/reporting/customs/dl_detail.php:182 #: admin/modules/system/custom_field.php:228 @@ -1564,19 +1567,19 @@ msgstr "Unggah Data Bibliografi Terpilih ke Peladen Katalog Induk" msgid "Date" msgstr "Date" -#: admin/modules/bibliography/index.php:627 +#: admin/modules/bibliography/index.php:635 msgid "User Name" msgstr "Nama Pengguna" -#: admin/modules/bibliography/index.php:628 +#: admin/modules/bibliography/index.php:636 msgid "Additional Information" msgstr "Informasi Tambahan" -#: admin/modules/bibliography/index.php:657 +#: admin/modules/bibliography/index.php:665 msgid "Biblio Log" msgstr "Catatan Biblio" -#: admin/modules/bibliography/index.php:685 +#: admin/modules/bibliography/index.php:693 #: admin/modules/bibliography/item.php:240 #: admin/modules/bibliography/pop_pattern.php:102 #: admin/modules/circulation/fines_list.php:152 @@ -1601,19 +1604,19 @@ msgstr "Catatan Biblio" #: admin/modules/membership/member_type.php:200 #: admin/modules/serial_control/serial_base_lib.inc.php:202 #: admin/modules/serial_control/subscription.php:163 -#: admin/modules/system/app_user.php:296 admin/modules/system/content.php:197 +#: admin/modules/system/app_user.php:302 admin/modules/system/content.php:197 #: admin/modules/system/custom_field.php:194 -#: admin/modules/system/holiday.php:196 admin/modules/system/module.php:167 +#: admin/modules/system/holiday.php:195 admin/modules/system/module.php:167 #: admin/modules/system/shortcut.php:129 #: admin/modules/system/user_group.php:207 msgid "Save" msgstr "Simpan" -#: admin/modules/bibliography/index.php:693 +#: admin/modules/bibliography/index.php:701 msgid "Log" msgstr "Catatan" -#: admin/modules/bibliography/index.php:714 +#: admin/modules/bibliography/index.php:722 #: admin/modules/bibliography/item.php:259 #: admin/modules/bibliography/pop_author_edit.php:78 #: admin/modules/circulation/fines_list.php:171 @@ -1637,15 +1640,15 @@ msgstr "Catatan" #: admin/modules/membership/index.php:431 #: admin/modules/membership/member_type.php:215 #: admin/modules/serial_control/subscription.php:178 -#: admin/modules/system/app_user.php:317 admin/modules/system/content.php:213 +#: admin/modules/system/app_user.php:323 admin/modules/system/content.php:213 #: admin/modules/system/custom_field.php:210 -#: admin/modules/system/holiday.php:211 admin/modules/system/module.php:182 +#: admin/modules/system/holiday.php:210 admin/modules/system/module.php:182 #: admin/modules/system/user_group.php:222 lib/contents/login.inc.php:224 #: lib/contents/newpass.inc.php:103 msgid "Update" msgstr "Perbaharui" -#: admin/modules/bibliography/index.php:734 +#: admin/modules/bibliography/index.php:742 msgid "" "Main title of collection. Separate child title with colon and pararel title " "with equal (=) sign." @@ -1653,15 +1656,15 @@ msgstr "" "Judul utama koleksi. Pisahkan anak judul dengan titik dua (:) dan judul " "paralel dengan tanda sama dengan (=)." -#: admin/modules/bibliography/index.php:738 +#: admin/modules/bibliography/index.php:746 msgid "Authors/Roles" msgstr "Pengarang/Peran" -#: admin/modules/bibliography/index.php:738 +#: admin/modules/bibliography/index.php:746 msgid "Add Author(s)" msgstr "Tambah Data Pengarang" -#: admin/modules/bibliography/index.php:740 +#: admin/modules/bibliography/index.php:748 #: admin/modules/reporting/customs/dl_detail.php:81 #: admin/modules/serial_control/index.php:69 #: lib/contents/clustering.inc.php:120 @@ -1671,7 +1674,7 @@ msgstr "Tambah Data Pengarang" msgid "Author(s)" msgstr "Pengarang" -#: admin/modules/bibliography/index.php:744 +#: admin/modules/bibliography/index.php:752 #: template/akasia-dz/detail_template.php:150 #: template/akasia/detail_template.php:150 #: template/default/detail_template.php:100 @@ -1679,7 +1682,7 @@ msgstr "Pengarang" msgid "Statement of Responsibility" msgstr "Pernyataan Tanggungjawab" -#: admin/modules/bibliography/index.php:744 +#: admin/modules/bibliography/index.php:752 msgid "" "Main source of information to show who has written, composed, illustrated, " "or in other ways contributed to the existence of the item." @@ -1687,7 +1690,7 @@ msgstr "" "Sumber utama informasi untuk memperlihatkan siapa yang menulis, menyusun, " "membuat ilustrasi, atau berkontribusi dengan cara apapun." -#: admin/modules/bibliography/index.php:748 +#: admin/modules/bibliography/index.php:756 #: admin/modules/bibliography/pop_p2p.php:56 lib/detail.inc.php:268 #: template/akasia-dz/custom_frontpage_record.inc.php:6 #: template/akasia-dz/detail_template.php:129 @@ -1700,11 +1703,11 @@ msgstr "" msgid "Edition" msgstr "Edisi" -#: admin/modules/bibliography/index.php:748 +#: admin/modules/bibliography/index.php:756 msgid "A version of publication having substantial changes or additions." msgstr "Versi publikasi yang memiliki perubahan atau penambahan vital." -#: admin/modules/bibliography/index.php:750 +#: admin/modules/bibliography/index.php:758 #: template/akasia-dz/detail_template.php:143 #: template/akasia/detail_template.php:143 #: template/default/detail_template.php:96 @@ -1712,7 +1715,7 @@ msgstr "Versi publikasi yang memiliki perubahan atau penambahan vital." msgid "Specific Detail Info" msgstr "Info Detail Spesifik" -#: admin/modules/bibliography/index.php:750 +#: admin/modules/bibliography/index.php:758 msgid "" "explain more details about an item e.g. scale within a map, running time in " "a movie dvd." @@ -1720,31 +1723,31 @@ msgstr "" "menjelaskan detail lebih mendalam tentang suatu eksemplar, misal skala peta, " "waktu putar DVD." -#: admin/modules/bibliography/index.php:760 +#: admin/modules/bibliography/index.php:768 msgid "Choose pattern" msgstr "Pilih pola" -#: admin/modules/bibliography/index.php:775 +#: admin/modules/bibliography/index.php:783 msgid "Total item(s)" msgstr "Total item" -#: admin/modules/bibliography/index.php:777 +#: admin/modules/bibliography/index.php:785 #: admin/modules/reporting/customs/procurement_report.php:67 msgid "Options" msgstr "Pilihan" -#: admin/modules/bibliography/index.php:778 +#: admin/modules/bibliography/index.php:786 #: admin/modules/master_file/item_code_pattern.php:87 msgid "Add new pattern" msgstr "Tambah pola baru" -#: admin/modules/bibliography/index.php:778 +#: admin/modules/bibliography/index.php:786 #: admin/modules/bibliography/pop_pattern.php:125 msgid "Add New Pattern" msgstr "Tambah Pola Baru" -#: admin/modules/bibliography/index.php:783 -#: admin/modules/bibliography/index.php:787 +#: admin/modules/bibliography/index.php:791 +#: admin/modules/bibliography/index.php:795 #: admin/modules/bibliography/item.php:309 #: admin/modules/bibliography/item.php:408 #: admin/modules/bibliography/item.php:417 @@ -1760,27 +1763,27 @@ msgstr "Tambah Pola Baru" #: admin/modules/master_file/location.php:137 #: admin/modules/master_file/location.php:149 #: admin/modules/master_file/submenu.php:35 -#: admin/modules/reporting/customs/item_titles_list.php:117 +#: admin/modules/reporting/customs/item_titles_list.php:118 #: admin/modules/reporting/customs/loan_history.php:113 #: admin/modules/reporting/customs/pop_procurement_list.php:83 #: admin/modules/reporting/customs/pop_procurement_list.php:167 #: admin/modules/stock_take/init.php:209 #: admin/modules/stock_take/lost_item_list.php:110 -#: admin/modules/system/sys_log.php:109 lib/contents/default.inc.php:168 +#: admin/modules/system/sys_log.php:109 #: template/akasia/partials/advsearch.php:65 #: template/default/parts/_modal_advanced.php:63 #: template/lightweight/partials/advsearch.php:65 msgid "Location" msgstr "Lokasi" -#: admin/modules/bibliography/index.php:791 +#: admin/modules/bibliography/index.php:799 #: admin/modules/bibliography/item.php:311 #: admin/modules/stock_take/init.php:211 msgid "Shelf Location" msgstr "Lokasi Rak" -#: admin/modules/bibliography/index.php:796 -#: admin/modules/bibliography/index.php:800 +#: admin/modules/bibliography/index.php:804 +#: admin/modules/bibliography/index.php:808 #: admin/modules/bibliography/item.php:319 #: admin/modules/bibliography/item.php:407 #: admin/modules/bibliography/item.php:416 @@ -1804,8 +1807,9 @@ msgstr "Lokasi Rak" #: admin/modules/master_file/submenu.php:39 #: admin/modules/reporting/customs/class_recap.php:72 #: admin/modules/reporting/customs/class_recap.php:149 -#: admin/modules/reporting/customs/item_titles_list.php:93 -#: admin/modules/reporting/customs/item_titles_list.php:159 +#: admin/modules/reporting/customs/item_titles_list.php:94 +#: admin/modules/reporting/customs/item_titles_list.php:163 +#: admin/modules/reporting/customs/item_titles_list.php:290 #: admin/modules/reporting/customs/loan_by_class.php:86 #: admin/modules/reporting/customs/pop_procurement_list.php:69 #: admin/modules/reporting/customs/pop_procurement_list.php:121 @@ -1815,14 +1819,13 @@ msgstr "Lokasi Rak" #: admin/modules/stock_take/lost_item_list.php:98 #: admin/modules/stock_take/lost_item_list.php:143 #: admin/modules/stock_take/st_report.php:174 -#: lib/contents/clustering.inc.php:79 lib/contents/default.inc.php:167 -#: template/akasia/partials/advsearch.php:56 +#: lib/contents/clustering.inc.php:79 template/akasia/partials/advsearch.php:56 #: template/default/parts/_modal_advanced.php:56 #: template/lightweight/partials/advsearch.php:56 msgid "Collection Type" msgstr "Tipe Koleksi" -#: admin/modules/bibliography/index.php:809 +#: admin/modules/bibliography/index.php:817 #: admin/modules/bibliography/item.php:327 #: admin/modules/master_file/item_status.php:61 #: admin/modules/master_file/item_status.php:99 @@ -1835,58 +1838,59 @@ msgstr "Tipe Koleksi" #: admin/modules/master_file/item_status.php:180 #: admin/modules/master_file/item_status.php:184 #: admin/modules/master_file/submenu.php:38 -#: admin/modules/reporting/customs/item_titles_list.php:105 -#: admin/modules/reporting/customs/item_titles_list.php:160 +#: admin/modules/reporting/customs/item_titles_list.php:106 +#: admin/modules/reporting/customs/item_titles_list.php:164 +#: admin/modules/reporting/customs/item_titles_list.php:291 msgid "Item Status" msgstr "Status Eksemplar" -#: admin/modules/bibliography/index.php:813 +#: admin/modules/bibliography/index.php:821 #: admin/modules/bibliography/item.php:343 msgid "Buy" msgstr "Beli" -#: admin/modules/bibliography/index.php:814 +#: admin/modules/bibliography/index.php:822 #: admin/modules/bibliography/item.php:344 msgid "Prize/Grant" msgstr "Hadiah/Hibah" -#: admin/modules/bibliography/index.php:815 +#: admin/modules/bibliography/index.php:823 #: admin/modules/bibliography/item.php:345 msgid "Source" msgstr "Sumber Perolehan" -#: admin/modules/bibliography/index.php:819 +#: admin/modules/bibliography/index.php:827 #: admin/modules/bibliography/item.php:331 msgid "Order Date" msgstr "Tanggal Pemesanan" -#: admin/modules/bibliography/index.php:823 +#: admin/modules/bibliography/index.php:831 #: admin/modules/bibliography/item.php:333 msgid "Receiving Date" msgstr "Tanggal Penerimaan" -#: admin/modules/bibliography/index.php:827 +#: admin/modules/bibliography/index.php:835 #: admin/modules/bibliography/item.php:329 msgid "Order Number" msgstr "No. Pemesanan" -#: admin/modules/bibliography/index.php:831 +#: admin/modules/bibliography/index.php:839 #: admin/modules/bibliography/item.php:347 msgid "Invoice" msgstr "Faktur" -#: admin/modules/bibliography/index.php:835 +#: admin/modules/bibliography/index.php:843 #: admin/modules/bibliography/item.php:349 msgid "Invoice Date" msgstr "Tanggal Faktur" -#: admin/modules/bibliography/index.php:840 -#: admin/modules/bibliography/index.php:890 +#: admin/modules/bibliography/index.php:848 +#: admin/modules/bibliography/index.php:898 #: admin/modules/bibliography/item.php:337 msgid "Not Applicable" msgstr "Tidak Digunakan" -#: admin/modules/bibliography/index.php:844 +#: admin/modules/bibliography/index.php:852 #: admin/modules/bibliography/item.php:341 #: admin/modules/master_file/submenu.php:32 #: admin/modules/master_file/supplier.php:56 @@ -1900,25 +1904,25 @@ msgstr "Tidak Digunakan" msgid "Supplier" msgstr "Agen" -#: admin/modules/bibliography/index.php:848 +#: admin/modules/bibliography/index.php:856 #: admin/modules/bibliography/item.php:357 #: admin/modules/reporting/customs/pop_procurement_list.php:168 msgid "Price" msgstr "Harga" -#: admin/modules/bibliography/index.php:853 +#: admin/modules/bibliography/index.php:861 msgid "Item(s) code batch generator" msgstr "Pembuat nomor eksemplar" -#: admin/modules/bibliography/index.php:857 +#: admin/modules/bibliography/index.php:865 msgid "Add New Items" msgstr "Tambah Eksemplar Baru" -#: admin/modules/bibliography/index.php:859 +#: admin/modules/bibliography/index.php:867 msgid "Item(s) Data" msgstr "Data Koleksi" -#: admin/modules/bibliography/index.php:868 +#: admin/modules/bibliography/index.php:876 #: admin/modules/bibliography/marcsru.php:343 #: admin/modules/bibliography/pop_p2p.php:61 #: admin/modules/bibliography/z3950sru.php:214 @@ -1928,38 +1932,37 @@ msgstr "Data Koleksi" #: admin/modules/master_file/submenu.php:27 #: admin/modules/reporting/customs/class_recap.php:71 #: admin/modules/reporting/customs/class_recap.php:101 -#: admin/modules/reporting/customs/item_titles_list.php:82 +#: admin/modules/reporting/customs/item_titles_list.php:83 #: admin/modules/reporting/customs/titles_list.php:83 #: admin/modules/serial_control/subscription.php:199 #: admin/modules/stock_take/init.php:193 #: admin/modules/stock_take/lost_item_list.php:86 #: admin/modules/stock_take/lost_item_list.php:141 -#: lib/contents/clustering.inc.php:60 lib/contents/default.inc.php:166 -#: template/akasia/partials/advsearch.php:76 +#: lib/contents/clustering.inc.php:60 template/akasia/partials/advsearch.php:76 #: template/default/parts/_modal_advanced.php:72 #: template/lightweight/partials/advsearch.php:76 msgid "GMD" msgstr "GMD" -#: admin/modules/bibliography/index.php:868 +#: admin/modules/bibliography/index.php:876 msgid "General material designation. The physical form of publication." msgstr "Tujuan utama bentuk. Bentuk fisik suatu publikasi." -#: admin/modules/bibliography/index.php:875 +#: admin/modules/bibliography/index.php:883 msgid "Not set" msgstr "Belum ditentukan" -#: admin/modules/bibliography/index.php:880 -#: admin/modules/bibliography/index.php:882 +#: admin/modules/bibliography/index.php:888 +#: admin/modules/bibliography/index.php:890 #: admin/modules/master_file/rda_cmc.php:139 msgid "RDA " msgstr "RDA " -#: admin/modules/bibliography/index.php:896 +#: admin/modules/bibliography/index.php:904 msgid "Use this for Serial publication" msgstr "Gunakan untuk koleksi terbitan berseri" -#: admin/modules/bibliography/index.php:898 +#: admin/modules/bibliography/index.php:906 #: admin/modules/master_file/frequency.php:55 #: admin/modules/master_file/frequency.php:76 #: admin/modules/master_file/frequency.php:78 @@ -1976,28 +1979,28 @@ msgstr "Gunakan untuk koleksi terbitan berseri" msgid "Frequency" msgstr "Kala Terbit" -#: admin/modules/bibliography/index.php:900 +#: admin/modules/bibliography/index.php:908 msgid "Unique publishing number for each title of publication." msgstr "Nomor publikasi yang unik dari setiap judul cetakan." -#: admin/modules/bibliography/index.php:911 +#: admin/modules/bibliography/index.php:919 #: admin/modules/bibliography/z3950sru.php:214 #: admin/modules/reporting/customs/pop_procurement_list.php:161 msgid "Publishing Year" msgstr "Tahun Terbit" -#: admin/modules/bibliography/index.php:911 +#: admin/modules/bibliography/index.php:919 msgid "Year of publication" msgstr "Tahun Terbit" -#: admin/modules/bibliography/index.php:920 +#: admin/modules/bibliography/index.php:928 #: admin/modules/reporting/customs/pop_procurement_list.php:162 #: admin/modules/reporting/customs/titles_list.php:129 #: admin/modules/reporting/customs/titles_list.php:257 msgid "Publishing Place" msgstr "Tempat Terbit" -#: admin/modules/bibliography/index.php:922 +#: admin/modules/bibliography/index.php:930 #: admin/modules/bibliography/pop_p2p.php:59 #: admin/modules/bibliography/z3950sru.php:214 #: template/akasia-dz/custom_frontpage_record.inc.php:8 @@ -2011,13 +2014,13 @@ msgstr "Tempat Terbit" msgid "Collation" msgstr "Deskripsi Fisik" -#: admin/modules/bibliography/index.php:922 +#: admin/modules/bibliography/index.php:930 msgid "" "Physical description of a publication e.g. publication length, width, page " "numbers, etc." msgstr "Deskripsi fisik publikasi, seperti lebar, tinggi, jumlah halaman, dll." -#: admin/modules/bibliography/index.php:924 +#: admin/modules/bibliography/index.php:932 #: template/akasia-dz/custom_frontpage_record.inc.php:9 #: template/akasia-dz/detail_template.php:50 #: template/akasia/custom_frontpage_record.inc.php:9 @@ -2029,7 +2032,7 @@ msgstr "Deskripsi fisik publikasi, seperti lebar, tinggi, jumlah halaman, dll." msgid "Series Title" msgstr "Judul Seri" -#: admin/modules/bibliography/index.php:930 +#: admin/modules/bibliography/index.php:938 #: admin/modules/bibliography/item.php:409 #: admin/modules/bibliography/item.php:418 #: admin/modules/bibliography/pop_p2p.php:62 @@ -2037,7 +2040,7 @@ msgstr "Judul Seri" #: admin/modules/master_file/pop_vocabolary_control.php:281 #: admin/modules/reporting/customs/class_recap.php:70 #: admin/modules/reporting/customs/class_recap.php:89 -#: admin/modules/reporting/customs/item_titles_list.php:78 +#: admin/modules/reporting/customs/item_titles_list.php:79 #: admin/modules/reporting/customs/loan_by_class.php:67 #: admin/modules/reporting/customs/loan_by_class.php:151 #: admin/modules/reporting/customs/loan_by_class.php:152 @@ -2059,19 +2062,19 @@ msgstr "Judul Seri" msgid "Classification" msgstr "Klasifikasi" -#: admin/modules/bibliography/index.php:932 +#: admin/modules/bibliography/index.php:940 msgid "Sets of ID that put in the book spine." msgstr "Kumpulan identitas yang ditempel pada punggung buku." -#: admin/modules/bibliography/index.php:935 +#: admin/modules/bibliography/index.php:943 msgid "Subjects/Topics" msgstr "Subjek/Topik" -#: admin/modules/bibliography/index.php:935 +#: admin/modules/bibliography/index.php:943 msgid "Add Subject(s)" msgstr "Tambah Subjek" -#: admin/modules/bibliography/index.php:937 +#: admin/modules/bibliography/index.php:945 #: admin/modules/serial_control/index.php:68 lib/contents/clustering.inc.php:98 #: template/akasia-dz/detail_template.php:136 #: template/akasia/detail_template.php:136 @@ -2083,7 +2086,7 @@ msgstr "Tambah Subjek" msgid "Subject(s)" msgstr "Subjek" -#: admin/modules/bibliography/index.php:945 +#: admin/modules/bibliography/index.php:953 #: admin/modules/bibliography/pop_p2p.php:60 #: admin/modules/master_file/doc_language.php:202 #: admin/modules/master_file/doc_language.php:218 @@ -2103,163 +2106,163 @@ msgstr "Subjek" msgid "Language" msgstr "Bahasa" -#: admin/modules/bibliography/index.php:945 +#: admin/modules/bibliography/index.php:953 msgid "Language use by publication." msgstr "Bahasa publikasi." -#: admin/modules/bibliography/index.php:947 +#: admin/modules/bibliography/index.php:955 msgid "Abstract/Notes" msgstr "Abstrak/Catatan" -#: admin/modules/bibliography/index.php:947 +#: admin/modules/bibliography/index.php:955 msgid "Insert here any abstract or notes from the publication." msgstr "Masukkan catatan atau abstrak publikasi, di sini." -#: admin/modules/bibliography/index.php:957 +#: admin/modules/bibliography/index.php:965 #: admin/modules/membership/index.php:564 msgid "Click to enlarge preview" msgstr "Klik untuk memperbesar" -#: admin/modules/bibliography/index.php:960 -#: admin/modules/membership/index.php:568 admin/modules/system/index.php:261 +#: admin/modules/bibliography/index.php:968 +#: admin/modules/membership/index.php:568 admin/modules/system/index.php:267 msgid "Remove Image" msgstr "Hapus Gambar" -#: admin/modules/bibliography/index.php:968 +#: admin/modules/bibliography/index.php:976 #: admin/modules/stock_take/st_upload.php:137 -#: admin/modules/system/index.php:265 +#: admin/modules/system/index.php:271 msgid "Choose file" msgstr "Pilih berkas" -#: admin/modules/bibliography/index.php:970 +#: admin/modules/bibliography/index.php:978 msgid "Or download from url" msgstr "Atau unduh dari url" -#: admin/modules/bibliography/index.php:974 admin/modules/system/backup.php:184 +#: admin/modules/bibliography/index.php:982 admin/modules/system/backup.php:176 msgid "Download" msgstr "Unduh" -#: admin/modules/bibliography/index.php:975 +#: admin/modules/bibliography/index.php:983 msgid "Trying search in DuckduckGo" msgstr "Gunakan Layanan DuckduckGo" -#: admin/modules/bibliography/index.php:987 +#: admin/modules/bibliography/index.php:995 msgid "or scan a cover" msgstr "atau pindai sampul" -#: admin/modules/bibliography/index.php:991 +#: admin/modules/bibliography/index.php:999 msgid "Show scan dialog" msgstr "Tunjukkan dialog pindai" -#: admin/modules/bibliography/index.php:992 -#: admin/modules/membership/index.php:609 admin/modules/system/app_user.php:374 +#: admin/modules/bibliography/index.php:1000 +#: admin/modules/membership/index.php:609 admin/modules/system/app_user.php:380 msgid "Reset" msgstr "Setel ulang" -#: admin/modules/bibliography/index.php:994 +#: admin/modules/bibliography/index.php:1002 msgid "Scan a cover" msgstr "Pindai sampul" -#: admin/modules/bibliography/index.php:995 +#: admin/modules/bibliography/index.php:1003 msgid "Format:" msgstr "Format:" -#: admin/modules/bibliography/index.php:997 +#: admin/modules/bibliography/index.php:1005 msgid "Scan" msgstr "Pindai" -#: admin/modules/bibliography/index.php:998 +#: admin/modules/bibliography/index.php:1006 msgid "Click to show or hide options" msgstr "Klik untuk muncul atau sembunyi pilihan" -#: admin/modules/bibliography/index.php:1000 +#: admin/modules/bibliography/index.php:1008 msgid "History index:" msgstr "Indeks Sejarah:" -#: admin/modules/bibliography/index.php:1000 +#: admin/modules/bibliography/index.php:1008 msgid "Recall" msgstr "Memanggil kembali" -#: admin/modules/bibliography/index.php:1001 +#: admin/modules/bibliography/index.php:1009 msgid "Host:" msgstr "Host:" -#: admin/modules/bibliography/index.php:1001 +#: admin/modules/bibliography/index.php:1009 msgid "Get machine" msgstr "Panggil mesin" -#: admin/modules/bibliography/index.php:1002 +#: admin/modules/bibliography/index.php:1010 msgid "Scanner:" msgstr "Pemindai:" -#: admin/modules/bibliography/index.php:1002 +#: admin/modules/bibliography/index.php:1010 msgid "Default" msgstr "Baku" -#: admin/modules/bibliography/index.php:1003 +#: admin/modules/bibliography/index.php:1011 msgid "Resolution" msgstr "Resolusi" -#: admin/modules/bibliography/index.php:1003 +#: admin/modules/bibliography/index.php:1011 msgid "Horizontal:" msgstr "Horisontal:" -#: admin/modules/bibliography/index.php:1003 +#: admin/modules/bibliography/index.php:1011 msgid "Vertical:" msgstr "Vertikal:" -#: admin/modules/bibliography/index.php:1004 -#: admin/modules/membership/index.php:606 admin/modules/system/app_user.php:371 +#: admin/modules/bibliography/index.php:1012 +#: admin/modules/membership/index.php:606 admin/modules/system/app_user.php:377 msgid "Capture" msgstr "Ambil Gambar" -#: admin/modules/bibliography/index.php:1004 +#: admin/modules/bibliography/index.php:1012 msgid "Width:" msgstr "Lebar:" -#: admin/modules/bibliography/index.php:1004 +#: admin/modules/bibliography/index.php:1012 msgid "Height:" msgstr "Tinggi:" -#: admin/modules/bibliography/index.php:1005 +#: admin/modules/bibliography/index.php:1013 msgid "Result" msgstr "Hasil" -#: admin/modules/bibliography/index.php:1005 +#: admin/modules/bibliography/index.php:1013 msgid "Max Width:" msgstr "Lebar Maksimal:" -#: admin/modules/bibliography/index.php:1005 +#: admin/modules/bibliography/index.php:1013 msgid "Max Height:" msgstr "Tinggi Maksimal:" -#: admin/modules/bibliography/index.php:1006 +#: admin/modules/bibliography/index.php:1014 msgid "Scan result" msgstr "Hasil pindai" -#: admin/modules/bibliography/index.php:1007 +#: admin/modules/bibliography/index.php:1015 #: admin/modules/bibliography/pop_pattern.php:128 msgid "Preview" msgstr "Pra-tinjau" -#: admin/modules/bibliography/index.php:1007 +#: admin/modules/bibliography/index.php:1015 msgid "Rotate Left" msgstr "Putar ke kiri" -#: admin/modules/bibliography/index.php:1007 +#: admin/modules/bibliography/index.php:1015 msgid "Rotate Right" msgstr "Putar ke kanan" -#: admin/modules/bibliography/index.php:1011 +#: admin/modules/bibliography/index.php:1019 msgid "Image" msgstr "Gambar Sampul" -#: admin/modules/bibliography/index.php:1015 +#: admin/modules/bibliography/index.php:1023 msgid "Add Attachment" msgstr "Tambah Lampiran" -#: admin/modules/bibliography/index.php:1017 -#: admin/modules/bibliography/pop_attach.php:258 +#: admin/modules/bibliography/index.php:1025 +#: admin/modules/bibliography/pop_attach.php:267 #: admin/modules/master_file/label.php:227 #: admin/modules/master_file/label.php:232 #: template/akasia-dz/detail_template.php:170 @@ -2269,23 +2272,23 @@ msgstr "Tambah Lampiran" msgid "File Attachment" msgstr "Lampiran Berkas" -#: admin/modules/bibliography/index.php:1020 +#: admin/modules/bibliography/index.php:1028 msgid "Biblio Relation" msgstr "Relasi biblio" -#: admin/modules/bibliography/index.php:1020 +#: admin/modules/bibliography/index.php:1028 msgid "Add Relation" msgstr "Tambah Relasi" -#: admin/modules/bibliography/index.php:1022 +#: admin/modules/bibliography/index.php:1030 msgid "Related Biblio Data" msgstr "Data biblio terkait" -#: admin/modules/bibliography/index.php:1104 +#: admin/modules/bibliography/index.php:1112 msgid "You are going to edit biblio data" msgstr "Anda akan mengubah data biblio" -#: admin/modules/bibliography/index.php:1104 +#: admin/modules/bibliography/index.php:1112 #: admin/modules/bibliography/item.php:362 #: admin/modules/bibliography/item.php:410 #: admin/modules/bibliography/item.php:419 @@ -2302,33 +2305,33 @@ msgstr "Anda akan mengubah data biblio" msgid "Last Updated" msgstr "Terakhir diubah" -#: admin/modules/bibliography/index.php:1158 +#: admin/modules/bibliography/index.php:1166 msgid "Current url is not valid or your internet is down." msgstr "URL ini tidak tersedia atau koneksi internet Anda terputus." -#: admin/modules/bibliography/index.php:1211 -#: admin/modules/bibliography/index.php:1217 -#: admin/modules/bibliography/index.php:1237 -#: admin/modules/bibliography/index.php:1243 +#: admin/modules/bibliography/index.php:1219 +#: admin/modules/bibliography/index.php:1225 +#: admin/modules/bibliography/index.php:1245 +#: admin/modules/bibliography/index.php:1251 #: admin/modules/stock_take/st_report.php:84 #: admin/modules/stock_take/st_report.php:88 template/default/tinfo.inc.php:78 msgid "None" msgstr "Tidak Ada" -#: admin/modules/bibliography/index.php:1211 -#: admin/modules/bibliography/index.php:1217 -#: admin/modules/bibliography/index.php:1237 -#: admin/modules/bibliography/index.php:1243 +#: admin/modules/bibliography/index.php:1219 +#: admin/modules/bibliography/index.php:1225 +#: admin/modules/bibliography/index.php:1245 +#: admin/modules/bibliography/index.php:1251 #: admin/modules/bibliography/printed_card.php:212 #: admin/modules/reporting/customs/titles_list.php:128 #: admin/modules/reporting/customs/titles_list.php:256 msgid "Copies" msgstr "Salin" -#: admin/modules/bibliography/index.php:1212 -#: admin/modules/bibliography/index.php:1218 -#: admin/modules/bibliography/index.php:1238 -#: admin/modules/bibliography/index.php:1244 +#: admin/modules/bibliography/index.php:1220 +#: admin/modules/bibliography/index.php:1226 +#: admin/modules/bibliography/index.php:1246 +#: admin/modules/bibliography/index.php:1252 #: admin/modules/circulation/loan_rules.php:224 #: admin/modules/circulation/loan_rules.php:245 #: admin/modules/circulation/loan_rules.php:252 @@ -2374,8 +2377,8 @@ msgstr "Salin" #: admin/modules/master_file/topic.php:260 #: admin/modules/master_file/topic.php:286 #: admin/modules/master_file/topic.php:292 -#: admin/modules/system/app_user.php:410 admin/modules/system/app_user.php:439 -#: admin/modules/system/app_user.php:446 +#: admin/modules/system/app_user.php:416 admin/modules/system/app_user.php:445 +#: admin/modules/system/app_user.php:452 #: admin/modules/system/user_group.php:244 #: admin/modules/system/user_group.php:256 msgid "Last Update" @@ -2445,7 +2448,7 @@ msgstr "Cetak Barkod untuk Data Terpilih" #: admin/modules/bibliography/item_barcode_generator.php:219 msgid "Change print barcode settings" -msgstr "Ubah setelan cetak barkod" +msgstr "Ubah setelan cetak Kode batang" #: admin/modules/bibliography/item_export.php:146 msgid "There is no record in item database yet, Export FAILED!" @@ -2463,11 +2466,11 @@ msgstr "Ekspor data eksemplar ke dalam berkas CSV" msgid "File type not allowed or the size is more than" msgstr "Tipe berkas tidak diizinkan atau ukurannya melebih ketentuan" -#: admin/modules/bibliography/item_import.php:197 +#: admin/modules/bibliography/item_import.php:206 msgid "Item Import tool" msgstr "Perangkat Impor Eksemplar" -#: admin/modules/bibliography/item_import.php:200 +#: admin/modules/bibliography/item_import.php:209 msgid "Import for item data from CSV file" msgstr "Impor data eksemplar dari data CSV" @@ -2501,7 +2504,7 @@ msgstr "Impor data eksemplar dari data CSV" #: admin/modules/reporting/customs/dl_detail.php:42 #: admin/modules/reporting/customs/due_date_warning.php:41 #: admin/modules/reporting/customs/fines_report.php:41 -#: admin/modules/reporting/customs/item_titles_list.php:41 +#: admin/modules/reporting/customs/item_titles_list.php:42 #: admin/modules/reporting/customs/item_usage.php:41 #: admin/modules/reporting/customs/loan_by_class.php:42 #: admin/modules/reporting/customs/loan_history.php:41 @@ -2770,88 +2773,92 @@ msgstr "" "Maaf, dari %s tidak ada hasil ATAU kemungkinan hasil dan detail XML " "dinonaktifkan." -#: admin/modules/bibliography/pop_attach.php:99 +#: admin/modules/bibliography/pop_attach.php:101 msgid "Upload FAILED! Forbidden file type or file size too big!" msgstr "Unggah GAGAL! Jenis berkas terlarang atau ukuran terlalu besar!" -#: admin/modules/bibliography/pop_attach.php:149 +#: admin/modules/bibliography/pop_attach.php:156 msgid "File Attachment data updated!" msgstr "Data berkas lampiran berhasil diperbarui!" -#: admin/modules/bibliography/pop_attach.php:154 +#: admin/modules/bibliography/pop_attach.php:161 msgid "File Attachment data FAILED to update!" msgstr "Data berkas lampiran GAGAL diperbarui!" -#: admin/modules/bibliography/pop_attach.php:158 -#: admin/modules/bibliography/pop_attach.php:173 +#: admin/modules/bibliography/pop_attach.php:165 +#: admin/modules/bibliography/pop_attach.php:180 msgid "File Attachment uploaded succesfully!" msgstr "Berkas Lampiran berhasil diunggah!" -#: admin/modules/bibliography/pop_attach.php:163 +#: admin/modules/bibliography/pop_attach.php:170 msgid "File Attachment data FAILED to save!" msgstr "Berkas Lampiran GAGAL disimpan!" -#: admin/modules/bibliography/pop_attach.php:183 +#: admin/modules/bibliography/pop_attach.php:190 msgid "Upload Now" msgstr "Unggah Sekarang" -#: admin/modules/bibliography/pop_attach.php:213 +#: admin/modules/bibliography/pop_attach.php:220 msgid "Repository ROOT" msgstr "Repositori ROOT" -#: admin/modules/bibliography/pop_attach.php:223 +#: admin/modules/bibliography/pop_attach.php:230 msgid "Repo. Directory" msgstr "Direktori Repositori" -#: admin/modules/bibliography/pop_attach.php:234 +#: admin/modules/bibliography/pop_attach.php:241 msgid "File To Attach" msgstr "Berkas untuk dilampirkan" -#: admin/modules/bibliography/pop_attach.php:237 +#: admin/modules/bibliography/pop_attach.php:244 msgid "URL" msgstr "URL" -#: admin/modules/bibliography/pop_attach.php:240 +#: admin/modules/bibliography/pop_attach.php:247 msgid "Work for embedded link or video attachment" msgstr "Digunakan bersama tempelan pranala atau lampiran video" -#: admin/modules/bibliography/pop_attach.php:241 +#: admin/modules/bibliography/pop_attach.php:248 msgid "Link" msgstr "Pranala" -#: admin/modules/bibliography/pop_attach.php:241 +#: admin/modules/bibliography/pop_attach.php:248 msgid "Popup" msgstr "Pop-up" -#: admin/modules/bibliography/pop_attach.php:241 +#: admin/modules/bibliography/pop_attach.php:248 msgid "Embed" msgstr "Tempel" -#: admin/modules/bibliography/pop_attach.php:242 +#: admin/modules/bibliography/pop_attach.php:249 msgid "Placement" msgstr "Penempatan" -#: admin/modules/bibliography/pop_attach.php:245 +#: admin/modules/bibliography/pop_attach.php:252 #: admin/modules/reporting/customs/member_fines_list.php:188 #: admin/modules/reporting/customs/procurement_report.php:125 msgid "Description" msgstr "Deskripsi" -#: admin/modules/bibliography/pop_attach.php:247 +#: admin/modules/bibliography/pop_attach.php:254 +msgid "File Password" +msgstr "Kata sandi Berkas" + +#: admin/modules/bibliography/pop_attach.php:256 msgid "Public" msgstr "Publik" -#: admin/modules/bibliography/pop_attach.php:248 +#: admin/modules/bibliography/pop_attach.php:257 msgid "Private" msgstr "Tertutup" -#: admin/modules/bibliography/pop_attach.php:249 +#: admin/modules/bibliography/pop_attach.php:258 #: admin/modules/reporting/customs/dl_counter.php:113 #: admin/modules/reporting/customs/dl_counter.php:200 msgid "Access" msgstr "Akses" -#: admin/modules/bibliography/pop_attach.php:256 +#: admin/modules/bibliography/pop_attach.php:265 msgid "Access Limit by Member Type" msgstr "Pembatasan Akses berdasarkan Tipe Keanggotaan" @@ -2987,7 +2994,8 @@ msgid "Settings saved" msgstr "Setelan tersimpan" #: admin/modules/bibliography/print_settings.php:78 -#: admin/modules/system/holiday.php:334 admin/modules/system/index.php:237 +#: admin/modules/system/envsetting.php:113 admin/modules/system/holiday.php:367 +#: admin/modules/system/index.php:243 admin/modules/system/mailsetting.php:169 #: admin/modules/system/membercard_theme.php:107 #: admin/modules/system/theme.php:138 admin/modules/system/ucsetting.php:76 msgid "Save Settings" @@ -3481,7 +3489,7 @@ msgstr "Eksemplar {itemCode} berhasi dikembalikan pada {returnDate}" #: admin/modules/reporting/customs/overdued_list.php:75 #: admin/modules/reporting/customs/reserve_list.php:69 #: admin/modules/reporting/customs/reserve_list.php:114 -#: files/membercard/old/membercard.php:300 lib/contents/member.inc.php:243 +#: files/membercard/old/membercard.php:300 lib/contents/member.inc.php:248 msgid "Member Name" msgstr "Nama Anggota" @@ -3536,7 +3544,7 @@ msgid "Are you sure want to finish current transaction?" msgstr "Tutup/Selesaikan Transaksi?" #: admin/modules/circulation/circulation_action.php:510 -#: lib/contents/member.inc.php:247 +#: lib/contents/member.inc.php:252 msgid "Member Email" msgstr "Surel Anggota" @@ -3556,12 +3564,12 @@ msgstr "Surel Anggota" #: admin/modules/membership/member_type.php:172 #: admin/modules/membership/submenu.php:29 #: admin/modules/reporting/customs/visitor_report.php:101 -#: lib/contents/member.inc.php:248 +#: lib/contents/member.inc.php:253 msgid "Member Type" msgstr "Tipe Keanggotaan" #: admin/modules/circulation/circulation_action.php:514 -#: admin/modules/membership/index.php:479 lib/contents/member.inc.php:251 +#: admin/modules/membership/index.php:479 lib/contents/member.inc.php:256 msgid "Register Date" msgstr "Tanggal Registrasi" @@ -3573,7 +3581,7 @@ msgstr "Masa Keanggotaan sudah habis" #: admin/modules/circulation/circulation_action.php:520 #: admin/modules/membership/index.php:482 #: admin/modules/membership/index.php:487 -#: files/membercard/old/membercard.php:353 lib/contents/member.inc.php:252 +#: files/membercard/old/membercard.php:353 lib/contents/member.inc.php:257 msgid "Expiry Date" msgstr "Berlaku Hingga" @@ -3598,6 +3606,7 @@ msgstr "Reservasi" #: admin/modules/circulation/circulation_action.php:564 #: admin/modules/circulation/circulation_action.php:566 +#: admin/modules/reporting/customs/overdued_list.php:209 msgid "Fines" msgstr "Denda" @@ -3605,7 +3614,7 @@ msgstr "Denda" #: admin/modules/circulation/submenu.php:30 #: admin/modules/reporting/customs/customs_report_list.inc.php:35 #: admin/modules/reporting/customs/loan_history.php:62 -#: lib/contents/member.inc.php:748 +#: lib/contents/member.inc.php:753 msgid "Loan History" msgstr "Sejarah Peminjaman" @@ -3708,8 +3717,8 @@ msgstr "Total denda tidak terbayar" #: admin/modules/membership/index.php:407 #: admin/modules/membership/member_type.php:191 #: admin/modules/reporting/customs/pop_procurement_list.php:31 -#: admin/modules/system/app_user.php:63 admin/modules/system/app_user.php:283 -#: admin/modules/system/app_user.php:424 admin/modules/system/backup.php:49 +#: admin/modules/system/app_user.php:63 admin/modules/system/app_user.php:289 +#: admin/modules/system/app_user.php:430 admin/modules/system/backup.php:49 #: admin/modules/system/backup_proc.php:47 #: admin/modules/system/barcode_generator.php:43 #: admin/modules/system/biblio_indexes.php:45 @@ -3886,14 +3895,15 @@ msgid "Quick Return is disabled" msgstr "Pengembalian cepat tidak tersedia" #: admin/modules/circulation/quick_return.php:82 -#: admin/modules/circulation/submenu.php:28 admin/modules/system/index.php:327 +#: admin/modules/circulation/submenu.php:28 admin/modules/system/index.php:337 msgid "Quick Return" msgstr "Pengembalian Kilat" #: admin/modules/circulation/quick_return.php:85 msgid "Insert an item ID to return collection with keyboard or barcode reader" msgstr "" -"Masukan kode eksemplar dengan menggunakan papan kunci atau pemindai barkod" +"Masukan kode eksemplar dengan menggunakan papan kunci atau pemindai Kode " +"batang" #: admin/modules/circulation/quick_return.php:89 msgid "Item ID" @@ -4761,7 +4771,7 @@ msgstr "Kode" #: admin/modules/master_file/rda_cmc.php:189 #: admin/modules/master_file/rda_cmc.php:209 #: admin/modules/master_file/rda_cmc.php:213 lib/contents/librarian.inc.php:47 -#: sysconfig.inc.php:694 +#: sysconfig.inc.php:701 msgid "Name" msgstr "Nama" @@ -4940,7 +4950,7 @@ msgstr "Kontak" #: admin/modules/membership/index.php:510 #: admin/modules/reporting/customs/due_date_warning.php:152 #: admin/modules/reporting/customs/member_loan_list.php:185 -#: admin/modules/reporting/customs/overdued_list.php:190 +#: admin/modules/reporting/customs/overdued_list.php:194 #: files/membercard/classic/membercard.php:286 #: files/membercard/old/membercard.php:331 msgid "Phone Number" @@ -5044,9 +5054,9 @@ msgstr "Baris pertama adalah nama kolom" #: admin/modules/membership/index.php:98 msgid "Member ID, Name and Birthday cannot be empty" -msgstr "ID dan Nama Anggota dan Tanggal Lahit tidak boleh kosong" +msgstr "ID dan Nama Anggota dan Tanggal Lahir tidak boleh kosong" -#: admin/modules/membership/index.php:101 admin/modules/system/app_user.php:99 +#: admin/modules/membership/index.php:101 admin/modules/system/app_user.php:101 #: lib/contents/login.inc.php:163 lib/contents/newpass.inc.php:57 msgid "Password confirmation does not match. See if your Caps Lock key is on!" msgstr "" @@ -5065,8 +5075,8 @@ msgid "Member Data Successfully Updated" msgstr "Data Anggota Berhasil diperbarui" #: admin/modules/membership/index.php:257 -#: admin/modules/membership/index.php:294 admin/modules/system/app_user.php:186 -#: admin/modules/system/app_user.php:209 +#: admin/modules/membership/index.php:294 admin/modules/system/app_user.php:190 +#: admin/modules/system/app_user.php:215 msgid "Image FAILED to upload" msgstr "Citra/Berkas Gambar GAGAL Diunggah" @@ -5125,7 +5135,7 @@ msgstr "Set Otomatis" #: admin/modules/reporting/customs/visitor_list.php:89 #: admin/modules/reporting/customs/visitor_list.php:128 #: admin/modules/reporting/customs/visitor_list.php:173 -#: files/membercard/old/membercard.php:314 lib/contents/member.inc.php:255 +#: files/membercard/old/membercard.php:314 lib/contents/member.inc.php:260 #: template/akasia-dz/visitor_template.php:53 #: template/akasia/visitor_template.php:53 #: template/default/visitor_template.php:43 @@ -5186,11 +5196,11 @@ msgstr "Nomor Identitas" msgid "Pending Membership" msgstr "Tunda Keanggotaan" -#: admin/modules/membership/index.php:594 admin/modules/system/app_user.php:359 +#: admin/modules/membership/index.php:594 admin/modules/system/app_user.php:365 msgid "or take a photo" msgstr "atau ambil foto" -#: admin/modules/membership/index.php:597 admin/modules/system/app_user.php:362 +#: admin/modules/membership/index.php:597 admin/modules/system/app_user.php:368 msgid "Load Camera" msgstr "Muat Kamera" @@ -5203,18 +5213,18 @@ msgstr "Foto" #: admin/modules/membership/index.php:711 #: admin/modules/reporting/customs/due_date_warning.php:152 #: admin/modules/reporting/customs/member_loan_list.php:185 -#: admin/modules/reporting/customs/overdued_list.php:190 +#: admin/modules/reporting/customs/overdued_list.php:194 #: files/membercard/old/membercard.php:322 msgid "E-mail" msgstr "Surel" -#: admin/modules/membership/index.php:630 admin/modules/system/app_user.php:403 -#: lib/contents/login.inc.php:199 lib/contents/member.inc.php:279 +#: admin/modules/membership/index.php:630 admin/modules/system/app_user.php:409 +#: lib/contents/login.inc.php:199 lib/contents/member.inc.php:284 #: lib/contents/newpass.inc.php:98 msgid "New Password" msgstr "Kata sandi Baru" -#: admin/modules/membership/index.php:632 admin/modules/system/app_user.php:405 +#: admin/modules/membership/index.php:632 admin/modules/system/app_user.php:411 #: lib/contents/login.inc.php:201 lib/contents/newpass.inc.php:100 msgid "Confirm New Password" msgstr "Konfirmasi Kata Sandi Baru" @@ -5224,7 +5234,7 @@ msgstr "Konfirmasi Kata Sandi Baru" msgid "You are going to edit member data" msgstr "Anda akan menyunting data anggota" -#: admin/modules/membership/index.php:644 admin/modules/system/app_user.php:411 +#: admin/modules/membership/index.php:644 admin/modules/system/app_user.php:417 msgid "Leave Password field blank if you don't want to change the password" msgstr "Biarkan ruas Kata Sandi kosong jika tidak ingin mengubahnya" @@ -5326,21 +5336,21 @@ msgid "Loan Periode (In Days)" msgstr "Lama Peminjaman (Dalam Hari)" #: admin/modules/membership/member_type.php:226 -#: admin/modules/system/index.php:326 admin/modules/system/index.php:338 -#: admin/modules/system/index.php:344 admin/modules/system/index.php:351 -#: admin/modules/system/index.php:357 admin/modules/system/index.php:363 -#: admin/modules/system/index.php:369 admin/modules/system/index.php:387 -#: admin/modules/system/index.php:403 admin/modules/system/ucsetting.php:89 +#: admin/modules/system/index.php:336 admin/modules/system/index.php:348 +#: admin/modules/system/index.php:354 admin/modules/system/index.php:361 +#: admin/modules/system/index.php:367 admin/modules/system/index.php:373 +#: admin/modules/system/index.php:379 admin/modules/system/index.php:397 +#: admin/modules/system/index.php:413 admin/modules/system/ucsetting.php:89 #: template/default/tinfo.inc.php:223 msgid "Enable" msgstr "Dimungkinkan" #: admin/modules/membership/member_type.php:227 -#: admin/modules/system/index.php:325 admin/modules/system/index.php:337 -#: admin/modules/system/index.php:343 admin/modules/system/index.php:350 -#: admin/modules/system/index.php:356 admin/modules/system/index.php:362 -#: admin/modules/system/index.php:368 admin/modules/system/index.php:386 -#: admin/modules/system/index.php:402 admin/modules/system/ucsetting.php:88 +#: admin/modules/system/index.php:335 admin/modules/system/index.php:347 +#: admin/modules/system/index.php:353 admin/modules/system/index.php:360 +#: admin/modules/system/index.php:366 admin/modules/system/index.php:372 +#: admin/modules/system/index.php:378 admin/modules/system/index.php:396 +#: admin/modules/system/index.php:412 admin/modules/system/ucsetting.php:88 #: template/default/tinfo.inc.php:224 msgid "Disable" msgstr "Tidak mungkin" @@ -5441,7 +5451,7 @@ msgstr "Rekapitulasi" #: admin/modules/reporting/customs/dl_detail.php:71 #: admin/modules/reporting/customs/due_date_warning.php:64 #: admin/modules/reporting/customs/fines_report.php:74 -#: admin/modules/reporting/customs/item_titles_list.php:64 +#: admin/modules/reporting/customs/item_titles_list.php:65 #: admin/modules/reporting/customs/item_usage.php:63 #: admin/modules/reporting/customs/loan_by_class.php:61 #: admin/modules/reporting/customs/loan_history.php:65 @@ -5468,7 +5478,7 @@ msgstr "Rekap berdasar" #: admin/modules/reporting/customs/dl_detail.php:106 #: admin/modules/reporting/customs/due_date_warning.php:83 #: admin/modules/reporting/customs/fines_report.php:103 -#: admin/modules/reporting/customs/item_titles_list.php:139 +#: admin/modules/reporting/customs/item_titles_list.php:140 #: admin/modules/reporting/customs/item_usage.php:89 #: admin/modules/reporting/customs/loan_by_class.php:120 #: admin/modules/reporting/customs/loan_history.php:131 @@ -5521,7 +5531,7 @@ msgid "List of bibliographic titles" msgstr "Daftar judul bibliografi" #: admin/modules/reporting/customs/customs_report_list.inc.php:30 -#: admin/modules/reporting/customs/item_titles_list.php:61 +#: admin/modules/reporting/customs/item_titles_list.php:62 msgid "Items Title List" msgstr "Daftar Judul Eksemplar" @@ -5620,7 +5630,7 @@ msgstr "Laporan Lampiran" #: admin/modules/reporting/customs/dl_counter.php:71 #: admin/modules/reporting/customs/dl_detail.php:77 -#: admin/modules/reporting/customs/item_titles_list.php:70 +#: admin/modules/reporting/customs/item_titles_list.php:71 #: admin/modules/reporting/customs/item_usage.php:69 #: admin/modules/reporting/customs/reserve_list.php:73 #: admin/modules/reporting/customs/titles_list.php:71 @@ -5630,7 +5640,7 @@ msgstr "Judul/ISBN" #: admin/modules/reporting/customs/dl_counter.php:79 #: admin/modules/reporting/customs/dl_detail.php:85 -#: admin/modules/reporting/customs/item_titles_list.php:129 +#: admin/modules/reporting/customs/item_titles_list.php:130 #: admin/modules/reporting/customs/titles_list.php:106 msgid "Publish year" msgstr "Tahun terbit" @@ -5648,7 +5658,7 @@ msgstr "Tanggal Akses hingga" #: admin/modules/reporting/customs/dl_counter.php:95 #: admin/modules/reporting/customs/dl_detail.php:101 #: admin/modules/reporting/customs/due_date_warning.php:77 -#: admin/modules/reporting/customs/item_titles_list.php:133 +#: admin/modules/reporting/customs/item_titles_list.php:134 #: admin/modules/reporting/customs/loan_history.php:125 #: admin/modules/reporting/customs/member_fines_list.php:102 #: admin/modules/reporting/customs/member_list.php:109 @@ -5662,7 +5672,7 @@ msgstr "Cantuman per halaman" #: admin/modules/reporting/customs/dl_counter.php:96 #: admin/modules/reporting/customs/dl_detail.php:102 #: admin/modules/reporting/customs/due_date_warning.php:79 -#: admin/modules/reporting/customs/item_titles_list.php:135 +#: admin/modules/reporting/customs/item_titles_list.php:136 #: admin/modules/reporting/customs/loan_history.php:127 #: admin/modules/reporting/customs/member_fines_list.php:104 #: admin/modules/reporting/customs/member_list.php:111 @@ -5677,7 +5687,7 @@ msgstr "Buat antara 20 dan 200" #: admin/modules/reporting/customs/dl_detail.php:105 #: admin/modules/reporting/customs/due_date_warning.php:82 #: admin/modules/reporting/customs/fines_report.php:102 -#: admin/modules/reporting/customs/item_titles_list.php:138 +#: admin/modules/reporting/customs/item_titles_list.php:139 #: admin/modules/reporting/customs/item_usage.php:88 #: admin/modules/reporting/customs/loan_by_class.php:119 #: admin/modules/reporting/customs/loan_history.php:130 @@ -5845,7 +5855,7 @@ msgstr "Des" msgid "Fines count report for" msgstr "Laporan perhitungan denda untuk" -#: admin/modules/reporting/customs/item_titles_list.php:90 +#: admin/modules/reporting/customs/item_titles_list.php:91 #: admin/modules/reporting/customs/titles_list.php:91 msgid "Press Ctrl and click to select multiple entries" msgstr "Tekan Ctrl dan klik untuk memilih lebih dari satu" @@ -5960,15 +5970,15 @@ msgstr "Tanggal Pendaftaran Sejak" msgid "Register Date Until" msgstr "Tanggal Pendaftaran Hingga" -#: admin/modules/reporting/customs/overdued_list.php:190 +#: admin/modules/reporting/customs/overdued_list.php:194 msgid "Send Notification e-mail" msgstr "Kirim surel Pemberitahuan" -#: admin/modules/reporting/customs/overdued_list.php:195 +#: admin/modules/reporting/customs/overdued_list.php:208 msgid "Book Price" msgstr "Harga Buku" -#: admin/modules/reporting/customs/overdued_list.php:196 +#: admin/modules/reporting/customs/overdued_list.php:209 msgid "day(s)" msgstr "hari" @@ -6033,14 +6043,14 @@ msgid "Activity Date Until" msgstr "Aktifitas Hingga" #: admin/modules/reporting/customs/staff_act.php:93 -#: admin/modules/system/app_user.php:329 admin/modules/system/app_user.php:435 -#: admin/modules/system/app_user.php:442 admin/modules/system/app_user.php:443 +#: admin/modules/system/app_user.php:335 admin/modules/system/app_user.php:441 +#: admin/modules/system/app_user.php:448 admin/modules/system/app_user.php:449 msgid "Real Name" msgstr "Nama Asli" #: admin/modules/reporting/customs/staff_act.php:94 -#: admin/modules/system/app_user.php:323 admin/modules/system/app_user.php:325 -#: admin/modules/system/app_user.php:436 +#: admin/modules/system/app_user.php:329 admin/modules/system/app_user.php:331 +#: admin/modules/system/app_user.php:442 msgid "Login Username" msgstr "Nama masuk Pengguna" @@ -6110,6 +6120,7 @@ msgstr "" "Laporan Penghitung Pengunjung untuk tahun {selectedYear}" #: admin/modules/reporting/customs/visitor_report_day.php:61 +#: admin/modules/reporting/customs/visitor_report_day.php:128 msgid "Visitor Report by Day" msgstr "Laporan Pengunjung berdasarkan Hari" @@ -6867,77 +6878,77 @@ msgstr "Resinkronisasi data bibliografi dengan inventarisasi terkini" msgid "Finish Current Stock Take Proccess" msgstr "Selesaikan Proses Inventarisasi Terkini" -#: admin/modules/system/app_user.php:93 +#: admin/modules/system/app_user.php:95 msgid "User Name or Real Name can't be empty" msgstr "Nama Pengguna atau Nama Asli tidak boleh kosong" -#: admin/modules/system/app_user.php:96 +#: admin/modules/system/app_user.php:98 msgid "Login username or Real Name is probihited!" msgstr "Nama masuk pengguna atau Nama Lengkap tidak bisa digunakan!" -#: admin/modules/system/app_user.php:176 +#: admin/modules/system/app_user.php:178 msgid "User Data Successfully Updated" msgstr "Data Pengguna Berhasil Diperbaharui" -#: admin/modules/system/app_user.php:191 +#: admin/modules/system/app_user.php:195 msgid "User Data FAILED to Updated. Please Contact System Administrator" msgstr "Data Pengguna GAGAL Diperbaharui. Hubungi Administrator Sistem" -#: admin/modules/system/app_user.php:199 +#: admin/modules/system/app_user.php:203 msgid "New User Data Successfully Saved" msgstr "Data Pengguna Baru Berhasil Disimpan" -#: admin/modules/system/app_user.php:213 +#: admin/modules/system/app_user.php:219 msgid "User Data FAILED to Save. Please Contact System Administrator" msgstr "Data Pengguna Baru GAGAL Disimpan. Hubungi Administrator Sistem" -#: admin/modules/system/app_user.php:262 admin/modules/system/submenu.php:48 +#: admin/modules/system/app_user.php:268 admin/modules/system/submenu.php:50 msgid "Librarian & System Users" msgstr "Pustakawan & Pengguna Sistem" -#: admin/modules/system/app_user.php:266 +#: admin/modules/system/app_user.php:272 msgid "User List" msgstr "Daftar Pengguna" -#: admin/modules/system/app_user.php:267 +#: admin/modules/system/app_user.php:273 msgid "Add New User" msgstr "Tambah Pengguna" -#: admin/modules/system/app_user.php:335 admin/modules/system/app_user.php:437 -#: admin/modules/system/app_user.php:444 +#: admin/modules/system/app_user.php:341 admin/modules/system/app_user.php:443 +#: admin/modules/system/app_user.php:450 msgid "User Type" msgstr "Tipe Keanggotaan" -#: admin/modules/system/app_user.php:337 lib/contents/librarian.inc.php:49 +#: admin/modules/system/app_user.php:343 lib/contents/librarian.inc.php:49 msgid "E-Mail" msgstr "Surel" -#: admin/modules/system/app_user.php:349 +#: admin/modules/system/app_user.php:355 msgid "Social Media" msgstr "Media Sosial" -#: admin/modules/system/app_user.php:353 +#: admin/modules/system/app_user.php:359 msgid "REMOVE IMAGE" msgstr "HILANGKAN GAMBAR" -#: admin/modules/system/app_user.php:385 +#: admin/modules/system/app_user.php:391 msgid "User Photo" msgstr "Foto Pengguna" -#: admin/modules/system/app_user.php:400 +#: admin/modules/system/app_user.php:406 msgid "Group(s)" msgstr "Kelompok" -#: admin/modules/system/app_user.php:410 +#: admin/modules/system/app_user.php:416 msgid "You are going to edit user profile" msgstr "Anda akan menyunting data pengguna" -#: admin/modules/system/app_user.php:438 admin/modules/system/app_user.php:445 +#: admin/modules/system/app_user.php:444 admin/modules/system/app_user.php:451 msgid "Last Login" msgstr "Terakhir kali Masuk" #: admin/modules/system/backup.php:103 admin/modules/system/backup.php:106 -#: admin/modules/system/backup.php:117 admin/modules/system/submenu.php:55 +#: admin/modules/system/backup.php:117 admin/modules/system/submenu.php:57 msgid "Database Backup" msgstr "Salinan Pangkalan Data" @@ -6945,23 +6956,23 @@ msgstr "Salinan Pangkalan Data" msgid "Start New Backup" msgstr "Mulai Salinan Baru" -#: admin/modules/system/backup.php:148 admin/modules/system/backup.php:156 +#: admin/modules/system/backup.php:147 msgid "Backup Executor" msgstr "Pelaksana Pencadangan" -#: admin/modules/system/backup.php:149 admin/modules/system/backup.php:157 +#: admin/modules/system/backup.php:148 msgid "Backup Time" msgstr "Waktu Pencadangan" -#: admin/modules/system/backup.php:150 admin/modules/system/backup.php:158 +#: admin/modules/system/backup.php:149 msgid "Backup File Location" msgstr "Lokasi Berkas Cadangan" -#: admin/modules/system/backup.php:151 admin/modules/system/backup.php:159 +#: admin/modules/system/backup.php:150 msgid "File Size" msgstr "Ukuran Berkas" -#: admin/modules/system/backup.php:176 +#: admin/modules/system/backup.php:168 msgid "File not found" msgstr "Berkas tidak ada" @@ -6990,7 +7001,7 @@ msgstr "Hubungi Admin Sistem untuk mengarahkan direktori backup" #: admin/modules/system/barcode_generator.php:102 #: admin/modules/system/barcode_generator.php:134 -#: admin/modules/system/submenu.php:53 +#: admin/modules/system/submenu.php:55 msgid "Barcode Generator" msgstr "Pembuat Barkod" @@ -7004,7 +7015,7 @@ msgstr "" #: admin/modules/system/barcode_generator.php:117 msgid "Error creating barcode!" -msgstr "GAGAL mencetak barkod!" +msgstr "GAGAL mencetak Kode batang!" #: admin/modules/system/barcode_generator.php:123 msgid "Barcode generation finished" @@ -7013,7 +7024,7 @@ msgstr "Pencetakan Barkod selesai" #: admin/modules/system/barcode_generator.php:137 msgid "" "Enter your barcodes code on one or more textboxes below to create barcode" -msgstr "Masukkan kode pada kotak teks di bawah untuk membuat barkod" +msgstr "Masukkan kode pada kotak teks di bawah untuk membuat Kode batang" #: admin/modules/system/barcode_generator.php:152 msgid "Barcode Size" @@ -7149,7 +7160,7 @@ msgstr "Data Konten berhasil disimpan" msgid "Content data FAILED to save!" msgstr "Data Konten GAGAL disimpan!" -#: admin/modules/system/content.php:169 admin/modules/system/submenu.php:38 +#: admin/modules/system/content.php:169 admin/modules/system/submenu.php:40 msgid "Content" msgstr "Konten" @@ -7192,7 +7203,7 @@ msgstr "Anda akan mengubah data Konten" #: admin/modules/system/custom_field.php:118 #: admin/modules/system/custom_field.php:150 #: admin/modules/system/custom_field.php:154 -#: admin/modules/system/submenu.php:36 +#: admin/modules/system/submenu.php:37 msgid "Custom Field" msgstr "Ruas Tambahan" @@ -7300,60 +7311,99 @@ msgstr "" "Peringatan : Memperbarui daftar data atau tabel utama akan " "menghapus konten dalam tabel ini" -#: admin/modules/system/envinfo.php:50 admin/modules/system/index.php:248 +#: admin/modules/system/envinfo.php:50 +msgid "SLiMS Environment Mode" +msgstr "Moda Lingkungan SLiMS" + +#: admin/modules/system/envinfo.php:51 admin/modules/system/index.php:254 msgid "SLiMS Version" msgstr "Versi SLiMS" -#: admin/modules/system/envinfo.php:51 +#: admin/modules/system/envinfo.php:52 msgid "Operating System" msgstr "Sistem Operasi" -#: admin/modules/system/envinfo.php:52 +#: admin/modules/system/envinfo.php:53 msgid "OS Architecture" msgstr "Arsitektur OS" -#: admin/modules/system/envinfo.php:53 +#: admin/modules/system/envinfo.php:54 msgid "Web Server" msgstr "Peladen Web" -#: admin/modules/system/envinfo.php:54 +#: admin/modules/system/envinfo.php:55 msgid "PHP version" msgstr "Versi PHP" -#: admin/modules/system/envinfo.php:55 +#: admin/modules/system/envinfo.php:56 msgid "MySQL Database version" msgstr "Versi Pangkalan data MySQL" -#: admin/modules/system/envinfo.php:56 +#: admin/modules/system/envinfo.php:57 msgid "MySQL Client version" msgstr "Versi Klien MySQL" -#: admin/modules/system/envinfo.php:57 +#: admin/modules/system/envinfo.php:58 msgid "Browser/User Agent" msgstr "Peramban/Agen Pengguna" -#: admin/modules/system/envinfo.php:58 +#: admin/modules/system/envinfo.php:59 msgid "Hostname" msgstr "Hostname" -#: admin/modules/system/envinfo.php:59 +#: admin/modules/system/envinfo.php:60 msgid "jQuery version" msgstr "versi JQuery" -#: admin/modules/system/envinfo.php:60 +#: admin/modules/system/envinfo.php:61 msgid "HTML5 Support?" msgstr "Mendukung HTML5?" -#: admin/modules/system/envinfo.php:66 admin/modules/system/submenu.php:32 +#: admin/modules/system/envinfo.php:67 admin/modules/system/submenu.php:32 msgid "System Environment" msgstr "Lingkungan Sistem" -#: admin/modules/system/envinfo.php:69 +#: admin/modules/system/envinfo.php:70 msgid "" "Information on SLiMS System Environment. Use this to support troubleshotting " "problem." msgstr "Informasi terkait sistem SLiMS. Digunakan untuk dukungan perbaikan." +#: admin/modules/system/envsetting.php:49 +#: admin/modules/system/mailsetting.php:64 +msgid "Error" +msgstr "Galat" + +#: admin/modules/system/envsetting.php:49 +msgid "sysconfig.env.inc.php file is not writeable!" +msgstr "tidak dapat menulis ke berkas sysconfig.env.inc.php!" + +#: admin/modules/system/envsetting.php:86 +#: admin/modules/system/mailsetting.php:130 +#: admin/modules/system/mailsetting.php:132 +msgid "Success" +msgstr "Berhasil" + +#: admin/modules/system/envsetting.php:86 +msgid "Configuration has been saved!" +msgstr "Telah tersimpan konfigurasi!" + +#: admin/modules/system/envsetting.php:99 +msgid "System Environment Settings" +msgstr "Setelan Lingkungan Sistem" + +#: admin/modules/system/envsetting.php:102 +msgid "SLiMS Environment preferences." +msgstr "Pilihan Lingkungan SLiMS." + +#: admin/modules/system/holiday.php:58 admin/modules/system/holiday.php:63 +#: admin/modules/system/holiday.php:78 admin/modules/system/holiday.php:85 +#: admin/modules/system/holiday.php:92 admin/modules/system/holiday.php:99 +#: admin/modules/system/holiday.php:124 admin/modules/system/holiday.php:160 +#: admin/modules/system/holiday.php:163 admin/modules/system/holiday.php:174 +msgid "Holiday Settings" +msgstr "Setelan Hari Libur" + #: admin/modules/system/holiday.php:58 msgid "Holiday description can't be empty!" msgstr "Keterangan hari mohon diisi!" @@ -7383,217 +7433,309 @@ msgstr "" msgid "Holiday FAILED to Save. Please Contact System Administrator" msgstr "Hari Libur GAGAL Disimpan. Hubungi administrator Sistem" -#: admin/modules/system/holiday.php:174 -msgid "Holiday Settings" -msgstr "Setelan Hari Libur" - -#: admin/modules/system/holiday.php:179 admin/modules/system/submenu.php:52 +#: admin/modules/system/holiday.php:178 admin/modules/system/submenu.php:54 msgid "Holiday Setting" msgstr "Setelan Hari Libur" -#: admin/modules/system/holiday.php:180 +#: admin/modules/system/holiday.php:179 msgid "Special holiday" msgstr "Hari Libur Khusus" -#: admin/modules/system/holiday.php:181 +#: admin/modules/system/holiday.php:180 msgid "Add Special holiday" msgstr "Tambah Hari Libur Khusus" -#: admin/modules/system/holiday.php:216 admin/modules/system/holiday.php:240 -#: admin/modules/system/holiday.php:244 +#: admin/modules/system/holiday.php:215 admin/modules/system/holiday.php:239 +#: admin/modules/system/holiday.php:243 msgid "Holiday Date Start" msgstr "Mula Tanggal Libur" -#: admin/modules/system/holiday.php:219 +#: admin/modules/system/holiday.php:218 msgid "Holiday Date End" msgstr "Akhir Tanggal Libur" -#: admin/modules/system/holiday.php:222 admin/modules/system/holiday.php:241 -#: admin/modules/system/holiday.php:245 +#: admin/modules/system/holiday.php:221 admin/modules/system/holiday.php:240 +#: admin/modules/system/holiday.php:244 msgid "Holiday Description" msgstr "Keterangan Hari Libur" -#: admin/modules/system/holiday.php:226 +#: admin/modules/system/holiday.php:225 msgid "You are going to edit holiday data" msgstr "Anda akan menyunting hari libur" -#: admin/modules/system/holiday.php:239 admin/modules/system/holiday.php:243 +#: admin/modules/system/holiday.php:238 admin/modules/system/holiday.php:242 msgid "Day name" msgstr "Nama hari" -#: admin/modules/system/holiday.php:278 -msgid "Maximum 6 day can be set as holiday!" -msgstr "Hari libur bisa diatur maksimal 6 hari!" - -#: admin/modules/system/holiday.php:292 -msgid "Holiday settings saved" -msgstr "Aturan hari libur tersimpan" +#: admin/modules/system/holiday.php:261 admin/modules/system/holiday.php:362 +#: simbio2/simbio_UTILS/simbio_date.inc.php:246 +msgid "Sunday" +msgstr "Minggu" -#: admin/modules/system/holiday.php:321 +#: admin/modules/system/holiday.php:264 admin/modules/system/holiday.php:354 #: simbio2/simbio_UTILS/simbio_date.inc.php:247 msgid "Monday" msgstr "Senin" -#: admin/modules/system/holiday.php:322 +#: admin/modules/system/holiday.php:267 admin/modules/system/holiday.php:355 #: simbio2/simbio_UTILS/simbio_date.inc.php:248 msgid "Tuesday" msgstr "Selasa" -#: admin/modules/system/holiday.php:323 +#: admin/modules/system/holiday.php:270 admin/modules/system/holiday.php:356 #: simbio2/simbio_UTILS/simbio_date.inc.php:249 msgid "Wednesday" msgstr "Rabu" -#: admin/modules/system/holiday.php:325 +#: admin/modules/system/holiday.php:273 admin/modules/system/holiday.php:358 #: simbio2/simbio_UTILS/simbio_date.inc.php:250 msgid "Thursday" msgstr "Kamis" -#: admin/modules/system/holiday.php:326 +#: admin/modules/system/holiday.php:276 admin/modules/system/holiday.php:359 #: simbio2/simbio_UTILS/simbio_date.inc.php:251 msgid "Friday" msgstr "Jumat" -#: admin/modules/system/holiday.php:327 +#: admin/modules/system/holiday.php:279 admin/modules/system/holiday.php:360 #: simbio2/simbio_UTILS/simbio_date.inc.php:252 msgid "Saturday" msgstr "Sabtu" -#: admin/modules/system/holiday.php:329 -#: simbio2/simbio_UTILS/simbio_date.inc.php:246 -msgid "Sunday" -msgstr "Minggu" +#: admin/modules/system/holiday.php:307 +msgid "Maximum 6 day can be set as holiday!" +msgstr "Hari libur bisa diatur maksimal 6 hari!" + +#: admin/modules/system/holiday.php:321 +msgid "Holiday settings saved" +msgstr "Aturan hari libur tersimpan" -#: admin/modules/system/index.php:78 admin/modules/system/index.php:96 -#: admin/modules/system/index.php:119 admin/modules/system/index.php:228 +#: admin/modules/system/index.php:81 admin/modules/system/index.php:99 +#: admin/modules/system/index.php:122 admin/modules/system/index.php:234 #: admin/modules/system/submenu.php:31 msgid "System Configuration" msgstr "Pengaturan Sistem" -#: admin/modules/system/index.php:81 +#: admin/modules/system/index.php:84 msgid "Modify global application preferences" msgstr "Merubah preferensi aplikasi global" -#: admin/modules/system/index.php:96 +#: admin/modules/system/index.php:99 msgid "Logo Image removed. Refreshing page" msgstr "Logo dihapus. Segarkan laman" -#: admin/modules/system/index.php:228 +#: admin/modules/system/index.php:234 msgid "Settings saved. Refreshing page" msgstr "Pengaturan disimpan. Penyegaran laman" -#: admin/modules/system/index.php:251 +#: admin/modules/system/index.php:257 msgid "Library Name" msgstr "Nama Perpustakaan" -#: admin/modules/system/index.php:254 +#: admin/modules/system/index.php:260 msgid "Library Subname" msgstr "Nama Tambahan Perpustakaan" -#: admin/modules/system/index.php:278 +#: admin/modules/system/index.php:284 msgid "Logo Image" msgstr "Gambar Logo" -#: admin/modules/system/index.php:309 +#: admin/modules/system/index.php:315 msgid "Default App. Language" msgstr "Bahasa Aplikasi Baku" -#: admin/modules/system/index.php:317 +#: admin/modules/system/index.php:319 +msgid "Search Engine" +msgstr "Mesin Pencari" + +#: admin/modules/system/index.php:327 msgid "Number Of Collections To Show In OPAC Result List" msgstr "Jumlah koleksi yang ditampilkan hasil pencarian OPAC" -#: admin/modules/system/index.php:321 +#: admin/modules/system/index.php:331 msgid "Show Promoted Titles at Homepage" msgstr "Tampilkan Judul Terpilih di laman OPAC" -#: admin/modules/system/index.php:331 +#: admin/modules/system/index.php:341 msgid "Don't Print" msgstr "Jangan Cetak" -#: admin/modules/system/index.php:332 +#: admin/modules/system/index.php:342 msgid "Print" msgstr "Cetak" -#: admin/modules/system/index.php:333 +#: admin/modules/system/index.php:343 msgid "Print Circulation Receipt" msgstr "Cetak Bukti Sirkulasi" -#: admin/modules/system/index.php:339 +#: admin/modules/system/index.php:349 msgid "Loan and Due Date Manual Change" msgstr "Perubahan Manual Tanggal Peminjaman dan Jatuh Tempo" -#: admin/modules/system/index.php:345 +#: admin/modules/system/index.php:355 msgid "Loan Limit Override" msgstr "Mengabaikan Batas Pinjam" -#: admin/modules/system/index.php:352 +#: admin/modules/system/index.php:362 msgid "Ignore Holidays Fine Calculation" msgstr "Abaikan Perhitungan Denda Kala Libur" -#: admin/modules/system/index.php:358 +#: admin/modules/system/index.php:368 msgid "OPAC XML Detail" msgstr "Detail XML OPAC" -#: admin/modules/system/index.php:364 +#: admin/modules/system/index.php:374 msgid "OPAC XML Result" msgstr "Hasil XML OPAC" -#: admin/modules/system/index.php:370 +#: admin/modules/system/index.php:380 msgid "Enable Search Spellchecker" msgstr "Aktifkan Pemeriksa Ejaan" -#: admin/modules/system/index.php:374 +#: admin/modules/system/index.php:384 msgid "Forbid" msgstr "Dilarang" -#: admin/modules/system/index.php:375 +#: admin/modules/system/index.php:385 msgid "Allow" msgstr "Diijinkan" -#: admin/modules/system/index.php:376 +#: admin/modules/system/index.php:386 msgid "Allow OPAC File Download" msgstr "Izinkan Pengunduhan Berkas OPAC" -#: admin/modules/system/index.php:379 +#: admin/modules/system/index.php:389 msgid "Session Login Timeout" msgstr "Sesi Masuk Berakhir" -#: admin/modules/system/index.php:382 +#: admin/modules/system/index.php:392 msgid "Barcode Encoding" msgstr "Penyandian Barkod" -#: admin/modules/system/index.php:388 +#: admin/modules/system/index.php:398 msgid "Visitor Counter by IP" msgstr "Konfigurasi Penghitung Pengunjung dengan IP" -#: admin/modules/system/index.php:389 +#: admin/modules/system/index.php:399 msgid "Allowed Counter IP" msgstr "IP yang Diizinkan" -#: admin/modules/system/index.php:391 +#: admin/modules/system/index.php:401 msgid "Visitor Limitation by Time" msgstr "Pembatasan Akses Penghitung Pengunjung berdasarkan Waktu" -#: admin/modules/system/index.php:394 +#: admin/modules/system/index.php:404 msgid "Time visitor limitation (in minute)" msgstr "Maksimal waktu kunjungan (dalam menit)" -#: admin/modules/system/index.php:397 +#: admin/modules/system/index.php:407 msgid "Email" msgstr "Surel" -#: admin/modules/system/index.php:398 +#: admin/modules/system/index.php:408 msgid "Database" msgstr "Pangkalan data" -#: admin/modules/system/index.php:399 +#: admin/modules/system/index.php:409 msgid "Reserve methode" msgstr "Metode pemesanan" -#: admin/modules/system/index.php:404 +#: admin/modules/system/index.php:414 msgid "Reserve for item on loan only" msgstr "Pemesanan hanya untuk eksemplar terpinjam" +#: admin/modules/system/mailsetting.php:53 +msgid "NB : Password is hidden for security reason" +msgstr "PS : Untuk alasan keamanan, kata sandi tidak diperlihatkan" + +#: admin/modules/system/mailsetting.php:54 +msgid "Example" +msgstr "Contoh" + +#: admin/modules/system/mailsetting.php:64 +#: admin/modules/system/mailsetting.php:159 +msgid "Directory config is not writeable." +msgstr "Tidak dapat menulis ke dalam direktori config." + +#: admin/modules/system/mailsetting.php:90 +#: admin/modules/system/mailsetting.php:149 +msgid "E-Mail Configuration" +msgstr "Konfigurasi surel" + +#: admin/modules/system/mailsetting.php:90 +#: admin/modules/system/ucsetting.php:52 +msgid "Settings inserted." +msgstr "Setelan tersimpan." + +#: admin/modules/system/mailsetting.php:155 +msgid "E-Mail test" +msgstr "Coba kirim surel" + +#: admin/modules/system/mailsetting.php:155 +msgid "Modify E-Mail preferences" +msgstr "Ganti pilihan surel" + +#: admin/modules/system/mailsetting.php:160 +msgid "" +"Make the following files and directories (and their contents) writeable (i." +"e., by changing the owner or permissions with chown or chmod)" +msgstr "" +"Direktori dan berkas-berkas di dalamnya harus dapat ditulis oleh sistem " +"(lakukan perubahan pada izin kepemilikan, contoh, gunakan chown atau chmod " +"pada Linux)" + +#: admin/modules/system/mailsetting.php:176 +msgid "Production" +msgstr "Produksi" + +#: admin/modules/system/mailsetting.php:177 +msgid "Development" +msgstr "Pengembangan" + +#: admin/modules/system/mailsetting.php:179 +msgid "Environment" +msgstr "Lingkungan" + +#: admin/modules/system/mailsetting.php:182 +msgid "SMTP Encryption" +msgstr "Enkripsi SMTP" + +#: admin/modules/system/mailsetting.php:185 +msgid "SMTP Server address" +msgstr "Alamat peladen SMTP" + +#: admin/modules/system/mailsetting.php:188 +msgid "SMTP Port" +msgstr "Porta SMTP" + +#: admin/modules/system/mailsetting.php:191 +msgid "Authentication Username" +msgstr "Nama pengguna terautentikasi" + +#: admin/modules/system/mailsetting.php:194 +msgid "Authentication Password" +msgstr "Kata sandi terautentikasi" + +#: admin/modules/system/mailsetting.php:194 +msgid "" +"Password does not appearance for security reason. If you want to look it, " +"open sysconfig.mail.inc.php file." +msgstr "" +"Untuk alasan keamanan, kata sandi tidak ditampilkan. Lihat berkas sysconfig." +"mail.inc.php untuk melihat kata sandi yang telah dimasukkan." + +#: admin/modules/system/mailsetting.php:197 +msgid "Email Sender Address" +msgstr "Alamat Surel Pengirim" + +#: admin/modules/system/mailsetting.php:200 +msgid "Email Sender Label" +msgstr "Nama Pengirim Surel" + +#: admin/modules/system/mailsetting.php:205 +msgid "Do Test" +msgstr "Coba kirim surel" + #: admin/modules/system/membercard_theme.php:81 #: admin/modules/system/theme.php:105 msgid "Error saving custom data!" @@ -7661,7 +7803,7 @@ msgstr "Data Modul Baru Berhasil Disimpan" msgid "Module Data FAILED to Save. Please Contact System Administrator" msgstr "Data Modul GAGAL Disimpan. Hubungi administrator Sistem" -#: admin/modules/system/module.php:142 admin/modules/system/submenu.php:46 +#: admin/modules/system/module.php:142 admin/modules/system/submenu.php:48 msgid "Modules" msgstr "Modul" @@ -7768,34 +7910,50 @@ msgid "Information about System Environment" msgstr "Informasi terkait Sistem" #: admin/modules/system/submenu.php:33 +msgid "System Environment Setting" +msgstr "Setelan Lingkungan Sistem" + +#: admin/modules/system/submenu.php:33 +msgid "Configure System Environment Mode" +msgstr "Moda Konfigurasi Lingkungan Sistem" + +#: admin/modules/system/submenu.php:34 msgid "UCS Setting" msgstr "Pengaturan UCS" -#: admin/modules/system/submenu.php:33 +#: admin/modules/system/submenu.php:34 msgid "Configure UCS Preferences" msgstr "Konfigurasi UCS" -#: admin/modules/system/submenu.php:35 +#: admin/modules/system/submenu.php:36 msgid "Plugins" msgstr "Plugin" -#: admin/modules/system/submenu.php:36 +#: admin/modules/system/submenu.php:37 msgid "Configure custom field" msgstr "Konfigurasi ruas tambahan" -#: admin/modules/system/submenu.php:42 admin/modules/system/submenu.php:44 +#: admin/modules/system/submenu.php:38 +msgid "E-Mail Setting" +msgstr "Pengaturan Surel" + +#: admin/modules/system/submenu.php:38 +msgid "Configure E-Mail Preferences" +msgstr "Konfigurasi Surel" + +#: admin/modules/system/submenu.php:44 admin/modules/system/submenu.php:46 msgid "Biblio Indexes" msgstr "Indeks Biblio" -#: admin/modules/system/submenu.php:42 admin/modules/system/submenu.php:44 +#: admin/modules/system/submenu.php:44 admin/modules/system/submenu.php:46 msgid "Bibliographic Indexes management" msgstr "Pengaturan Indeks Bibliografi" -#: admin/modules/system/submenu.php:46 +#: admin/modules/system/submenu.php:48 msgid "Configure Application Modules" msgstr "Konfigurasi Modul Aplikasi" -#: admin/modules/system/submenu.php:47 admin/modules/system/user_group.php:55 +#: admin/modules/system/submenu.php:49 admin/modules/system/user_group.php:55 #: admin/modules/system/user_group.php:96 #: admin/modules/system/user_group.php:99 #: admin/modules/system/user_group.php:132 @@ -7806,28 +7964,28 @@ msgstr "Konfigurasi Modul Aplikasi" msgid "User Group" msgstr "Kelompok Pengguna" -#: admin/modules/system/submenu.php:47 +#: admin/modules/system/submenu.php:49 msgid "Manage Group of Application User" msgstr "Kelola Kelompok Pengguna Aplikasi" -#: admin/modules/system/submenu.php:48 +#: admin/modules/system/submenu.php:50 msgid "Manage Application User or Library Staff" msgstr "Kelola Pengguna Aplikasi atau Staf Perpustakaan" -#: admin/modules/system/submenu.php:52 +#: admin/modules/system/submenu.php:54 msgid "Configure Holiday Setting" msgstr "Konfigurasi Hari Libur" -#: admin/modules/system/submenu.php:54 admin/modules/system/sys_log.php:67 +#: admin/modules/system/submenu.php:56 admin/modules/system/sys_log.php:67 #: admin/modules/system/sys_log.php:77 msgid "System Log" msgstr "Catatan Sistem" -#: admin/modules/system/submenu.php:54 +#: admin/modules/system/submenu.php:56 msgid "View Application System Log" msgstr "Lihat Catatan Aplikasi Sistem" -#: admin/modules/system/submenu.php:55 +#: admin/modules/system/submenu.php:57 msgid "Backup Application Database" msgstr "Buat Salinan Pangkalan Data Aplikasi" @@ -7891,10 +8049,6 @@ msgstr "Pengaturan tersimpan." msgid "Failed save settings!" msgstr "Gagal menyimpan pengaturan!" -#: admin/modules/system/ucsetting.php:52 -msgid "Settings inserted." -msgstr "Setelan tersimpan." - #: admin/modules/system/ucsetting.php:65 msgid "Modify UCS preferences" msgstr "Ubah Preferensi UCS" @@ -8116,11 +8270,11 @@ msgstr "" "Akses Katalog Publik Daring - Gunakan fasilitas pencarian untuk mempercepat " "penemuan data katalog" -#: index.php:56 +#: index.php:58 msgid "You are currently Logged on as member" msgstr "Anda saat ini masuk sebagai anggota" -#: index.php:56 lib/contents/member.inc.php:712 +#: index.php:58 lib/contents/member.inc.php:717 msgid "LOGOUT" msgstr "KELUAR" @@ -8180,24 +8334,12 @@ msgstr "Semua Koleksi" msgid "All GMD/Media" msgstr "Semua GMD/Media" -#: lib/contents/default.inc.php:161 lib/contents/default.inc.php:174 +#: lib/contents/default.inc.php:93 msgid "Found {biblio_list->num_rows} from your keywords" msgstr "" "Ditemukan {biblio_list->num_rows} dari pencarian Anda " "melalui kata kunci" -#: lib/contents/default.inc.php:198 -msgid "" -"You currently on page {page} of {total_pages} page(s)" -msgstr "" -"Saat ini anda berada pada halaman {page} dari total " -"{total_pages} halaman" - -#: lib/contents/default.inc.php:219 -msgid "Did you mean:" -msgstr "Yang Anda maksud:" - #: lib/contents/download_current_loan.inc.php:88 msgid "Current Loan item(s)" msgstr "Eksemplar Terpinjam Saat Ini" @@ -8207,12 +8349,12 @@ msgid "Your Current Loan" msgstr "Pinjaman Terkini" #: lib/contents/download_loan_history.inc.php:64 -#: lib/contents/member.inc.php:408 +#: lib/contents/member.inc.php:413 msgid "Return Date" msgstr "Tanggal Kembali" #: lib/contents/download_loan_history.inc.php:88 -#: lib/contents/member.inc.php:421 +#: lib/contents/member.inc.php:426 msgid "item(s) loan history" msgstr "sejarah peminjaman eksemplar" @@ -8310,7 +8452,7 @@ msgstr "Kata Sandi saat ini tidak boleh kosong!" msgid "Hi {username}, please update your password!" msgstr "Hai {username}, mohon perbarui kata sandi Anda!" -#: lib/contents/login.inc.php:197 lib/contents/member.inc.php:275 +#: lib/contents/login.inc.php:197 lib/contents/member.inc.php:280 msgid "Current Password" msgstr "Kata Sandi Terkini" @@ -8322,7 +8464,7 @@ msgstr "Token tidak valid!" msgid "Go Home" msgstr "Kembali ke Beranda" -#: lib/contents/login.inc.php:234 lib/contents/member.inc.php:909 +#: lib/contents/login.inc.php:234 lib/contents/member.inc.php:914 msgid "Password" msgstr "Kata Sandi" @@ -8330,7 +8472,7 @@ msgstr "Kata Sandi" msgid "Remember me" msgstr "Ingat saya" -#: lib/contents/login.inc.php:266 lib/contents/member.inc.php:934 +#: lib/contents/login.inc.php:266 lib/contents/member.inc.php:939 msgid "Login" msgstr "Masuk" @@ -8372,160 +8514,160 @@ msgstr "GAGAL Masuk! Nama Pengguna/Surel atau kata sandi salah!" msgid "Title has been added in the basket." msgstr "Pesanan sudah dimasukkan dalam keranjang." -#: lib/contents/member.inc.php:234 +#: lib/contents/member.inc.php:239 msgid "Your Membership Already EXPIRED! Please extend your membership." msgstr "" "Masa Berlaku Keanggotaan Anda sudah KEDALUWARSA! Harap perpanjang " "keanggotaan Anda." -#: lib/contents/member.inc.php:237 +#: lib/contents/member.inc.php:242 msgid "" "Membership currently in pending state, no loan transaction can be made yet." msgstr "" "Keanggotaan dalam status ditunda, tidak bisa melakukan transaksi peminjaman." -#: lib/contents/member.inc.php:283 +#: lib/contents/member.inc.php:288 msgid "Confirm Password" msgstr "Konfirmasi Kata Sandi" -#: lib/contents/member.inc.php:287 lib/contents/member.inc.php:795 +#: lib/contents/member.inc.php:292 lib/contents/member.inc.php:800 msgid "Change Password" msgstr "Ubah Kata Sandi" -#: lib/contents/member.inc.php:375 +#: lib/contents/member.inc.php:380 msgid "item(s) currently on loan" msgstr "eksemplar yang sedang dipinjam" -#: lib/contents/member.inc.php:375 +#: lib/contents/member.inc.php:380 msgid "Download All Current Loan" msgstr "Unduh Semua Pinjaman Terkini" -#: lib/contents/member.inc.php:384 +#: lib/contents/member.inc.php:389 msgid "OVERDUED" msgstr "TERLAMBAT" -#: lib/contents/member.inc.php:421 +#: lib/contents/member.inc.php:426 msgid "Download All Loan History" msgstr "Unduh Semua Sejarah Pinjaman" -#: lib/contents/member.inc.php:469 +#: lib/contents/member.inc.php:474 msgid "Reserve title(s) on Basket" msgstr "Kirim pesanan dalam Keranjang" -#: lib/contents/member.inc.php:470 +#: lib/contents/member.inc.php:475 msgid "Clear Basket" msgstr "Bersihkan Keranjang" -#: lib/contents/member.inc.php:471 +#: lib/contents/member.inc.php:476 msgid "Remove selected title(s) from Basket" msgstr "Hapus judul terpilih dari Keranjang" -#: lib/contents/member.inc.php:473 +#: lib/contents/member.inc.php:478 msgid "title(s) on basket" msgstr "judul dalam keranjang" -#: lib/contents/member.inc.php:584 +#: lib/contents/member.inc.php:589 #, php-format msgid "%s already reseved" msgstr "%s sudah dipesan" -#: lib/contents/member.inc.php:601 +#: lib/contents/member.inc.php:606 #, php-format msgid "Item for %s is available for loan" msgstr "Eksemplar %s tersedia untuk dipinjam" -#: lib/contents/member.inc.php:607 +#: lib/contents/member.inc.php:612 #, php-format msgid "%s reserved successfully" msgstr "%s berhasil dipesan" -#: lib/contents/member.inc.php:611 +#: lib/contents/member.inc.php:616 #, php-format msgid "Reserve %s failed. " msgstr "Gagal memesan %s. " -#: lib/contents/member.inc.php:617 +#: lib/contents/member.inc.php:622 #, php-format msgid "No item available to be reserved for %s" msgstr "Data eksemplar %s tidak tersedia untuk dipesan" -#: lib/contents/member.inc.php:624 +#: lib/contents/member.inc.php:629 msgid "No Titles to reserve" msgstr "Tidak ada judul untuk dipesan" -#: lib/contents/member.inc.php:631 +#: lib/contents/member.inc.php:636 msgid "Reservation not allowed" -msgstr "Tidak bisa dipesan" +msgstr "Anda tidak diizinkan untuk memesan" -#: lib/contents/member.inc.php:639 +#: lib/contents/member.inc.php:644 msgid "Reserve limit reached" -msgstr "Tidak bisa memesan" +msgstr "Pemesanan Anda sudah melebihi batas" -#: lib/contents/member.inc.php:640 +#: lib/contents/member.inc.php:645 #, php-format msgid "Maximum reserve limit is %d collection" msgstr "Batas maksimum pemesanan %d koleksi" -#: lib/contents/member.inc.php:670 +#: lib/contents/member.inc.php:675 msgid "Your password have been changed successfully." msgstr "Kata Sandi Anda sudah berhasil dirubah." -#: lib/contents/member.inc.php:673 +#: lib/contents/member.inc.php:678 msgid "Current password entered WRONG! Please insert the right password!" msgstr "" "Kata Sandi yang dimasukkan SALAH! Silahkan masukkan kata sandi yang benar!" -#: lib/contents/member.inc.php:675 +#: lib/contents/member.inc.php:680 msgid "" "Password confirmation FAILED! Make sure to check undercase or uppercase " "letters!" msgstr "Konfirmasi kata sandi GAGAL! Periksa ukuran huruf yang digunakan!" -#: lib/contents/member.inc.php:677 +#: lib/contents/member.inc.php:682 msgid "Password update FAILED! ERROR ON DATABASE!" msgstr "Perubahan kata sandi GAGAL! GALAT PADA PANGKALAN DATA!" -#: lib/contents/member.inc.php:693 +#: lib/contents/member.inc.php:698 msgid "Reservation e-mail sent successfully!" msgstr "Surel untuk reservasi berhasil dikirim!" -#: lib/contents/member.inc.php:740 +#: lib/contents/member.inc.php:745 msgid "Current Loan" msgstr "Pinjaman Terkini" -#: lib/contents/member.inc.php:744 +#: lib/contents/member.inc.php:749 msgid "Title Basket" msgstr "Keranjang Judul Anda" -#: lib/contents/member.inc.php:752 +#: lib/contents/member.inc.php:757 msgid "My Account" msgstr "Akun Saya" -#: lib/contents/member.inc.php:771 +#: lib/contents/member.inc.php:776 msgid "My Current Loan" msgstr "Pinjaman saya saat ini" -#: lib/contents/member.inc.php:777 +#: lib/contents/member.inc.php:782 msgid "My Title Basket" msgstr "Keranjang Judul saya" -#: lib/contents/member.inc.php:783 +#: lib/contents/member.inc.php:788 msgid "My Loan History" msgstr "Sejarah Peminjaman saya" -#: lib/contents/member.inc.php:789 +#: lib/contents/member.inc.php:794 msgid "Member Detail" msgstr "Detail Keanggotaan" -#: lib/contents/member.inc.php:896 +#: lib/contents/member.inc.php:901 msgid "Library Member Login" msgstr "Masuk Anggota Perpustakaan" -#: lib/contents/member.inc.php:900 +#: lib/contents/member.inc.php:905 msgid "Wrong Captcha Code entered, Please write the right code!" msgstr "Kode Captcha yang dimasukkan SALAH. Silahkan masukkan kode yang benar!" -#: lib/contents/member.inc.php:903 +#: lib/contents/member.inc.php:908 msgid "" "Please insert your member ID and password given by library system " "administrator. If you are library's member and don't have a password yet, " @@ -8601,7 +8743,7 @@ msgstr "Detail XML" #: lib/contents/show_detail.inc.php:119 #: template/akasia-dz/biblio_list_template.php:85 #: template/akasia/biblio_list_template.php:86 -#: template/default/biblio_list_template.php:120 +#: template/default/biblio_list_template.php:123 #: template/lightweight/biblio_list_template.php:85 msgid "Citation for: {title}" msgstr "Sitasi untuk: {title}" @@ -8610,43 +8752,43 @@ msgstr "Sitasi untuk: {title}" msgid "Cite this" msgstr "Kutip ini" -#: lib/contents/visitor.inc.php:161 +#: lib/contents/visitor.inc.php:166 msgid ", thank you for inserting your data to our visitor log" msgstr ", terimakasih telah memasukkan data Anda pada catatan pengunjung kami" -#: lib/contents/visitor.inc.php:163 +#: lib/contents/visitor.inc.php:168 msgid "" "Your membership already EXPIRED, please renew/extend your membership " "immediately" msgstr "" "Masa berlaku keanggotaan sudah BERAKHIR! Harap perpanjang keanggotaan anda" -#: lib/contents/visitor.inc.php:166 +#: lib/contents/visitor.inc.php:171 msgid "Welcome back" msgstr "Selamat datang kembali" -#: lib/contents/visitor.inc.php:168 +#: lib/contents/visitor.inc.php:173 msgid "Sorry, Please fill institution field if you are not library member" msgstr "Maaf, masukkan nama lembaga apabila Anda bukan anggota perpustakaan" -#: lib/contents/visitor.inc.php:170 +#: lib/contents/visitor.inc.php:175 msgid "Error inserting counter data to database!" msgstr "" "Terjadi galat dalam memasukkan data penghitung ke dalam pangkalan data!" -#: lib/contents/visitor.inc.php:186 +#: lib/contents/visitor.inc.php:194 msgid "Welcome to our library." msgstr "Selamat datang di perpustakaan kami." -#: lib/contents/visitor.inc.php:187 template/default/visitor_template.php:31 +#: lib/contents/visitor.inc.php:195 template/default/visitor_template.php:31 msgid "Please fill your member ID or name." msgstr "Harap isi ID anggota atau nama Anda." -#: lib/contents/visitor.inc.php:188 +#: lib/contents/visitor.inc.php:196 msgid "Error while inserting counter data to database." msgstr "Galat saat memasukkan data pengunjung ke dalam pangkalan data." -#: lib/contents/visitor.inc.php:266 template/akasia-dz/visitor_template.php:32 +#: lib/contents/visitor.inc.php:276 template/akasia-dz/visitor_template.php:32 #: template/akasia/visitor_template.php:32 #: template/lightweight/visitor_template.php:32 msgid "Visitor Counter" @@ -8672,9 +8814,9 @@ msgstr "Klik disini untuk mencari dokumen lain dari pengarang ini" msgid "Click to view others documents with this subject" msgstr "Klik di sini untuk mencari dokumen lain dengan subjek ini" -#: lib/detail.inc.php:462 template/akasia-dz/biblio_list_template.php:166 -#: template/akasia/biblio_list_template.php:167 -#: template/lightweight/biblio_list_template.php:166 +#: lib/detail.inc.php:462 template/akasia-dz/biblio_list_template.php:169 +#: template/akasia/biblio_list_template.php:170 +#: template/lightweight/biblio_list_template.php:169 msgid "Share to" msgstr "Bagikan" @@ -8838,83 +8980,83 @@ msgstr "Hal. Akhir" msgid "No Data" msgstr "Tidak Ada Data" -#: sysconfig.inc.php:687 +#: sysconfig.inc.php:694 msgid "Personal Name" msgstr "Nama Orang" -#: sysconfig.inc.php:688 +#: sysconfig.inc.php:695 msgid "Organizational Body" msgstr "Badan Organisasi" -#: sysconfig.inc.php:689 +#: sysconfig.inc.php:696 msgid "Conference" msgstr "Konferensi" -#: sysconfig.inc.php:692 +#: sysconfig.inc.php:699 msgid "Topic" msgstr "Topik" -#: sysconfig.inc.php:693 +#: sysconfig.inc.php:700 msgid "Geographic" msgstr "Geografis" -#: sysconfig.inc.php:695 +#: sysconfig.inc.php:702 msgid "Temporal" msgstr "Masa" -#: sysconfig.inc.php:696 +#: sysconfig.inc.php:703 msgid "Genre" msgstr "Aliran" -#: sysconfig.inc.php:697 +#: sysconfig.inc.php:704 msgid "Occupation" msgstr "Pekerjaan" -#: sysconfig.inc.php:700 +#: sysconfig.inc.php:707 msgid "Primary Author" msgstr "Pengarang Utama" -#: sysconfig.inc.php:701 +#: sysconfig.inc.php:708 msgid "Additional Author" msgstr "Pengarang Tambahan" -#: sysconfig.inc.php:702 +#: sysconfig.inc.php:709 msgid "Editor" msgstr "Penyunting" -#: sysconfig.inc.php:703 +#: sysconfig.inc.php:710 msgid "Translator" msgstr "Penerjemah" -#: sysconfig.inc.php:704 +#: sysconfig.inc.php:711 msgid "Director" msgstr "Direktur" -#: sysconfig.inc.php:705 +#: sysconfig.inc.php:712 msgid "Producer" msgstr "Produser" -#: sysconfig.inc.php:706 +#: sysconfig.inc.php:713 msgid "Composer" msgstr "Penggubah" -#: sysconfig.inc.php:707 +#: sysconfig.inc.php:714 msgid "Illustrator" msgstr "Ilustrator" -#: sysconfig.inc.php:708 +#: sysconfig.inc.php:715 msgid "Creator" msgstr "Pencipta" -#: sysconfig.inc.php:709 +#: sysconfig.inc.php:716 msgid "Contributor" msgstr "Kontributor" -#: sysconfig.inc.php:713 +#: sysconfig.inc.php:720 msgid "Senior Librarian" msgstr "Pustakawan Senior" -#: sysconfig.inc.php:714 +#: sysconfig.inc.php:721 msgid "Library Staff" msgstr "Staf Perpustakaan" @@ -8922,7 +9064,7 @@ msgstr "Staf Perpustakaan" #: template/akasia-dz/biblio_list_template.php:79 #: template/akasia/biblio_list_template.php:50 #: template/akasia/biblio_list_template.php:80 -#: template/default/biblio_list_template.php:99 +#: template/default/biblio_list_template.php:102 #: template/lightweight/biblio_list_template.php:50 #: template/lightweight/biblio_list_template.php:79 msgid "View record detail description for this title" @@ -8936,68 +9078,68 @@ msgstr "Tampilkan penjelasan lengkap dalam Format XML" #: template/akasia-dz/biblio_list_template.php:85 #: template/akasia/biblio_list_template.php:86 -#: template/default/biblio_list_template.php:120 +#: template/default/biblio_list_template.php:123 #: template/lightweight/biblio_list_template.php:85 msgid "Cite" msgstr "Sitasi" -#: template/akasia-dz/biblio_list_template.php:144 -#: template/akasia/biblio_list_template.php:145 -#: template/lightweight/biblio_list_template.php:144 +#: template/akasia-dz/biblio_list_template.php:147 +#: template/akasia/biblio_list_template.php:148 +#: template/lightweight/biblio_list_template.php:147 msgid "none copy available" msgstr "tidak ada kopi yang tersedia" -#: template/akasia-dz/biblio_list_template.php:146 -#: template/akasia/biblio_list_template.php:147 -#: template/lightweight/biblio_list_template.php:146 +#: template/akasia-dz/biblio_list_template.php:149 +#: template/akasia/biblio_list_template.php:150 +#: template/lightweight/biblio_list_template.php:149 msgid "{numberAvailable} copies available for loan" msgstr "{numberAvailable} koleksi tersedia untuk dipinjam" -#: template/akasia-dz/biblio_list_template.php:158 -#: template/akasia/biblio_list_template.php:159 -#: template/lightweight/biblio_list_template.php:158 +#: template/akasia-dz/biblio_list_template.php:161 +#: template/akasia/biblio_list_template.php:162 +#: template/lightweight/biblio_list_template.php:161 msgid "mark this" msgstr "tandai ini" -#: template/akasia-dz/biblio_list_template.php:167 -#: template/akasia/biblio_list_template.php:168 -#: template/lightweight/biblio_list_template.php:167 +#: template/akasia-dz/biblio_list_template.php:170 +#: template/akasia/biblio_list_template.php:171 +#: template/lightweight/biblio_list_template.php:170 msgid "Share this title to Facebook" msgstr "Bagikan ke Facebook" -#: template/akasia-dz/biblio_list_template.php:168 -#: template/akasia/biblio_list_template.php:169 -#: template/lightweight/biblio_list_template.php:168 +#: template/akasia-dz/biblio_list_template.php:171 +#: template/akasia/biblio_list_template.php:172 +#: template/lightweight/biblio_list_template.php:171 msgid "Share this title to Twitter" msgstr "Bagikan ke Twitter" -#: template/akasia-dz/biblio_list_template.php:169 -#: template/akasia/biblio_list_template.php:170 -#: template/lightweight/biblio_list_template.php:169 +#: template/akasia-dz/biblio_list_template.php:172 +#: template/akasia/biblio_list_template.php:173 +#: template/lightweight/biblio_list_template.php:172 msgid "Share this title to Google Plus" msgstr "Bagikan ke Google Plus" -#: template/akasia-dz/biblio_list_template.php:170 -#: template/akasia/biblio_list_template.php:171 -#: template/lightweight/biblio_list_template.php:170 +#: template/akasia-dz/biblio_list_template.php:173 +#: template/akasia/biblio_list_template.php:174 +#: template/lightweight/biblio_list_template.php:173 msgid "Share this title to Digg It" msgstr "Bagikan ke Digg It" -#: template/akasia-dz/biblio_list_template.php:171 -#: template/akasia/biblio_list_template.php:172 -#: template/lightweight/biblio_list_template.php:171 +#: template/akasia-dz/biblio_list_template.php:174 +#: template/akasia/biblio_list_template.php:175 +#: template/lightweight/biblio_list_template.php:174 msgid "Share this title to Reddit" msgstr "Bagikan ke Reddit" -#: template/akasia-dz/biblio_list_template.php:172 -#: template/akasia/biblio_list_template.php:173 -#: template/lightweight/biblio_list_template.php:172 +#: template/akasia-dz/biblio_list_template.php:175 +#: template/akasia/biblio_list_template.php:176 +#: template/lightweight/biblio_list_template.php:175 msgid "Share this title to LinkedIn" msgstr "Bagikan ke LinkedIn" -#: template/akasia-dz/biblio_list_template.php:173 -#: template/akasia/biblio_list_template.php:174 -#: template/lightweight/biblio_list_template.php:173 +#: template/akasia-dz/biblio_list_template.php:176 +#: template/akasia/biblio_list_template.php:177 +#: template/lightweight/biblio_list_template.php:176 msgid "Share this title to StumbleUpon" msgstr "Bagikan ke StumbleUpon" @@ -9033,7 +9175,7 @@ msgstr "Gaya Turabian" #: template/akasia-dz/detail_template.php:37 #: template/akasia/custom_frontpage_record.inc.php:11 #: template/akasia/detail_template.php:37 -#: template/default/biblio_list_template.php:110 +#: template/default/biblio_list_template.php:113 #: template/default/detail_template.php:31 #: template/lightweight/custom_frontpage_record.inc.php:11 #: template/lightweight/detail_template.php:37 @@ -9232,11 +9374,11 @@ msgstr "Informasi Lainnya" msgid "Advanced Search" msgstr "Pencarian Spesifik" -#: template/default/biblio_list_template.php:114 +#: template/default/biblio_list_template.php:117 msgid "Add to basket" msgstr "Tambahkan ke dalam keranjang" -#: template/default/biblio_list_template.php:119 +#: template/default/biblio_list_template.php:122 msgid "View Detail" msgstr "Tampilkan Detail" @@ -9550,6 +9692,178 @@ msgstr "Masuk" msgid "Put some keyword(s)..." msgstr "Masukkan kata kunci..." +#~ msgid "" +#~ "You currently on page {page} of {total_pages} page(s)" +#~ msgstr "" +#~ "Saat ini anda berada pada halaman {page} dari total " +#~ "{total_pages} halaman" + +#~ msgid "Did you mean:" +#~ msgstr "Yang Anda maksud:" + +#~ msgid "Send" +#~ msgstr "Kirim" + +#~ msgid "Telegram Account" +#~ msgstr "Akun Telegram" + +#~ msgid "Telegram Username" +#~ msgstr "Nama Pengguna Telegram" + +#~ msgid "Direct Message" +#~ msgstr "Pesan Langsung" + +#~ msgid "Write Message" +#~ msgstr "Tulis Pesan" + +#~ msgid "Question or Response can't be empty" +#~ msgstr "Pertanyaan atau Tanggapan tidak boleh dikosongkan" + +#~ msgid "Telegram Auto Response" +#~ msgstr "Tanggapan Automatis Telegram" + +#~ msgid "Question List" +#~ msgstr "Daftar Pertanyaan" + +#, fuzzy +#~| msgid "Add New Subscription" +#~ msgid "Add New Question" +#~ msgstr "Tambah Data Berlangganan" + +#, fuzzy +#~| msgid "Suggestion" +#~ msgid "Question" +#~ msgstr "Saran" + +#, fuzzy, php-format +#~| msgid "Welcome to our library." +#~ msgid "Welcome to %s library" +#~ msgstr "Selamat datang di perpustakaan kami." + +#, fuzzy +#~| msgid "My Account" +#~ msgid "Your Account :" +#~ msgstr "Akun Saya" + +#, fuzzy, php-format +#~| msgid "Member ID" +#~ msgid "Member ID : %s" +#~ msgstr "ID Anggota" + +#, fuzzy, php-format +#~| msgid "Member Name" +#~ msgid "Member Name : %s" +#~ msgstr "Nama Anggota" + +#, fuzzy +#~| msgid "Insert Item Code/Barcode" +#~ msgid "Insert Item Code" +#~ msgstr "Masukkan Kode Eksemplar/Barkod" + +#, fuzzy +#~| msgid "This Item is not registered in database" +#~ msgid "Item not registered in database" +#~ msgstr "Eksemplar ini tidak terdaftar dalam pangkalan data" + +#, fuzzy +#~| msgid "Transaction finished" +#~ msgid "Transaction Aborted" +#~ msgstr "Transaksi Selesai" + +#, fuzzy +#~| msgid "%s already reseved" +#~ msgid "Account already registered" +#~ msgstr "%s sudah dipesan" + +#, fuzzy +#~| msgid "Enter your member ID" +#~ msgid "Insert your username" +#~ msgstr "Masukkan ID anggota Anda" + +#, fuzzy +#~| msgid "Status" +#~ msgid "Status : " +#~ msgstr "Status" + +#, fuzzy +#~| msgid "Current Loans" +#~ msgid "Current Fines" +#~ msgstr "Pinjaman Saat Ini" + +#~ msgid "Debet" +#~ msgstr "Debit" + +#, fuzzy +#~| msgid "Title can not be empty" +#~ msgid "TOKEN and Bot Name can not be empty" +#~ msgstr "Judul tidak boleh kosong" + +#, fuzzy +#~| msgid "Shortcut Settings" +#~ msgid "Bot Settings" +#~ msgstr "Pengaturan Pemintas" + +#, fuzzy +#~| msgid "Modify UCS preferences" +#~ msgid "Modify telegram bot preferences" +#~ msgstr "Ubah Preferensi UCS" + +#, fuzzy +#~| msgid "Item Status" +#~ msgid "Bot Telegram Status" +#~ msgstr "Status Eksemplar" + +#, fuzzy +#~| msgid "Self Location" +#~ msgid "Self Activation" +#~ msgstr "Lokasi Rak" + +#, fuzzy +#~| msgid "Self Location" +#~ msgid "Self Loan Extension" +#~ msgstr "Lokasi Rak" + +#, fuzzy +#~| msgid "Self Location" +#~ msgid "Self Booking" +#~ msgstr "Lokasi Rak" + +#, fuzzy +#~| msgid "Print Circulation Receipt" +#~ msgid "Circulation Receipt" +#~ msgstr "Cetak Bukti Sirkulasi" + +#, fuzzy +#~| msgid "Send Notification e-mail" +#~ msgid "Visiting Notification" +#~ msgstr "Kirim surel Pemberitahuan" + +#, fuzzy +#~| msgid "Due Date Warning" +#~ msgid "Overdue Warning" +#~ msgstr "Peringatan Jatuh Tempo" + +#, fuzzy +#~| msgid "Overdue" +#~ msgid "Overdue Notice" +#~ msgstr "Keterlambatan" + +#, fuzzy +#~| msgid "Location Name" +#~ msgid "Bot Name" +#~ msgstr "Nama Lokasi" + +#, fuzzy +#~| msgid "Collections" +#~ msgid "Max Connections" +#~ msgstr "Koleksi" + +#, fuzzy +#~| msgid "Author added!" +#~ msgid "Bot Authorized!" +#~ msgstr "Pengarang berhasil ditambahkan!" + #~ msgid "SYSTEM CONFIG" #~ msgstr "KONFIGURASI SISTEM" @@ -9608,11 +9922,6 @@ msgstr "Masukkan kata kunci..." #~ msgid "Add to print queue" #~ msgstr "Tambahkan dalam antrian cetak?" -#, fuzzy -#~| msgid "UCS Configuration" -#~ msgid "Global Configuration" -#~ msgstr "Pengaturan UCS" - #~ msgid "Fonts" #~ msgstr "Fonta" @@ -9873,9 +10182,6 @@ msgstr "Masukkan kata kunci..." #~ msgid "{recordCount} records inserted to database." #~ msgstr "{recordCount} data berhasil disimpan ke dalam basisdata." -#~ msgid "Debet" -#~ msgstr "Debit" - #~ msgid "Goto backup tools" #~ msgstr "Buat Cadangan Pangkalan Data" diff --git a/lib/maennchen/zipstream-php/CHANGELOG.md b/lib/maennchen/zipstream-php/CHANGELOG.md new file mode 100644 index 00000000..b1979abc --- /dev/null +++ b/lib/maennchen/zipstream-php/CHANGELOG.md @@ -0,0 +1,51 @@ +# CHANGELOG for ZipStream-PHP + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [2.1.0] - 2020-06-01 +### Changed +- Don't execute ob_flush() when output buffering is not enabled (#152) +- Fix inconsistent return type on 32-bit systems (#149) Fix #144 +- Use mbstring polyfill (#151) +- Promote 7zip usage over unzip to avoid UTF-8 issues (#147) + +## [2.0.0] - 2020-02-22 +### Breaking change +- Only the self opened streams will be closed (#139) +If you were relying on ZipStream to close streams that the library didn't open, +you'll need to close them yourself now. + +### Changed +- Minor change to data descriptor (#136) + +## [1.2.0] - 2019-07-11 + +### Added +- Option to flush output buffer after every write (#122) + +## [1.1.0] - 2019-04-30 + +### Fixed +- Honor last-modified timestamps set via `ZipStream\Option\File::setTime()` (#106) +- Documentation regarding output of HTTP headers +- Test warnings with PHPUnit (#109) + +### Added +- Test for FileNotReadableException (#114) +- Size attribute to File options (#113) +- Tests on PHP 7.3 (#108) + +## [1.0.0] - 2019-04-17 + +### Breaking changes +- Mininum PHP version is now 7.1 +- Options are now passed to the ZipStream object via the Option\Archive object. See the wiki for available options and code examples + +### Added +- Add large file support with Zip64 headers + +### Changed +- Major refactoring and code cleanup diff --git a/lib/maennchen/zipstream-php/CONTRIBUTING.md b/lib/maennchen/zipstream-php/CONTRIBUTING.md new file mode 100644 index 00000000..f8ef5a57 --- /dev/null +++ b/lib/maennchen/zipstream-php/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# ZipStream Readme for Contributors +## Code styling +### Indention +For spaces are used to indent code. The convention is [K&R](http://en.wikipedia.org/wiki/Indent_style#K&R) + +### Comments +Double Slashes are used for an one line comment. + +Classes, Variables, Methods etc: + +```php +/** + * My comment + * + * @myanotation like @param etc. + */ +``` + +## Pull requests +Feel free to submit pull requests. + +## Testing +For every new feature please write a new PHPUnit test. + +Before every commit execute `./vendor/bin/phpunit` to check if your changes wrecked something: diff --git a/lib/maennchen/zipstream-php/LICENSE b/lib/maennchen/zipstream-php/LICENSE new file mode 100644 index 00000000..ebe7fe2f --- /dev/null +++ b/lib/maennchen/zipstream-php/LICENSE @@ -0,0 +1,24 @@ +MIT License + +Copyright (C) 2007-2009 Paul Duncan +Copyright (C) 2014 Jonatan Männchen +Copyright (C) 2014 Jesse G. Donat +Copyright (C) 2018 Nicolas CARPi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/maennchen/zipstream-php/README.md b/lib/maennchen/zipstream-php/README.md new file mode 100644 index 00000000..c489867d --- /dev/null +++ b/lib/maennchen/zipstream-php/README.md @@ -0,0 +1,124 @@ +# ZipStream-PHP + +![.github/workflows/php.yml](https://github.com/maennchen/ZipStream-PHP/workflows/.github/workflows/php.yml/badge.svg) +[![Coverage Status](https://coveralls.io/repos/github/maennchen/ZipStream-PHP/badge.svg?branch=master)](https://coveralls.io/github/maennchen/ZipStream-PHP?branch=master) +[![Latest Stable Version](https://poser.pugx.org/maennchen/zipstream-php/v/stable)](https://packagist.org/packages/maennchen/zipstream-php) +[![Total Downloads](https://poser.pugx.org/maennchen/zipstream-php/downloads)](https://packagist.org/packages/maennchen/zipstream-php) +[![Financial Contributors on Open Collective](https://opencollective.com/zipstream/all/badge.svg?label=financial+contributors)](https://opencollective.com/zipstream) [![License](https://img.shields.io/github/license/maennchen/zipstream-php.svg)](LICENSE) + +## Overview + +A fast and simple streaming zip file downloader for PHP. Using this library will save you from having to write the Zip to disk. You can directly send it to the user, which is much faster. It can work with S3 buckets or any PSR7 Stream. + +Please see the [LICENSE](LICENSE) file for licensing and warranty information. + +## Installation + +Simply add a dependency on maennchen/zipstream-php to your project's composer.json file if you use Composer to manage the dependencies of your project. Use following command to add the package to your project's dependencies: + +```bash +composer require maennchen/zipstream-php +``` + +## Usage and options + +Here's a simple example: + +```php +// Autoload the dependencies +require 'vendor/autoload.php'; + +// enable output of HTTP headers +$options = new ZipStream\Option\Archive(); +$options->setSendHttpHeaders(true); + +// create a new zipstream object +$zip = new ZipStream\ZipStream('example.zip', $options); + +// create a file named 'hello.txt' +$zip->addFile('hello.txt', 'This is the contents of hello.txt'); + +// add a file named 'some_image.jpg' from a local file 'path/to/image.jpg' +$zip->addFileFromPath('some_image.jpg', 'path/to/image.jpg'); + +// add a file named 'goodbye.txt' from an open stream resource +$fp = tmpfile(); +fwrite($fp, 'The quick brown fox jumped over the lazy dog.'); +rewind($fp); +$zip->addFileFromStream('goodbye.txt', $fp); +fclose($fp); + +// finish the zip stream +$zip->finish(); +``` + +You can also add comments, modify file timestamps, and customize (or +disable) the HTTP headers. It is also possible to specify the storage method when adding files, +the current default storage method is 'deflate' i.e files are stored with Compression mode 0x08. + +See the [Wiki](https://github.com/maennchen/ZipStream-PHP/wiki) for details. + +## Known issues + +The native Mac OS archive extraction tool prior to macOS 10.15 might not open archives in some conditions. A workaround is to disable the Zip64 feature with the option `$opt->setEnableZip64(false)`. This limits the archive to 4 Gb and 64k files but will allow users on macOS 10.14 and below to open them without issue. See #116. + +The linux `unzip` utility might not handle properly unicode characters. It is recommended to extract with another tool like [7-zip](https://www.7-zip.org/). See [#146](https://github.com/maennchen/ZipStream-PHP/issues/146). + +It is the responsability of the client code to make sure that files are not saved with the same path, as it is not possible for the library to figure it out while streaming a zip. See [#154](https://github.com/maennchen/ZipStream-PHP/issues/154). + +## Upgrade to version 2.0.0 + +* Only the self opened streams will be closed (#139) +If you were relying on ZipStream to close streams that the library didn't open, +you'll need to close them yourself now. + +## Upgrade to version 1.0.0 + +* All options parameters to all function have been moved from an `array` to structured option objects. See [the wiki](https://github.com/maennchen/ZipStream-PHP/wiki/Available-options) for examples. +* The whole library has been refactored. The minimal PHP requirement has been raised to PHP 7.1. + +## Usage with Symfony and S3 + +You can find example code on [the wiki](https://github.com/maennchen/ZipStream-PHP/wiki/Symfony-example). + +## Contributing + +ZipStream-PHP is a collaborative project. Please take a look at the [CONTRIBUTING.md](CONTRIBUTING.md) file. + +## About the Authors + +* Paul Duncan - https://pablotron.org/ +* Jonatan Männchen - https://maennchen.dev +* Jesse G. Donat - https://donatstudios.com +* Nicolas CARPi - https://www.deltablot.com +* Nik Barham - https://www.brokencube.co.uk + +## Contributors + +### Code Contributors + +This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. + + +### Financial Contributors + +Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/zipstream/contribute)] + +#### Individuals + + + +#### Organizations + +Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/zipstream/contribute)] + + + + + + + + + + + diff --git a/lib/maennchen/zipstream-php/composer.json b/lib/maennchen/zipstream-php/composer.json new file mode 100644 index 00000000..78943cf8 --- /dev/null +++ b/lib/maennchen/zipstream-php/composer.json @@ -0,0 +1,46 @@ +{ + "name": "maennchen/zipstream-php", + "description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.", + "keywords": ["zip", "stream"], + "type": "library", + "license": "MIT", + "authors": [{ + "name": "Paul Duncan", + "email": "pabs@pablotron.org" + }, + { + "name": "Jonatan Männchen", + "email": "jonatan@maennchen.ch" + }, + { + "name": "Jesse Donat", + "email": "donatj@gmail.com" + }, + { + "name": "András Kolesár", + "email": "kolesar@kolesar.hu" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "symfony/polyfill-mbstring": "^1.0", + "psr/http-message": "^1.0", + "myclabs/php-enum": "^1.5" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.8 || ^9.4.2", + "guzzlehttp/guzzle": "^6.5.3 || ^7.2.0", + "ext-zip": "*", + "mikey179/vfsstream": "^1.6", + "vimeo/psalm": "^4.1", + "php-coveralls/php-coveralls": "^2.4" + }, + "autoload": { + "psr-4": { + "ZipStream\\": "src/" + } + }, + "archive": { + "exclude": ["/test", "/CHANGELOG.md", "/CONTRIBUTING.md", "/phpunit.xml.dist", "/psalm.xml"] + } +} diff --git a/lib/maennchen/zipstream-php/phpunit.xml.dist b/lib/maennchen/zipstream-php/phpunit.xml.dist new file mode 100644 index 00000000..8a2f3188 --- /dev/null +++ b/lib/maennchen/zipstream-php/phpunit.xml.dist @@ -0,0 +1,14 @@ + + + + + src + + + + + test + + + + diff --git a/lib/math/psalm.xml b/lib/maennchen/zipstream-php/psalm.xml similarity index 93% rename from lib/math/psalm.xml rename to lib/maennchen/zipstream-php/psalm.xml index 123263ef..4e4c4f60 100644 --- a/lib/math/psalm.xml +++ b/lib/maennchen/zipstream-php/psalm.xml @@ -1,11 +1,9 @@ @@ -35,7 +33,6 @@ - diff --git a/lib/maennchen/zipstream-php/src/Bigint.php b/lib/maennchen/zipstream-php/src/Bigint.php new file mode 100644 index 00000000..ff84d0d5 --- /dev/null +++ b/lib/maennchen/zipstream-php/src/Bigint.php @@ -0,0 +1,173 @@ +fillBytes($value, 0, 8); + } + + /** + * Fill the bytes field with int + * + * @param int $value + * @param int $start + * @param int $count + * @return void + */ + protected function fillBytes(int $value, int $start, int $count): void + { + for ($i = 0; $i < $count; $i++) { + $this->bytes[$start + $i] = $i >= PHP_INT_SIZE ? 0 : $value & 0xFF; + $value >>= 8; + } + } + + /** + * Get an instance + * + * @param int $value + * @return Bigint + */ + public static function init(int $value = 0): self + { + return new self($value); + } + + /** + * Fill bytes from low to high + * + * @param int $low + * @param int $high + * @return Bigint + */ + public static function fromLowHigh(int $low, int $high): self + { + $bigint = new Bigint(); + $bigint->fillBytes($low, 0, 4); + $bigint->fillBytes($high, 4, 4); + return $bigint; + } + + /** + * Get high 32 + * + * @return int + */ + public function getHigh32(): int + { + return $this->getValue(4, 4); + } + + /** + * Get value from bytes array + * + * @param int $end + * @param int $length + * @return int + */ + public function getValue(int $end = 0, int $length = 8): int + { + $result = 0; + for ($i = $end + $length - 1; $i >= $end; $i--) { + $result <<= 8; + $result |= $this->bytes[$i]; + } + return $result; + } + + /** + * Get low FF + * + * @param bool $force + * @return float + */ + public function getLowFF(bool $force = false): float + { + if ($force || $this->isOver32()) { + return (float)0xFFFFFFFF; + } + return (float)$this->getLow32(); + } + + /** + * Check if is over 32 + * + * @psalm-suppress ArgumentTypeCoercion + * @param bool $force + * @return bool + */ + public function isOver32(bool $force = false): bool + { + // value 0xFFFFFFFF already needs a Zip64 header + return $force || + max(array_slice($this->bytes, 4, 4)) > 0 || + min(array_slice($this->bytes, 0, 4)) === 0xFF; + } + + /** + * Get low 32 + * + * @return int + */ + public function getLow32(): int + { + return $this->getValue(0, 4); + } + + /** + * Get hexadecimal + * + * @return string + */ + public function getHex64(): string + { + $result = '0x'; + for ($i = 7; $i >= 0; $i--) { + $result .= sprintf('%02X', $this->bytes[$i]); + } + return $result; + } + + /** + * Add + * + * @param Bigint $other + * @return Bigint + */ + public function add(Bigint $other): Bigint + { + $result = clone $this; + $overflow = false; + for ($i = 0; $i < 8; $i++) { + $result->bytes[$i] += $other->bytes[$i]; + if ($overflow) { + $result->bytes[$i]++; + $overflow = false; + } + if ($result->bytes[$i] & 0x100) { + $overflow = true; + $result->bytes[$i] &= 0xFF; + } + } + if ($overflow) { + throw new OverflowException; + } + return $result; + } +} diff --git a/lib/maennchen/zipstream-php/src/DeflateStream.php b/lib/maennchen/zipstream-php/src/DeflateStream.php new file mode 100644 index 00000000..d6c27288 --- /dev/null +++ b/lib/maennchen/zipstream-php/src/DeflateStream.php @@ -0,0 +1,70 @@ +filter) { + $this->removeDeflateFilter(); + $this->seek(0); + $this->addDeflateFilter($this->options); + } else { + rewind($this->stream); + } + } + + /** + * Remove the deflate filter + * + * @return void + */ + public function removeDeflateFilter(): void + { + if (!$this->filter) { + return; + } + stream_filter_remove($this->filter); + $this->filter = null; + } + + /** + * Add a deflate filter + * + * @param Option\File $options + * @return void + */ + public function addDeflateFilter(Option\File $options): void + { + $this->options = $options; + // parameter 4 for stream_filter_append expects array + // so we convert the option object in an array + $optionsArr = [ + 'comment' => $options->getComment(), + 'method' => $options->getMethod(), + 'deflateLevel' => $options->getDeflateLevel(), + 'time' => $options->getTime() + ]; + $this->filter = stream_filter_append( + $this->stream, + 'zlib.deflate', + STREAM_FILTER_READ, + $optionsArr + ); + } +} diff --git a/lib/maennchen/zipstream-php/src/Exception.php b/lib/maennchen/zipstream-php/src/Exception.php new file mode 100644 index 00000000..18ccfbbd --- /dev/null +++ b/lib/maennchen/zipstream-php/src/Exception.php @@ -0,0 +1,11 @@ +zip = $zip; + + $this->name = $name; + $this->opt = $opt ?: new FileOptions(); + $this->method = $this->opt->getMethod(); + $this->version = Version::STORE(); + $this->ofs = new Bigint(); + } + + public function processPath(string $path): void + { + if (!is_readable($path)) { + if (!file_exists($path)) { + throw new FileNotFoundException($path); + } + throw new FileNotReadableException($path); + } + if ($this->zip->isLargeFile($path) === false) { + $data = file_get_contents($path); + $this->processData($data); + } else { + $this->method = $this->zip->opt->getLargeFileMethod(); + + $stream = new DeflateStream(fopen($path, 'rb')); + $this->processStream($stream); + $stream->close(); + } + } + + public function processData(string $data): void + { + $this->len = new Bigint(strlen($data)); + $this->crc = crc32($data); + + // compress data if needed + if ($this->method->equals(Method::DEFLATE())) { + $data = gzdeflate($data); + } + + $this->zlen = new Bigint(strlen($data)); + $this->addFileHeader(); + $this->zip->send($data); + $this->addFileFooter(); + } + + /** + * Create and send zip header for this file. + * + * @return void + * @throws \ZipStream\Exception\EncodingException + */ + public function addFileHeader(): void + { + $name = static::filterFilename($this->name); + + // calculate name length + $nameLength = strlen($name); + + // create dos timestamp + $time = static::dosTime($this->opt->getTime()->getTimestamp()); + + $comment = $this->opt->getComment(); + + if (!mb_check_encoding($name, 'ASCII') || + !mb_check_encoding($comment, 'ASCII')) { + // Sets Bit 11: Language encoding flag (EFS). If this bit is set, + // the filename and comment fields for this file + // MUST be encoded using UTF-8. (see APPENDIX D) + if (!mb_check_encoding($name, 'UTF-8') || + !mb_check_encoding($comment, 'UTF-8')) { + throw new EncodingException( + 'File name and comment should use UTF-8 ' . + 'if one of them does not fit into ASCII range.' + ); + } + $this->bits |= self::BIT_EFS_UTF8; + } + + if ($this->method->equals(Method::DEFLATE())) { + $this->version = Version::DEFLATE(); + } + + $force = (boolean)($this->bits & self::BIT_ZERO_HEADER) && + $this->zip->opt->isEnableZip64(); + + $footer = $this->buildZip64ExtraBlock($force); + + // If this file will start over 4GB limit in ZIP file, + // CDR record will have to use Zip64 extension to describe offset + // to keep consistency we use the same value here + if ($this->zip->ofs->isOver32()) { + $this->version = Version::ZIP64(); + } + + $fields = [ + ['V', ZipStream::FILE_HEADER_SIGNATURE], + ['v', $this->version->getValue()], // Version needed to Extract + ['v', $this->bits], // General purpose bit flags - data descriptor flag set + ['v', $this->method->getValue()], // Compression method + ['V', $time], // Timestamp (DOS Format) + ['V', $this->crc], // CRC32 of data (0 -> moved to data descriptor footer) + ['V', $this->zlen->getLowFF($force)], // Length of compressed data (forced to 0xFFFFFFFF for zero header) + ['V', $this->len->getLowFF($force)], // Length of original data (forced to 0xFFFFFFFF for zero header) + ['v', $nameLength], // Length of filename + ['v', strlen($footer)], // Extra data (see above) + ]; + + // pack fields and calculate "total" length + $header = ZipStream::packFields($fields); + + // print header and filename + $data = $header . $name . $footer; + $this->zip->send($data); + + // save header length + $this->hlen = Bigint::init(strlen($data)); + } + + /** + * Strip characters that are not legal in Windows filenames + * to prevent compatibility issues + * + * @param string $filename Unprocessed filename + * @return string + */ + public static function filterFilename(string $filename): string + { + // strip leading slashes from file name + // (fixes bug in windows archive viewer) + $filename = preg_replace('/^\\/+/', '', $filename); + + return str_replace(['\\', ':', '*', '?', '"', '<', '>', '|'], '_', $filename); + } + + /** + * Convert a UNIX timestamp to a DOS timestamp. + * + * @param int $when + * @return int DOS Timestamp + */ + final protected static function dosTime(int $when): int + { + // get date array for timestamp + $d = getdate($when); + + // set lower-bound on dates + if ($d['year'] < 1980) { + $d = array( + 'year' => 1980, + 'mon' => 1, + 'mday' => 1, + 'hours' => 0, + 'minutes' => 0, + 'seconds' => 0 + ); + } + + // remove extra years from 1980 + $d['year'] -= 1980; + + // return date string + return + ($d['year'] << 25) | + ($d['mon'] << 21) | + ($d['mday'] << 16) | + ($d['hours'] << 11) | + ($d['minutes'] << 5) | + ($d['seconds'] >> 1); + } + + protected function buildZip64ExtraBlock(bool $force = false): string + { + + $fields = []; + if ($this->len->isOver32($force)) { + $fields[] = ['P', $this->len]; // Length of original data + } + + if ($this->len->isOver32($force)) { + $fields[] = ['P', $this->zlen]; // Length of compressed data + } + + if ($this->ofs->isOver32()) { + $fields[] = ['P', $this->ofs]; // Offset of local header record + } + + if (!empty($fields)) { + if (!$this->zip->opt->isEnableZip64()) { + throw new OverflowException(); + } + + array_unshift( + $fields, + ['v', 0x0001], // 64 bit extension + ['v', count($fields) * 8] // Length of data block + ); + $this->version = Version::ZIP64(); + } + + if ($this->bits & self::BIT_EFS_UTF8) { + // Put the tricky entry to + // force Linux unzip to lookup EFS flag. + $fields[] = ['v', 0x5653]; // Choose 'ZS' for proprietary usage + $fields[] = ['v', 0x0000]; // zero length + } + + return ZipStream::packFields($fields); + } + + /** + * Create and send data descriptor footer for this file. + * + * @return void + */ + + public function addFileFooter(): void + { + + if ($this->bits & self::BIT_ZERO_HEADER) { + // compressed and uncompressed size + $sizeFormat = 'V'; + if ($this->zip->opt->isEnableZip64()) { + $sizeFormat = 'P'; + } + $fields = [ + ['V', ZipStream::DATA_DESCRIPTOR_SIGNATURE], + ['V', $this->crc], // CRC32 + [$sizeFormat, $this->zlen], // Length of compressed data + [$sizeFormat, $this->len], // Length of original data + ]; + + $footer = ZipStream::packFields($fields); + $this->zip->send($footer); + } else { + $footer = ''; + } + $this->totalLength = $this->hlen->add($this->zlen)->add(Bigint::init(strlen($footer))); + $this->zip->addToCdr($this); + } + + public function processStream(StreamInterface $stream): void + { + $this->zlen = new Bigint(); + $this->len = new Bigint(); + + if ($this->zip->opt->isZeroHeader()) { + $this->processStreamWithZeroHeader($stream); + } else { + $this->processStreamWithComputedHeader($stream); + } + } + + protected function processStreamWithZeroHeader(StreamInterface $stream): void + { + $this->bits |= self::BIT_ZERO_HEADER; + $this->addFileHeader(); + $this->readStream($stream, self::COMPUTE | self::SEND); + $this->addFileFooter(); + } + + protected function readStream(StreamInterface $stream, ?int $options = null): void + { + $this->deflateInit(); + $total = 0; + $size = $this->opt->getSize(); + while (!$stream->eof() && ($size === 0 || $total < $size)) { + $data = $stream->read(self::CHUNKED_READ_BLOCK_SIZE); + $total += strlen($data); + if ($size > 0 && $total > $size) { + $data = substr($data, 0 , strlen($data)-($total - $size)); + } + $this->deflateData($stream, $data, $options); + if ($options & self::SEND) { + $this->zip->send($data); + } + } + $this->deflateFinish($options); + } + + protected function deflateInit(): void + { + $hash = hash_init(self::HASH_ALGORITHM); + $this->hash = $hash; + if ($this->method->equals(Method::DEFLATE())) { + $this->deflate = deflate_init( + ZLIB_ENCODING_RAW, + ['level' => $this->opt->getDeflateLevel()] + ); + } + } + + protected function deflateData(StreamInterface $stream, string &$data, ?int $options = null): void + { + if ($options & self::COMPUTE) { + $this->len = $this->len->add(Bigint::init(strlen($data))); + hash_update($this->hash, $data); + } + if ($this->deflate) { + $data = deflate_add( + $this->deflate, + $data, + $stream->eof() + ? ZLIB_FINISH + : ZLIB_NO_FLUSH + ); + } + if ($options & self::COMPUTE) { + $this->zlen = $this->zlen->add(Bigint::init(strlen($data))); + } + } + + protected function deflateFinish(?int $options = null): void + { + if ($options & self::COMPUTE) { + $this->crc = hexdec(hash_final($this->hash)); + } + } + + protected function processStreamWithComputedHeader(StreamInterface $stream): void + { + $this->readStream($stream, self::COMPUTE); + $stream->rewind(); + + // incremental compression with deflate_add + // makes this second read unnecessary + // but it is only available from PHP 7.0 + if (!$this->deflate && $stream instanceof DeflateStream && $this->method->equals(Method::DEFLATE())) { + $stream->addDeflateFilter($this->opt); + $this->zlen = new Bigint(); + while (!$stream->eof()) { + $data = $stream->read(self::CHUNKED_READ_BLOCK_SIZE); + $this->zlen = $this->zlen->add(Bigint::init(strlen($data))); + } + $stream->rewind(); + } + + $this->addFileHeader(); + $this->readStream($stream, self::SEND); + $this->addFileFooter(); + } + + /** + * Send CDR record for specified file. + * + * @return string + */ + public function getCdrFile(): string + { + $name = static::filterFilename($this->name); + + // get attributes + $comment = $this->opt->getComment(); + + // get dos timestamp + $time = static::dosTime($this->opt->getTime()->getTimestamp()); + + $footer = $this->buildZip64ExtraBlock(); + + $fields = [ + ['V', ZipStream::CDR_FILE_SIGNATURE], // Central file header signature + ['v', ZipStream::ZIP_VERSION_MADE_BY], // Made by version + ['v', $this->version->getValue()], // Extract by version + ['v', $this->bits], // General purpose bit flags - data descriptor flag set + ['v', $this->method->getValue()], // Compression method + ['V', $time], // Timestamp (DOS Format) + ['V', $this->crc], // CRC32 + ['V', $this->zlen->getLowFF()], // Compressed Data Length + ['V', $this->len->getLowFF()], // Original Data Length + ['v', strlen($name)], // Length of filename + ['v', strlen($footer)], // Extra data len (see above) + ['v', strlen($comment)], // Length of comment + ['v', 0], // Disk number + ['v', 0], // Internal File Attributes + ['V', 32], // External File Attributes + ['V', $this->ofs->getLowFF()] // Relative offset of local header + ]; + + // pack fields, then append name and comment + $header = ZipStream::packFields($fields); + + return $header . $name . $footer . $comment; + } + + /** + * @return Bigint + */ + public function getTotalLength(): Bigint + { + return $this->totalLength; + } +} diff --git a/lib/maennchen/zipstream-php/src/Option/Archive.php b/lib/maennchen/zipstream-php/src/Option/Archive.php new file mode 100644 index 00000000..21d14d8c --- /dev/null +++ b/lib/maennchen/zipstream-php/src/Option/Archive.php @@ -0,0 +1,263 @@ + 4 GB or file count > 64k) + * + * @var bool + */ + private $enableZip64 = true; + /** + * Enable streaming files with single read where + * general purpose bit 3 indicates local file header + * contain zero values in crc and size fields, + * these appear only after file contents + * in data descriptor block. + * + * @var bool + */ + private $zeroHeader = false; + /** + * Enable reading file stat for determining file size. + * When a 32-bit system reads file size that is + * over 2 GB, invalid value appears in file size + * due to integer overflow. Should be disabled on + * 32-bit systems with method addFileFromPath + * if any file may exceed 2 GB. In this case file + * will be read in blocks and correct size will be + * determined from content. + * + * @var bool + */ + private $statFiles = true; + /** + * Enable flush after every write to output stream. + * @var bool + */ + private $flushOutput = false; + /** + * HTTP Content-Disposition. Defaults to + * 'attachment', where + * FILENAME is the specified filename. + * + * Note that this does nothing if you are + * not sending HTTP headers. + * + * @var string + */ + private $contentDisposition = 'attachment'; + /** + * Note that this does nothing if you are + * not sending HTTP headers. + * + * @var string + */ + private $contentType = 'application/x-zip'; + /** + * @var int + */ + private $deflateLevel = 6; + + /** + * @var StreamInterface|resource + */ + private $outputStream; + + /** + * Options constructor. + */ + public function __construct() + { + $this->largeFileMethod = Method::STORE(); + $this->outputStream = fopen('php://output', 'wb'); + } + + public function getComment(): string + { + return $this->comment; + } + + public function setComment(string $comment): void + { + $this->comment = $comment; + } + + public function getLargeFileSize(): int + { + return $this->largeFileSize; + } + + public function setLargeFileSize(int $largeFileSize): void + { + $this->largeFileSize = $largeFileSize; + } + + public function getLargeFileMethod(): Method + { + return $this->largeFileMethod; + } + + public function setLargeFileMethod(Method $largeFileMethod): void + { + $this->largeFileMethod = $largeFileMethod; + } + + public function isSendHttpHeaders(): bool + { + return $this->sendHttpHeaders; + } + + public function setSendHttpHeaders(bool $sendHttpHeaders): void + { + $this->sendHttpHeaders = $sendHttpHeaders; + } + + public function getHttpHeaderCallback(): Callable + { + return $this->httpHeaderCallback; + } + + public function setHttpHeaderCallback(Callable $httpHeaderCallback): void + { + $this->httpHeaderCallback = $httpHeaderCallback; + } + + public function isEnableZip64(): bool + { + return $this->enableZip64; + } + + public function setEnableZip64(bool $enableZip64): void + { + $this->enableZip64 = $enableZip64; + } + + public function isZeroHeader(): bool + { + return $this->zeroHeader; + } + + public function setZeroHeader(bool $zeroHeader): void + { + $this->zeroHeader = $zeroHeader; + } + + public function isFlushOutput(): bool + { + return $this->flushOutput; + } + + public function setFlushOutput(bool $flushOutput): void + { + $this->flushOutput = $flushOutput; + } + + public function isStatFiles(): bool + { + return $this->statFiles; + } + + public function setStatFiles(bool $statFiles): void + { + $this->statFiles = $statFiles; + } + + public function getContentDisposition(): string + { + return $this->contentDisposition; + } + + public function setContentDisposition(string $contentDisposition): void + { + $this->contentDisposition = $contentDisposition; + } + + public function getContentType(): string + { + return $this->contentType; + } + + public function setContentType(string $contentType): void + { + $this->contentType = $contentType; + } + + /** + * @return StreamInterface|resource + */ + public function getOutputStream() + { + return $this->outputStream; + } + + /** + * @param StreamInterface|resource $outputStream + */ + public function setOutputStream($outputStream): void + { + $this->outputStream = $outputStream; + } + + /** + * @return int + */ + public function getDeflateLevel(): int + { + return $this->deflateLevel; + } + + /** + * @param int $deflateLevel + */ + public function setDeflateLevel(int $deflateLevel): void + { + $this->deflateLevel = $deflateLevel; + } +} diff --git a/lib/maennchen/zipstream-php/src/Option/File.php b/lib/maennchen/zipstream-php/src/Option/File.php new file mode 100644 index 00000000..05ff7b5e --- /dev/null +++ b/lib/maennchen/zipstream-php/src/Option/File.php @@ -0,0 +1,117 @@ +deflateLevel = $this->deflateLevel ?: $archiveOptions->getDeflateLevel(); + $this->time = $this->time ?: new DateTime(); + } + + /** + * @return string + */ + public function getComment(): string + { + return $this->comment; + } + + /** + * @param string $comment + */ + public function setComment(string $comment): void + { + $this->comment = $comment; + } + + /** + * @return Method + */ + public function getMethod(): Method + { + return $this->method ?: Method::DEFLATE(); + } + + /** + * @param Method $method + */ + public function setMethod(Method $method): void + { + $this->method = $method; + } + + /** + * @return int + */ + public function getDeflateLevel(): int + { + return $this->deflateLevel ?: Archive::DEFAULT_DEFLATE_LEVEL; + } + + /** + * @param int $deflateLevel + */ + public function setDeflateLevel(int $deflateLevel): void + { + $this->deflateLevel = $deflateLevel; + } + + /** + * @return DateTimeInterface + */ + public function getTime(): DateTimeInterface + { + return $this->time; + } + + /** + * @param DateTimeInterface $time + */ + public function setTime(DateTimeInterface $time): void + { + $this->time = $time; + } + + /** + * @return int + */ + public function getSize(): int + { + return $this->size; + } + + /** + * @param int $size + */ + public function setSize(int $size): void + { + $this->size = $size; + } +} diff --git a/lib/maennchen/zipstream-php/src/Option/Method.php b/lib/maennchen/zipstream-php/src/Option/Method.php new file mode 100644 index 00000000..bbec84c0 --- /dev/null +++ b/lib/maennchen/zipstream-php/src/Option/Method.php @@ -0,0 +1,19 @@ +stream = $stream; + } + + /** + * Closes the stream and any underlying resources. + * + * @return void + */ + public function close(): void + { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + + /** + * Separates any underlying resources from the stream. + * + * After the stream has been detached, the stream is in an unusable state. + * + * @return resource|null Underlying PHP stream, if any + */ + public function detach() + { + $result = $this->stream; + $this->stream = null; + return $result; + } + + /** + * Reads all data from the stream into a string, from the beginning to end. + * + * This method MUST attempt to seek to the beginning of the stream before + * reading data and read the stream until the end is reached. + * + * Warning: This could attempt to load a large amount of data into memory. + * + * This method MUST NOT raise an exception in order to conform with PHP's + * string casting operations. + * + * @see http://php.net/manual/en/language.oop5.magic.php#object.tostring + * @return string + */ + public function __toString(): string + { + try { + $this->seek(0); + } catch (RuntimeException $e) {} + return (string) stream_get_contents($this->stream); + } + + /** + * Seek to a position in the stream. + * + * @link http://www.php.net/manual/en/function.fseek.php + * @param int $offset Stream offset + * @param int $whence Specifies how the cursor position will be calculated + * based on the seek offset. Valid values are identical to the built-in + * PHP $whence values for `fseek()`. SEEK_SET: Set position equal to + * offset bytes SEEK_CUR: Set position to current location plus offset + * SEEK_END: Set position to end-of-stream plus offset. + * @throws RuntimeException on failure. + */ + public function seek($offset, $whence = SEEK_SET): void + { + if (!$this->isSeekable()) { + throw new RuntimeException; + } + if (fseek($this->stream, $offset, $whence) !== 0) { + throw new RuntimeException; + } + } + + /** + * Returns whether or not the stream is seekable. + * + * @return bool + */ + public function isSeekable(): bool + { + return (bool)$this->getMetadata('seekable'); + } + + /** + * Get stream metadata as an associative array or retrieve a specific key. + * + * The keys returned are identical to the keys returned from PHP's + * stream_get_meta_data() function. + * + * @link http://php.net/manual/en/function.stream-get-meta-data.php + * @param string $key Specific metadata to retrieve. + * @return array|mixed|null Returns an associative array if no key is + * provided. Returns a specific key value if a key is provided and the + * value is found, or null if the key is not found. + */ + public function getMetadata($key = null) + { + $metadata = stream_get_meta_data($this->stream); + return $key !== null ? @$metadata[$key] : $metadata; + } + + /** + * Get the size of the stream if known. + * + * @return int|null Returns the size in bytes if known, or null if unknown. + */ + public function getSize(): ?int + { + $stats = fstat($this->stream); + return $stats['size']; + } + + /** + * Returns the current position of the file read/write pointer + * + * @return int Position of the file pointer + * @throws RuntimeException on error. + */ + public function tell(): int + { + $position = ftell($this->stream); + if ($position === false) { + throw new RuntimeException; + } + return $position; + } + + /** + * Returns true if the stream is at the end of the stream. + * + * @return bool + */ + public function eof(): bool + { + return feof($this->stream); + } + + /** + * Seek to the beginning of the stream. + * + * If the stream is not seekable, this method will raise an exception; + * otherwise, it will perform a seek(0). + * + * @see seek() + * @link http://www.php.net/manual/en/function.fseek.php + * @throws RuntimeException on failure. + */ + public function rewind(): void + { + $this->seek(0); + } + + /** + * Write data to the stream. + * + * @param string $string The string that is to be written. + * @return int Returns the number of bytes written to the stream. + * @throws RuntimeException on failure. + */ + public function write($string): int + { + if (!$this->isWritable()) { + throw new RuntimeException; + } + if (fwrite($this->stream, $string) === false) { + throw new RuntimeException; + } + return \mb_strlen($string); + } + + /** + * Returns whether or not the stream is writable. + * + * @return bool + */ + public function isWritable(): bool + { + $mode = $this->getMetadata('mode'); + if (!is_string($mode)) { + throw new RuntimeException('Could not get stream mode from metadata!'); + } + return preg_match('/[waxc+]/', $mode) === 1; + } + + /** + * Read data from the stream. + * + * @param int $length Read up to $length bytes from the object and return + * them. Fewer than $length bytes may be returned if underlying stream + * call returns fewer bytes. + * @return string Returns the data read from the stream, or an empty string + * if no bytes are available. + * @throws \RuntimeException if an error occurs. + */ + public function read($length): string + { + if (!$this->isReadable()) { + throw new RuntimeException; + } + $result = fread($this->stream, $length); + if ($result === false) { + throw new RuntimeException; + } + return $result; + } + + /** + * Returns whether or not the stream is readable. + * + * @return bool + */ + public function isReadable(): bool + { + $mode = $this->getMetadata('mode'); + if (!is_string($mode)) { + throw new RuntimeException('Could not get stream mode from metadata!'); + } + return preg_match('/[r+]/', $mode) === 1; + } + + /** + * Returns the remaining contents in a string + * + * @return string + * @throws \RuntimeException if unable to read or an error occurs while + * reading. + */ + public function getContents(): string + { + if (!$this->isReadable()) { + throw new RuntimeException; + } + $result = stream_get_contents($this->stream); + if ($result === false) { + throw new RuntimeException; + } + return $result; + } +} diff --git a/lib/maennchen/zipstream-php/src/ZipStream.php b/lib/maennchen/zipstream-php/src/ZipStream.php new file mode 100644 index 00000000..d281d259 --- /dev/null +++ b/lib/maennchen/zipstream-php/src/ZipStream.php @@ -0,0 +1,602 @@ +addFile('some_file.gif', $data); + * + * * add second file + * $data = file_get_contents('some_file.gif'); + * $zip->addFile('another_file.png', $data); + * + * 3. Finish the zip stream: + * + * $zip->finish(); + * + * You can also add an archive comment, add comments to individual files, + * and adjust the timestamp of files. See the API documentation for each + * method below for additional information. + * + * Example: + * + * // create a new zip stream object + * $zip = new ZipStream('some_files.zip'); + * + * // list of local files + * $files = array('foo.txt', 'bar.jpg'); + * + * // read and add each file to the archive + * foreach ($files as $path) + * $zip->addFile($path, file_get_contents($path)); + * + * // write archive footer to stream + * $zip->finish(); + */ +class ZipStream +{ + /** + * This number corresponds to the ZIP version/OS used (2 bytes) + * From: https://www.iana.org/assignments/media-types/application/zip + * The upper byte (leftmost one) indicates the host system (OS) for the + * file. Software can use this information to determine + * the line record format for text files etc. The current + * mappings are: + * + * 0 - MS-DOS and OS/2 (F.A.T. file systems) + * 1 - Amiga 2 - VAX/VMS + * 3 - *nix 4 - VM/CMS + * 5 - Atari ST 6 - OS/2 H.P.F.S. + * 7 - Macintosh 8 - Z-System + * 9 - CP/M 10 thru 255 - unused + * + * The lower byte (rightmost one) indicates the version number of the + * software used to encode the file. The value/10 + * indicates the major version number, and the value + * mod 10 is the minor version number. + * Here we are using 6 for the OS, indicating OS/2 H.P.F.S. + * to prevent file permissions issues upon extract (see #84) + * 0x603 is 00000110 00000011 in binary, so 6 and 3 + */ + const ZIP_VERSION_MADE_BY = 0x603; + + /** + * The following signatures end with 0x4b50, which in ASCII is PK, + * the initials of the inventor Phil Katz. + * See https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers + */ + const FILE_HEADER_SIGNATURE = 0x04034b50; + const CDR_FILE_SIGNATURE = 0x02014b50; + const CDR_EOF_SIGNATURE = 0x06054b50; + const DATA_DESCRIPTOR_SIGNATURE = 0x08074b50; + const ZIP64_CDR_EOF_SIGNATURE = 0x06064b50; + const ZIP64_CDR_LOCATOR_SIGNATURE = 0x07064b50; + + /** + * Global Options + * + * @var ArchiveOptions + */ + public $opt; + + /** + * @var array + */ + public $files = []; + + /** + * @var Bigint + */ + public $cdr_ofs; + + /** + * @var Bigint + */ + public $ofs; + + /** + * @var bool + */ + protected $need_headers; + + /** + * @var null|String + */ + protected $output_name; + + /** + * Create a new ZipStream object. + * + * Parameters: + * + * @param String $name - Name of output file (optional). + * @param ArchiveOptions $opt - Archive Options + * + * Large File Support: + * + * By default, the method addFileFromPath() will send send files + * larger than 20 megabytes along raw rather than attempting to + * compress them. You can change both the maximum size and the + * compression behavior using the largeFile* options above, with the + * following caveats: + * + * * For "small" files (e.g. files smaller than largeFileSize), the + * memory use can be up to twice that of the actual file. In other + * words, adding a 10 megabyte file to the archive could potentially + * occupy 20 megabytes of memory. + * + * * Enabling compression on large files (e.g. files larger than + * large_file_size) is extremely slow, because ZipStream has to pass + * over the large file once to calculate header information, and then + * again to compress and send the actual data. + * + * Examples: + * + * // create a new zip file named 'foo.zip' + * $zip = new ZipStream('foo.zip'); + * + * // create a new zip file named 'bar.zip' with a comment + * $opt->setComment = 'this is a comment for the zip file.'; + * $zip = new ZipStream('bar.zip', $opt); + * + * Notes: + * + * In order to let this library send HTTP headers, a filename must be given + * _and_ the option `sendHttpHeaders` must be `true`. This behavior is to + * allow software to send its own headers (including the filename), and + * still use this library. + */ + public function __construct(?string $name = null, ?ArchiveOptions $opt = null) + { + $this->opt = $opt ?: new ArchiveOptions(); + + $this->output_name = $name; + $this->need_headers = $name && $this->opt->isSendHttpHeaders(); + + $this->cdr_ofs = new Bigint(); + $this->ofs = new Bigint(); + } + + /** + * addFile + * + * Add a file to the archive. + * + * @param String $name - path of file in archive (including directory). + * @param String $data - contents of file + * @param FileOptions $options + * + * File Options: + * time - Last-modified timestamp (seconds since the epoch) of + * this file. Defaults to the current time. + * comment - Comment related to this file. + * method - Storage method for file ("store" or "deflate") + * + * Examples: + * + * // add a file named 'foo.txt' + * $data = file_get_contents('foo.txt'); + * $zip->addFile('foo.txt', $data); + * + * // add a file named 'bar.jpg' with a comment and a last-modified + * // time of two hours ago + * $data = file_get_contents('bar.jpg'); + * $opt->setTime = time() - 2 * 3600; + * $opt->setComment = 'this is a comment about bar.jpg'; + * $zip->addFile('bar.jpg', $data, $opt); + */ + public function addFile(string $name, string $data, ?FileOptions $options = null): void + { + $options = $options ?: new FileOptions(); + $options->defaultTo($this->opt); + + $file = new File($this, $name, $options); + $file->processData($data); + } + + /** + * addFileFromPath + * + * Add a file at path to the archive. + * + * Note that large files may be compressed differently than smaller + * files; see the "Large File Support" section above for more + * information. + * + * @param String $name - name of file in archive (including directory path). + * @param String $path - path to file on disk (note: paths should be encoded using + * UNIX-style forward slashes -- e.g '/path/to/some/file'). + * @param FileOptions $options + * + * File Options: + * time - Last-modified timestamp (seconds since the epoch) of + * this file. Defaults to the current time. + * comment - Comment related to this file. + * method - Storage method for file ("store" or "deflate") + * + * Examples: + * + * // add a file named 'foo.txt' from the local file '/tmp/foo.txt' + * $zip->addFileFromPath('foo.txt', '/tmp/foo.txt'); + * + * // add a file named 'bigfile.rar' from the local file + * // '/usr/share/bigfile.rar' with a comment and a last-modified + * // time of two hours ago + * $path = '/usr/share/bigfile.rar'; + * $opt->setTime = time() - 2 * 3600; + * $opt->setComment = 'this is a comment about bar.jpg'; + * $zip->addFileFromPath('bigfile.rar', $path, $opt); + * + * @return void + * @throws \ZipStream\Exception\FileNotFoundException + * @throws \ZipStream\Exception\FileNotReadableException + */ + public function addFileFromPath(string $name, string $path, ?FileOptions $options = null): void + { + $options = $options ?: new FileOptions(); + $options->defaultTo($this->opt); + + $file = new File($this, $name, $options); + $file->processPath($path); + } + + /** + * addFileFromStream + * + * Add an open stream to the archive. + * + * @param String $name - path of file in archive (including directory). + * @param resource $stream - contents of file as a stream resource + * @param FileOptions $options + * + * File Options: + * time - Last-modified timestamp (seconds since the epoch) of + * this file. Defaults to the current time. + * comment - Comment related to this file. + * + * Examples: + * + * // create a temporary file stream and write text to it + * $fp = tmpfile(); + * fwrite($fp, 'The quick brown fox jumped over the lazy dog.'); + * + * // add a file named 'streamfile.txt' from the content of the stream + * $x->addFileFromStream('streamfile.txt', $fp); + * + * @return void + */ + public function addFileFromStream(string $name, $stream, ?FileOptions $options = null): void + { + $options = $options ?: new FileOptions(); + $options->defaultTo($this->opt); + + $file = new File($this, $name, $options); + $file->processStream(new DeflateStream($stream)); + } + + /** + * addFileFromPsr7Stream + * + * Add an open stream to the archive. + * + * @param String $name - path of file in archive (including directory). + * @param StreamInterface $stream - contents of file as a stream resource + * @param FileOptions $options + * + * File Options: + * time - Last-modified timestamp (seconds since the epoch) of + * this file. Defaults to the current time. + * comment - Comment related to this file. + * + * Examples: + * + * $stream = $response->getBody(); + * // add a file named 'streamfile.txt' from the content of the stream + * $x->addFileFromPsr7Stream('streamfile.txt', $stream); + * + * @return void + */ + public function addFileFromPsr7Stream( + string $name, + StreamInterface $stream, + ?FileOptions $options = null + ): void { + $options = $options ?: new FileOptions(); + $options->defaultTo($this->opt); + + $file = new File($this, $name, $options); + $file->processStream($stream); + } + + /** + * finish + * + * Write zip footer to stream. + * + * Example: + * + * // add a list of files to the archive + * $files = array('foo.txt', 'bar.jpg'); + * foreach ($files as $path) + * $zip->addFile($path, file_get_contents($path)); + * + * // write footer to stream + * $zip->finish(); + * @return void + * + * @throws OverflowException + */ + public function finish(): void + { + // add trailing cdr file records + foreach ($this->files as $cdrFile) { + $this->send($cdrFile); + $this->cdr_ofs = $this->cdr_ofs->add(Bigint::init(strlen($cdrFile))); + } + + // Add 64bit headers (if applicable) + if (count($this->files) >= 0xFFFF || + $this->cdr_ofs->isOver32() || + $this->ofs->isOver32()) { + if (!$this->opt->isEnableZip64()) { + throw new OverflowException(); + } + + $this->addCdr64Eof(); + $this->addCdr64Locator(); + } + + // add trailing cdr eof record + $this->addCdrEof(); + + // The End + $this->clear(); + } + + /** + * Send ZIP64 CDR EOF (Central Directory Record End-of-File) record. + * + * @return void + */ + protected function addCdr64Eof(): void + { + $num_files = count($this->files); + $cdr_length = $this->cdr_ofs; + $cdr_offset = $this->ofs; + + $fields = [ + ['V', static::ZIP64_CDR_EOF_SIGNATURE], // ZIP64 end of central file header signature + ['P', 44], // Length of data below this header (length of block - 12) = 44 + ['v', static::ZIP_VERSION_MADE_BY], // Made by version + ['v', Version::ZIP64], // Extract by version + ['V', 0x00], // disk number + ['V', 0x00], // no of disks + ['P', $num_files], // no of entries on disk + ['P', $num_files], // no of entries in cdr + ['P', $cdr_length], // CDR size + ['P', $cdr_offset], // CDR offset + ]; + + $ret = static::packFields($fields); + $this->send($ret); + } + + /** + * Create a format string and argument list for pack(), then call + * pack() and return the result. + * + * @param array $fields + * @return string + */ + public static function packFields(array $fields): string + { + $fmt = ''; + $args = []; + + // populate format string and argument list + foreach ($fields as [$format, $value]) { + if ($format === 'P') { + $fmt .= 'VV'; + if ($value instanceof Bigint) { + $args[] = $value->getLow32(); + $args[] = $value->getHigh32(); + } else { + $args[] = $value; + $args[] = 0; + } + } else { + if ($value instanceof Bigint) { + $value = $value->getLow32(); + } + $fmt .= $format; + $args[] = $value; + } + } + + // prepend format string to argument list + array_unshift($args, $fmt); + + // build output string from header and compressed data + return pack(...$args); + } + + /** + * Send string, sending HTTP headers if necessary. + * Flush output after write if configure option is set. + * + * @param String $str + * @return void + */ + public function send(string $str): void + { + if ($this->need_headers) { + $this->sendHttpHeaders(); + } + $this->need_headers = false; + + $outputStream = $this->opt->getOutputStream(); + + if ($outputStream instanceof StreamInterface) { + $outputStream->write($str); + } else { + fwrite($outputStream, $str); + } + + if ($this->opt->isFlushOutput()) { + // flush output buffer if it is on and flushable + $status = ob_get_status(); + if (isset($status['flags']) && ($status['flags'] & PHP_OUTPUT_HANDLER_FLUSHABLE)) { + ob_flush(); + } + + // Flush system buffers after flushing userspace output buffer + flush(); + } + } + + /** + * Send HTTP headers for this stream. + * + * @return void + */ + protected function sendHttpHeaders(): void + { + // grab content disposition + $disposition = $this->opt->getContentDisposition(); + + if ($this->output_name) { + // Various different browsers dislike various characters here. Strip them all for safety. + $safe_output = trim(str_replace(['"', "'", '\\', ';', "\n", "\r"], '', $this->output_name)); + + // Check if we need to UTF-8 encode the filename + $urlencoded = rawurlencode($safe_output); + $disposition .= "; filename*=UTF-8''{$urlencoded}"; + } + + $headers = array( + 'Content-Type' => $this->opt->getContentType(), + 'Content-Disposition' => $disposition, + 'Pragma' => 'public', + 'Cache-Control' => 'public, must-revalidate', + 'Content-Transfer-Encoding' => 'binary' + ); + + $call = $this->opt->getHttpHeaderCallback(); + foreach ($headers as $key => $val) { + $call("$key: $val"); + } + } + + /** + * Send ZIP64 CDR Locator (Central Directory Record Locator) record. + * + * @return void + */ + protected function addCdr64Locator(): void + { + $cdr_offset = $this->ofs->add($this->cdr_ofs); + + $fields = [ + ['V', static::ZIP64_CDR_LOCATOR_SIGNATURE], // ZIP64 end of central file header signature + ['V', 0x00], // Disc number containing CDR64EOF + ['P', $cdr_offset], // CDR offset + ['V', 1], // Total number of disks + ]; + + $ret = static::packFields($fields); + $this->send($ret); + } + + /** + * Send CDR EOF (Central Directory Record End-of-File) record. + * + * @return void + */ + protected function addCdrEof(): void + { + $num_files = count($this->files); + $cdr_length = $this->cdr_ofs; + $cdr_offset = $this->ofs; + + // grab comment (if specified) + $comment = $this->opt->getComment(); + + $fields = [ + ['V', static::CDR_EOF_SIGNATURE], // end of central file header signature + ['v', 0x00], // disk number + ['v', 0x00], // no of disks + ['v', min($num_files, 0xFFFF)], // no of entries on disk + ['v', min($num_files, 0xFFFF)], // no of entries in cdr + ['V', $cdr_length->getLowFF()], // CDR size + ['V', $cdr_offset->getLowFF()], // CDR offset + ['v', strlen($comment)], // Zip Comment size + ]; + + $ret = static::packFields($fields) . $comment; + $this->send($ret); + } + + /** + * Clear all internal variables. Note that the stream object is not + * usable after this. + * + * @return void + */ + protected function clear(): void + { + $this->files = []; + $this->ofs = new Bigint(); + $this->cdr_ofs = new Bigint(); + $this->opt = new ArchiveOptions(); + } + + /** + * Is this file larger than large_file_size? + * + * @param string $path + * @return bool + */ + public function isLargeFile(string $path): bool + { + if (!$this->opt->isStatFiles()) { + return false; + } + $stat = stat($path); + return $stat['size'] > $this->opt->getLargeFileSize(); + } + + /** + * Save file attributes for trailing CDR record. + * + * @param File $file + * @return void + */ + public function addToCdr(File $file): void + { + $file->ofs = $this->ofs; + $this->ofs = $this->ofs->add($file->getTotalLength()); + $this->files[] = $file->getCdrFile(); + } +} diff --git a/lib/maennchen/zipstream-php/test/BigintTest.php b/lib/maennchen/zipstream-php/test/BigintTest.php new file mode 100644 index 00000000..ac9c7c28 --- /dev/null +++ b/lib/maennchen/zipstream-php/test/BigintTest.php @@ -0,0 +1,65 @@ +assertSame('0x0000000012345678', $bigint->getHex64()); + $this->assertSame(0x12345678, $bigint->getLow32()); + $this->assertSame(0, $bigint->getHigh32()); + } + + public function testConstructLarge(): void + { + $bigint = new Bigint(0x87654321); + $this->assertSame('0x0000000087654321', $bigint->getHex64()); + $this->assertSame('87654321', bin2hex(pack('N', $bigint->getLow32()))); + $this->assertSame(0, $bigint->getHigh32()); + } + + public function testAddSmallValue(): void + { + $bigint = new Bigint(1); + $bigint = $bigint->add(Bigint::init(2)); + $this->assertSame(3, $bigint->getLow32()); + $this->assertFalse($bigint->isOver32()); + $this->assertTrue($bigint->isOver32(true)); + $this->assertSame($bigint->getLowFF(), (float)$bigint->getLow32()); + $this->assertSame($bigint->getLowFF(true), (float)0xFFFFFFFF); + } + + public function testAddWithOverflowAtLowestByte(): void + { + $bigint = new Bigint(0xFF); + $bigint = $bigint->add(Bigint::init(0x01)); + $this->assertSame(0x100, $bigint->getLow32()); + } + + public function testAddWithOverflowAtInteger32(): void + { + $bigint = new Bigint(0xFFFFFFFE); + $this->assertFalse($bigint->isOver32()); + $bigint = $bigint->add(Bigint::init(0x01)); + $this->assertTrue($bigint->isOver32()); + $bigint = $bigint->add(Bigint::init(0x01)); + $this->assertSame('0x0000000100000000', $bigint->getHex64()); + $this->assertTrue($bigint->isOver32()); + $this->assertSame((float)0xFFFFFFFF, $bigint->getLowFF()); + } + + public function testAddWithOverflowAtInteger64(): void + { + $bigint = Bigint::fromLowHigh(0xFFFFFFFF, 0xFFFFFFFF); + $this->assertSame('0xFFFFFFFFFFFFFFFF', $bigint->getHex64()); + $this->expectException(OverflowException::class); + $bigint->add(Bigint::init(1)); + } +} diff --git a/lib/maennchen/zipstream-php/test/ZipStreamTest.php b/lib/maennchen/zipstream-php/test/ZipStreamTest.php new file mode 100644 index 00000000..8b37f0ae --- /dev/null +++ b/lib/maennchen/zipstream-php/test/ZipStreamTest.php @@ -0,0 +1,614 @@ +expectException(\ZipStream\Exception\FileNotFoundException::class); + // Get ZipStream Object + $zip = new ZipStream(); + + // Trigger error by adding a file which doesn't exist + $zip->addFileFromPath('foobar.php', '/foo/bar/foobar.php'); + } + + public function testFileNotReadableException(): void + { + // create new virtual filesystem + $root = vfsStream::setup('vfs'); + // create a virtual file with no permissions + $file = vfsStream::newFile('foo.txt', 0000)->at($root)->setContent('bar'); + $zip = new ZipStream(); + $this->expectException(\ZipStream\Exception\FileNotReadableException::class); + $zip->addFileFromPath('foo.txt', $file->url()); + } + + public function testDostime(): void + { + // Allows testing of protected method + $class = new \ReflectionClass(File::class); + $method = $class->getMethod('dostime'); + $method->setAccessible(true); + + $this->assertSame($method->invoke(null, 1416246368), 1165069764); + + // January 1 1980 - DOS Epoch. + $this->assertSame($method->invoke(null, 315532800), 2162688); + + // January 1 1970 -> January 1 1980 due to minimum DOS Epoch. @todo Throw Exception? + $this->assertSame($method->invoke(null, 0), 2162688); + } + + public function testAddFile(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $zip->addFile('sample.txt', 'Sample String Data'); + $zip->addFile('test/sample.txt', 'More Simple Sample Data'); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); + + $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); + $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); + } + + /** + * @return array + */ + protected function getTmpFileStream(): array + { + $tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest'); + $stream = fopen($tmp, 'wb+'); + + return array($tmp, $stream); + } + + /** + * @param string $tmp + * @return string + */ + protected function validateAndExtractZip($tmp): string + { + $tmpDir = $this->getTmpDir(); + + $zipArch = new \ZipArchive; + $res = $zipArch->open($tmp); + + if ($res !== true) { + $this->fail("Failed to open {$tmp}. Code: $res"); + + return $tmpDir; + } + + $this->assertEquals(0, $zipArch->status); + $this->assertEquals(0, $zipArch->statusSys); + + $zipArch->extractTo($tmpDir); + $zipArch->close(); + + return $tmpDir; + } + + protected function getTmpDir(): string + { + $tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest'); + unlink($tmp); + mkdir($tmp) or $this->fail('Failed to make directory'); + + return $tmp; + } + + /** + * @param string $path + * @return string[] + */ + protected function getRecursiveFileList(string $path): array + { + $data = array(); + $path = (string)realpath($path); + $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)); + + $pathLen = strlen($path); + foreach ($files as $file) { + $filePath = $file->getRealPath(); + if (!is_dir($filePath)) { + $data[] = substr($filePath, $pathLen + 1); + } + } + + sort($data); + + return $data; + } + + public function testAddFileUtf8NameComment(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $name = 'árvíztűrő tükörfúrógép.txt'; + $content = 'Sample String Data'; + $comment = + 'Filename has every special characters ' . + 'from Hungarian language in lowercase. ' . + 'In uppercase: ÁÍŰŐÜÖÚÓÉ'; + + $fileOptions = new FileOptions(); + $fileOptions->setComment($comment); + + $zip->addFile($name, $content, $fileOptions); + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array($name), $files); + $this->assertStringEqualsFile($tmpDir . '/' . $name, $content); + + $zipArch = new \ZipArchive(); + $zipArch->open($tmp); + $this->assertEquals($comment, $zipArch->getCommentName($name)); + } + + public function testAddFileUtf8NameNonUtfComment(): void + { + $this->expectException(\ZipStream\Exception\EncodingException::class); + + $stream = $this->getTmpFileStream()[1]; + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $name = 'á.txt'; + $content = 'any'; + $comment = 'á'; + + $fileOptions = new FileOptions(); + $fileOptions->setComment(mb_convert_encoding($comment, 'ISO-8859-2', 'UTF-8')); + + $zip->addFile($name, $content, $fileOptions); + } + + public function testAddFileNonUtf8NameUtfComment(): void + { + $this->expectException(\ZipStream\Exception\EncodingException::class); + + $stream = $this->getTmpFileStream()[1]; + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $name = 'á.txt'; + $content = 'any'; + $comment = 'á'; + + $fileOptions = new FileOptions(); + $fileOptions->setComment($comment); + + $zip->addFile(mb_convert_encoding($name, 'ISO-8859-2', 'UTF-8'), $content, $fileOptions); + } + + public function testAddFileWithStorageMethod(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + $zip->addFile('sample.txt', 'Sample String Data', $fileOptions); + $zip->addFile('test/sample.txt', 'More Simple Sample Data'); + $zip->finish(); + fclose($stream); + + $zipArch = new \ZipArchive(); + $zipArch->open($tmp); + + $sample1 = $zipArch->statName('sample.txt'); + $sample12 = $zipArch->statName('test/sample.txt'); + $this->assertEquals($sample1['comp_method'], Method::STORE); + $this->assertEquals($sample12['comp_method'], Method::DEFLATE); + + $zipArch->close(); + } + + public function testDecompressFileWithMacUnarchiver(): void + { + if (!file_exists(self::OSX_ARCHIVE_UTILITY)) { + $this->markTestSkipped('The Mac OSX Archive Utility is not available.'); + } + + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $folder = uniqid('', true); + + $zip->addFile($folder . '/sample.txt', 'Sample Data'); + $zip->finish(); + fclose($stream); + + exec(escapeshellarg(self::OSX_ARCHIVE_UTILITY) . ' ' . escapeshellarg($tmp), $output, $returnStatus); + + $this->assertEquals(0, $returnStatus); + $this->assertCount(0, $output); + + $this->assertFileExists(dirname($tmp) . '/' . $folder . '/sample.txt'); + $this->assertStringEqualsFile(dirname($tmp) . '/' . $folder . '/sample.txt', 'Sample Data'); + } + + public function testAddFileFromPath(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + [$tmpExample, $streamExample] = $this->getTmpFileStream(); + fwrite($streamExample, 'Sample String Data'); + fclose($streamExample); + $zip->addFileFromPath('sample.txt', $tmpExample); + + [$tmpExample, $streamExample] = $this->getTmpFileStream(); + fwrite($streamExample, 'More Simple Sample Data'); + fclose($streamExample); + $zip->addFileFromPath('test/sample.txt', $tmpExample); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array('sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'), $files); + + $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); + $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); + } + + public function testAddFileFromPathWithStorageMethod(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + [$tmpExample, $streamExample] = $this->getTmpFileStream(); + fwrite($streamExample, 'Sample String Data'); + fclose($streamExample); + $zip->addFileFromPath('sample.txt', $tmpExample, $fileOptions); + + [$tmpExample, $streamExample] = $this->getTmpFileStream(); + fwrite($streamExample, 'More Simple Sample Data'); + fclose($streamExample); + $zip->addFileFromPath('test/sample.txt', $tmpExample); + + $zip->finish(); + fclose($stream); + + $zipArch = new \ZipArchive(); + $zipArch->open($tmp); + + $sample1 = $zipArch->statName('sample.txt'); + $this->assertEquals(Method::STORE, $sample1['comp_method']); + + $sample2 = $zipArch->statName('test/sample.txt'); + $this->assertEquals(Method::DEFLATE, $sample2['comp_method']); + + $zipArch->close(); + } + + public function testAddLargeFileFromPath(): void + { + $methods = [Method::DEFLATE(), Method::STORE()]; + $falseTrue = [false, true]; + foreach ($methods as $method) { + foreach ($falseTrue as $zeroHeader) { + foreach ($falseTrue as $zip64) { + if ($zeroHeader && $method->equals(Method::DEFLATE())) { + continue; + } + $this->addLargeFileFileFromPath($method, $zeroHeader, $zip64); + } + } + } + } + + protected function addLargeFileFileFromPath($method, $zeroHeader, $zip64): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + $options->setLargeFileMethod($method); + $options->setLargeFileSize(5); + $options->setZeroHeader($zeroHeader); + $options->setEnableZip64($zip64); + + $zip = new ZipStream(null, $options); + + [$tmpExample, $streamExample] = $this->getTmpFileStream(); + for ($i = 0; $i <= 10000; $i++) { + fwrite($streamExample, sha1((string)$i)); + if ($i % 100 === 0) { + fwrite($streamExample, "\n"); + } + } + fclose($streamExample); + $shaExample = sha1_file($tmpExample); + $zip->addFileFromPath('sample.txt', $tmpExample); + unlink($tmpExample); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array('sample.txt'), $files); + + $this->assertEquals(sha1_file($tmpDir . '/sample.txt'), $shaExample, "SHA-1 Mismatch Method: {$method}"); + } + + public function testAddFileFromStream(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + // In this test we can't use temporary stream to feed data + // because zlib.deflate filter gives empty string before PHP 7 + // it works fine with file stream + $streamExample = fopen(__FILE__, 'rb'); + $zip->addFileFromStream('sample.txt', $streamExample); +// fclose($streamExample); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + $streamExample2 = fopen('php://temp', 'wb+'); + fwrite($streamExample2, 'More Simple Sample Data'); + rewind($streamExample2); // move the pointer back to the beginning of file. + $zip->addFileFromStream('test/sample.txt', $streamExample2, $fileOptions); +// fclose($streamExample2); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array('sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'), $files); + + $this->assertStringEqualsFile(__FILE__, file_get_contents($tmpDir . '/sample.txt')); + $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); + } + + public function testAddFileFromStreamWithStorageMethod(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + $streamExample = fopen('php://temp', 'wb+'); + fwrite($streamExample, 'Sample String Data'); + rewind($streamExample); // move the pointer back to the beginning of file. + $zip->addFileFromStream('sample.txt', $streamExample, $fileOptions); +// fclose($streamExample); + + $streamExample2 = fopen('php://temp', 'bw+'); + fwrite($streamExample2, 'More Simple Sample Data'); + rewind($streamExample2); // move the pointer back to the beginning of file. + $zip->addFileFromStream('test/sample.txt', $streamExample2); +// fclose($streamExample2); + + $zip->finish(); + fclose($stream); + + $zipArch = new \ZipArchive(); + $zipArch->open($tmp); + + $sample1 = $zipArch->statName('sample.txt'); + $this->assertEquals(Method::STORE, $sample1['comp_method']); + + $sample2 = $zipArch->statName('test/sample.txt'); + $this->assertEquals(Method::DEFLATE, $sample2['comp_method']); + + $zipArch->close(); + } + + public function testAddFileFromPsr7Stream(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $body = 'Sample String Data'; + $response = new Response(200, [], $body); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + $zip->addFileFromPsr7Stream('sample.json', $response->getBody(), $fileOptions); + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array('sample.json'), $files); + $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); + } + + public function testAddFileFromPsr7StreamWithOutputToPsr7Stream(): void + { + [$tmp, $resource] = $this->getTmpFileStream(); + $psr7OutputStream = new Stream($resource); + + $options = new ArchiveOptions(); + $options->setOutputStream($psr7OutputStream); + + $zip = new ZipStream(null, $options); + + $body = 'Sample String Data'; + $response = new Response(200, [], $body); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + + $zip->addFileFromPsr7Stream('sample.json', $response->getBody(), $fileOptions); + $zip->finish(); + $psr7OutputStream->close(); + + $tmpDir = $this->validateAndExtractZip($tmp); + $files = $this->getRecursiveFileList($tmpDir); + + $this->assertEquals(array('sample.json'), $files); + $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); + } + + public function testAddFileFromPsr7StreamWithFileSizeSet(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + + $zip = new ZipStream(null, $options); + + $body = 'Sample String Data'; + $fileSize = strlen($body); + // Add fake padding + $fakePadding = "\0\0\0\0\0\0"; + $response = new Response(200, [], $body . $fakePadding); + + $fileOptions = new FileOptions(); + $fileOptions->setMethod(Method::STORE()); + $fileOptions->setSize($fileSize); + $zip->addFileFromPsr7Stream('sample.json', $response->getBody(), $fileOptions); + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(array('sample.json'), $files); + $this->assertStringEqualsFile($tmpDir . '/sample.json', $body); + } + + public function testCreateArchiveWithFlushOptionSet(): void + { + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + $options->setFlushOutput(true); + + $zip = new ZipStream(null, $options); + + $zip->addFile('sample.txt', 'Sample String Data'); + $zip->addFile('test/sample.txt', 'More Simple Sample Data'); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + + $files = $this->getRecursiveFileList($tmpDir); + $this->assertEquals(['sample.txt', 'test' . DIRECTORY_SEPARATOR . 'sample.txt'], $files); + + $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); + $this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data'); + } + + public function testCreateArchiveWithOutputBufferingOffAndFlushOptionSet(): void + { + // WORKAROUND (1/2): remove phpunit's output buffer in order to run test without any buffering + ob_end_flush(); + $this->assertEquals(0, ob_get_level()); + + [$tmp, $stream] = $this->getTmpFileStream(); + + $options = new ArchiveOptions(); + $options->setOutputStream($stream); + $options->setFlushOutput(true); + + $zip = new ZipStream(null, $options); + + $zip->addFile('sample.txt', 'Sample String Data'); + + $zip->finish(); + fclose($stream); + + $tmpDir = $this->validateAndExtractZip($tmp); + $this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data'); + + // WORKAROUND (2/2): add back output buffering so that PHPUnit doesn't complain that it is missing + ob_start(); + } +} diff --git a/lib/maennchen/zipstream-php/test/bootstrap.php b/lib/maennchen/zipstream-php/test/bootstrap.php new file mode 100644 index 00000000..b43c9bd6 --- /dev/null +++ b/lib/maennchen/zipstream-php/test/bootstrap.php @@ -0,0 +1,6 @@ +setOutputStream(fopen('php://memory', 'wb')); + $fileOpt->setTime(clone $expectedTime); + + $zip = new ZipStream(null, $archiveOpt); + + $zip->addFile('sample.txt', 'Sample', $fileOpt); + + $zip->finish(); + + $this->assertEquals($expectedTime, $fileOpt->getTime()); + } +} diff --git a/lib/markbaker/complex/.github/workflows/main.yml b/lib/markbaker/complex/.github/workflows/main.yml new file mode 100644 index 00000000..43d5bf04 --- /dev/null +++ b/lib/markbaker/complex/.github/workflows/main.yml @@ -0,0 +1,150 @@ +name: main +on: [ push, pull_request ] +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + experimental: + - false + php-version: + - '7.2' + - '7.3' + - '7.4' + - '8.0' + + include: + - php-version: '8.1' + experimental: true + + name: PHP ${{ matrix.php-version }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + coverage: none + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Delete composer lock file + id: composer-lock + if: ${{ matrix.php-version == '8.1' }} + run: | + echo "::set-output name=flags::--ignore-platform-reqs" + + - name: Install dependencies + run: composer update --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} + + - name: Setup problem matchers for PHP + run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" + + - name: Setup problem matchers for PHPUnit + run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: "Run PHPUnit tests (Experimental: ${{ matrix.experimental }})" + env: + FAILURE_ACTION: "${{ matrix.experimental == true }}" + run: vendor/bin/phpunit --verbose || $FAILURE_ACTION + + phpcs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + coverage: none + tools: cs2pr + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Code style with PHP_CodeSniffer + run: ./vendor/bin/phpcs -q --report=checkstyle classes/src/ | cs2pr + + versions: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + coverage: none + tools: cs2pr + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Code Version Compatibility check with PHP_CodeSniffer + run: ./vendor/bin/phpcs -q --report-width=200 --report=summary,full classes/src/ --standard=PHPCompatibility --runtime-set testVersion 7.2- + + coverage: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + coverage: pcov + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Test Coverage + run: ./vendor/bin/phpunit --verbose --coverage-text diff --git a/lib/markbaker/complex/README.md b/lib/markbaker/complex/README.md index c306394e..27afc59c 100644 --- a/lib/markbaker/complex/README.md +++ b/lib/markbaker/complex/README.md @@ -3,11 +3,13 @@ PHPComplex --- -PHP Class for handling Complex numbers +PHP Class Library for working with Complex numbers -Master: [![Build Status](https://travis-ci.org/MarkBaker/PHPComplex.png?branch=master)](http://travis-ci.org/MarkBaker/PHPComplex) +[![Build Status](https://github.com/MarkBaker/PHPComplex/workflows/main/badge.svg)](https://github.com/MarkBaker/PHPComplex/actions) +[![Total Downloads](https://img.shields.io/packagist/dt/markbaker/complex)](https://packagist.org/packages/markbaker/complex) +[![Latest Stable Version](https://img.shields.io/github/v/release/MarkBaker/PHPComplex)](https://packagist.org/packages/markbaker/complex) +[![License](https://img.shields.io/github/license/MarkBaker/PHPComplex)](https://packagist.org/packages/markbaker/complex) -Develop: [![Build Status](https://travis-ci.org/MarkBaker/PHPComplex.png?branch=develop)](http://travis-ci.org/MarkBaker/PHPComplex) [![Complex Numbers](https://imgs.xkcd.com/comics/complex_numbers_2x.png)](https://xkcd.com/2028/) @@ -63,19 +65,37 @@ together with functions for --- +# Installation + +```shell +composer require markbaker/complex:^3.0 +``` + +# Important BC Note + +If you've previously been using procedural calls to functions and operations using this library, then from version 3.0 you should use [MarkBaker/PHPComplexFunctions](https://github.com/MarkBaker/PHPComplexFunctions) instead (available on packagist as [markbaker/complex-functions](https://packagist.org/packages/markbaker/complex-functions)). + +You'll need to replace `markbaker/complex`in your `composer.json` file with the new library, but otherwise there should be no difference in the namespacing, or in the way that you have called the Complex functions in the past, so no actual code changes are required. + +```shell +composer require markbaker/complex-functions:^1.0 +``` + +You should not reference this library (`markbaker/complex`) in your `composer.json`, composer wil take care of that for you. + # Usage To create a new complex object, you can provide either the real, imaginary and suffix parts as individual values, or as an array of values passed passed to the constructor; or a string representing the value. e.g -``` +```php $real = 1.23; $imaginary = -4.56; $suffix = 'i'; $complexObject = new Complex\Complex($real, $imaginary, $suffix); ``` -or -``` +or as an array +```php $real = 1.23; $imaginary = -4.56; $suffix = 'i'; @@ -84,8 +104,8 @@ $arguments = [$real, $imaginary, $suffix]; $complexObject = new Complex\Complex($arguments); ``` -or -``` +or as a string +```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); @@ -98,57 +118,54 @@ This also allows you to chain multiple methods as you would for a fluent interfa To perform mathematical operations with Complex values, you can call the appropriate method against a complex value, passing other values as arguments -``` +```php $complexString1 = '1.23-4.56i'; $complexString2 = '2.34+5.67i'; $complexObject = new Complex\Complex($complexString1); echo $complexObject->add($complexString2); ``` -or pass all values to the appropriate function -``` + +or use the static Operation methods +```php $complexString1 = '1.23-4.56i'; $complexString2 = '2.34+5.67i'; -echo Complex\add($complexString1, $complexString2); +echo Complex\Operations::add($complexString1, $complexString2); ``` If you want to perform the same operation against multiple values (e.g. to add three or more complex numbers), then you can pass multiple arguments to any of the operations. -You can pass these arguments as Complex objects, or as an array or string that will parse to a complex object. +You can pass these arguments as Complex objects, or as an array, or string that will parse to a complex object. ## Using functions When calling any of the available functions for a complex value, you can either call the relevant method for the Complex object -``` +```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); echo $complexObject->sinh(); ``` -or you can call the function as you would in procedural code, passing the Complex object as an argument -``` -$complexString = '1.23-4.56i'; -$complexObject = new Complex\Complex($complexString); -echo Complex\sinh($complexObject); -``` -When called procedurally using the function, you can pass in the argument as a Complex object, or as an array or string that will parse to a complex object. -``` +or use the static Functions methods +```php $complexString = '1.23-4.56i'; -echo Complex\sinh($complexString); +echo Complex\Functions::sinh($complexString); ``` +As with operations, you can pass these arguments as Complex objects, or as an array or string that will parse to a complex object. -In the case of the `pow()` function (the only implemented function that requires an additional argument) you need to pass both arguments when calling the function procedurally -``` +In the case of the `pow()` function (the only implemented function that requires an additional argument) you need to pass both arguments when calling the function + +```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); -echo Complex\pow($complexObject, 2); +echo Complex\Functions::pow($complexObject, 2); ``` or pass the additional argument when calling the method -``` +```php $complexString = '1.23-4.56i'; $complexObject = new Complex\Complex($complexString); diff --git a/lib/markbaker/complex/classes/Autoloader.php b/lib/markbaker/complex/classes/Autoloader.php deleted file mode 100644 index 792ecef0..00000000 --- a/lib/markbaker/complex/classes/Autoloader.php +++ /dev/null @@ -1,53 +0,0 @@ -regex = $regex; - parent::__construct($it, $regex); - } -} - -class FilenameFilter extends FilesystemRegexFilter -{ - // Filter files against the regex - public function accept() - { - return (!$this->isFile() || preg_match($this->regex, $this->getFilename())); - } -} - - -$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src'; -$srcDirectory = new RecursiveDirectoryIterator($srcFolder); - -$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i'); -$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Complex|Exception)\.php).*$/i'); - -foreach (new RecursiveIteratorIterator($filteredFileList) as $file) { - if ($file->isFile()) { - include_once $file; - } -} diff --git a/lib/markbaker/complex/classes/src/Complex.php b/lib/markbaker/complex/classes/src/Complex.php index 4f873afc..25414ee6 100644 --- a/lib/markbaker/complex/classes/src/Complex.php +++ b/lib/markbaker/complex/classes/src/Complex.php @@ -186,7 +186,7 @@ public function __construct($realPart = 0.0, $imaginaryPart = null, $suffix = 'i // Set parsed values in our properties $this->realPart = (float) $realPart; $this->imaginaryPart = (float) $imaginaryPart; - $this->suffix = strtolower($suffix); + $this->suffix = strtolower($suffix ?? ''); } /** @@ -194,7 +194,7 @@ public function __construct($realPart = 0.0, $imaginaryPart = null, $suffix = 'i * * @return Float */ - public function getReal() + public function getReal(): float { return $this->realPart; } @@ -204,7 +204,7 @@ public function getReal() * * @return Float */ - public function getImaginary() + public function getImaginary(): float { return $this->imaginaryPart; } @@ -214,7 +214,7 @@ public function getImaginary() * * @return String */ - public function getSuffix() + public function getSuffix(): string { return $this->suffix; } @@ -224,7 +224,7 @@ public function getSuffix() * * @return Bool */ - public function isReal() + public function isReal(): bool { return $this->imaginaryPart == 0.0; } @@ -234,12 +234,12 @@ public function isReal() * * @return Bool */ - public function isComplex() + public function isComplex(): bool { return !$this->isReal(); } - public function format() + public function format(): string { $str = ""; if ($this->imaginaryPart != 0.0) { @@ -262,7 +262,7 @@ public function format() return $str; } - public function __toString() + public function __toString(): string { return $this->format(); } @@ -274,7 +274,7 @@ public function __toString() * @return Complex * @throws Exception If the argument isn't a Complex number or cannot be converted to one */ - public static function validateComplexArgument($complex) + public static function validateComplexArgument($complex): Complex { if (is_scalar($complex) || is_array($complex)) { $complex = new Complex($complex); @@ -290,7 +290,7 @@ public static function validateComplexArgument($complex) * * @return Complex */ - public function reverse() + public function reverse(): Complex { return new Complex( $this->imaginaryPart, @@ -299,7 +299,7 @@ public function reverse() ); } - public function invertImaginary() + public function invertImaginary(): Complex { return new Complex( $this->realPart, @@ -308,7 +308,7 @@ public function invertImaginary() ); } - public function invertReal() + public function invertReal(): Complex { return new Complex( $this->realPart * -1, @@ -376,15 +376,13 @@ public function __call($functionName, $arguments) $functionName = strtolower(str_replace('_', '', $functionName)); // Test for function calls - if (in_array($functionName, self::$functions)) { - $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}"; - return $functionName($this, ...$arguments); + if (in_array($functionName, self::$functions, true)) { + return Functions::$functionName($this, ...$arguments); } // Test for operation calls - if (in_array($functionName, self::$operations)) { - $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}"; - return $functionName($this, ...$arguments); + if (in_array($functionName, self::$operations, true)) { + return Operations::$functionName($this, ...$arguments); } - throw new Exception('Function or Operation does not exist'); + throw new Exception('Complex Function or Operation does not exist'); } } diff --git a/lib/markbaker/complex/classes/src/Functions.php b/lib/markbaker/complex/classes/src/Functions.php new file mode 100644 index 00000000..ba593ac3 --- /dev/null +++ b/lib/markbaker/complex/classes/src/Functions.php @@ -0,0 +1,805 @@ +getReal() - $invsqrt->getImaginary(), + $complex->getImaginary() + $invsqrt->getReal() + ); + $log = self::ln($adjust); + + return new Complex( + $log->getImaginary(), + -1 * $log->getReal() + ); + } + + /** + * Returns the inverse hyperbolic cosine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic cosine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function acosh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal() && ($complex->getReal() > 1)) { + return new Complex(\acosh($complex->getReal())); + } + + $acosh = self::acos($complex) + ->reverse(); + if ($acosh->getReal() < 0.0) { + $acosh = $acosh->invertReal(); + } + + return $acosh; + } + + /** + * Returns the inverse cotangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse cotangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function acot($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return self::atan(self::inverse($complex)); + } + + /** + * Returns the inverse hyperbolic cotangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic cotangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function acoth($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return self::atanh(self::inverse($complex)); + } + + /** + * Returns the inverse cosecant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse cosecant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function acsc($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::asin(self::inverse($complex)); + } + + /** + * Returns the inverse hyperbolic cosecant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic cosecant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function acsch($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::asinh(self::inverse($complex)); + } + + /** + * Returns the argument of a complex number. + * Also known as the theta of the complex number, i.e. the angle in radians + * from the real axis to the representation of the number in polar coordinates. + * + * This function is a synonym for theta() + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return float The argument (or theta) value of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * + * @see theta + */ + public static function argument($complex): float + { + return self::theta($complex); + } + + /** + * Returns the inverse secant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse secant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function asec($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::acos(self::inverse($complex)); + } + + /** + * Returns the inverse hyperbolic secant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic secant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function asech($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::acosh(self::inverse($complex)); + } + + /** + * Returns the inverse sine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse sine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function asin($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + $square = Operations::multiply($complex, $complex); + $invsqrt = new Complex(1.0); + $invsqrt = Operations::subtract($invsqrt, $square); + $invsqrt = self::sqrt($invsqrt); + $adjust = new Complex( + $invsqrt->getReal() - $complex->getImaginary(), + $invsqrt->getImaginary() + $complex->getReal() + ); + $log = self::ln($adjust); + + return new Complex( + $log->getImaginary(), + -1 * $log->getReal() + ); + } + + /** + * Returns the inverse hyperbolic sine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic sine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function asinh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal() && ($complex->getReal() > 1)) { + return new Complex(\asinh($complex->getReal())); + } + + $asinh = clone $complex; + $asinh = $asinh->reverse() + ->invertReal(); + $asinh = self::asin($asinh); + + return $asinh->reverse() + ->invertImaginary(); + } + + /** + * Returns the inverse tangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse tangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function atan($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\atan($complex->getReal())); + } + + $t1Value = new Complex(-1 * $complex->getImaginary(), $complex->getReal()); + $uValue = new Complex(1, 0); + + $d1Value = clone $uValue; + $d1Value = Operations::subtract($d1Value, $t1Value); + $d2Value = Operations::add($t1Value, $uValue); + $uResult = $d1Value->divideBy($d2Value); + $uResult = self::ln($uResult); + + return new Complex( + (($uResult->getImaginary() == M_PI) ? -M_PI : $uResult->getImaginary()) * -0.5, + $uResult->getReal() * 0.5, + $complex->getSuffix() + ); + } + + /** + * Returns the inverse hyperbolic tangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse hyperbolic tangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function atanh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + $real = $complex->getReal(); + if ($real >= -1.0 && $real <= 1.0) { + return new Complex(\atanh($real)); + } else { + return new Complex(\atanh(1 / $real), (($real < 0.0) ? M_PI_2 : -1 * M_PI_2)); + } + } + + $iComplex = clone $complex; + $iComplex = $iComplex->invertImaginary() + ->reverse(); + return self::atan($iComplex) + ->invertReal() + ->reverse(); + } + + /** + * Returns the complex conjugate of a complex number + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The conjugate of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function conjugate($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return new Complex( + $complex->getReal(), + -1 * $complex->getImaginary(), + $complex->getSuffix() + ); + } + + /** + * Returns the cosine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The cosine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function cos($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\cos($complex->getReal())); + } + + return self::conjugate( + new Complex( + \cos($complex->getReal()) * \cosh($complex->getImaginary()), + \sin($complex->getReal()) * \sinh($complex->getImaginary()), + $complex->getSuffix() + ) + ); + } + + /** + * Returns the hyperbolic cosine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic cosine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function cosh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\cosh($complex->getReal())); + } + + return new Complex( + \cosh($complex->getReal()) * \cos($complex->getImaginary()), + \sinh($complex->getReal()) * \sin($complex->getImaginary()), + $complex->getSuffix() + ); + } + + /** + * Returns the cotangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The cotangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function cot($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::inverse(self::tan($complex)); + } + + /** + * Returns the hyperbolic cotangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic cotangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function coth($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return self::inverse(self::tanh($complex)); + } + + /** + * Returns the cosecant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The cosecant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function csc($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::inverse(self::sin($complex)); + } + + /** + * Returns the hyperbolic cosecant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic cosecant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function csch($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return new Complex(INF); + } + + return self::inverse(self::sinh($complex)); + } + + /** + * Returns the exponential of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The exponential of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function exp($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if (($complex->getReal() == 0.0) && (\abs($complex->getImaginary()) == M_PI)) { + return new Complex(-1.0, 0.0); + } + + $rho = \exp($complex->getReal()); + + return new Complex( + $rho * \cos($complex->getImaginary()), + $rho * \sin($complex->getImaginary()), + $complex->getSuffix() + ); + } + + /** + * Returns the inverse of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The inverse of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws InvalidArgumentException If function would result in a division by zero + */ + public static function inverse($complex): Complex + { + $complex = clone Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + throw new InvalidArgumentException('Division by zero'); + } + + return $complex->divideInto(1.0); + } + + /** + * Returns the natural logarithm of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The natural logarithm of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws InvalidArgumentException If the real and the imaginary parts are both zero + */ + public static function ln($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { + throw new InvalidArgumentException(); + } + + return new Complex( + \log(self::rho($complex)), + self::theta($complex), + $complex->getSuffix() + ); + } + + /** + * Returns the base-2 logarithm of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The base-2 logarithm of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws InvalidArgumentException If the real and the imaginary parts are both zero + */ + public static function log2($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { + throw new InvalidArgumentException(); + } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) { + return new Complex(\log($complex->getReal(), 2), 0.0, $complex->getSuffix()); + } + + return self::ln($complex) + ->multiply(\log(Complex::EULER, 2)); + } + + /** + * Returns the common logarithm (base 10) of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The common logarithm (base 10) of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws InvalidArgumentException If the real and the imaginary parts are both zero + */ + public static function log10($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { + throw new InvalidArgumentException(); + } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) { + return new Complex(\log10($complex->getReal()), 0.0, $complex->getSuffix()); + } + + return self::ln($complex) + ->multiply(\log10(Complex::EULER)); + } + + /** + * Returns the negative of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The negative value of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * + * @see rho + * + */ + public static function negative($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return new Complex( + -1 * $complex->getReal(), + -1 * $complex->getImaginary(), + $complex->getSuffix() + ); + } + + /** + * Returns a complex number raised to a power. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @param float|integer $power The power to raise this value to + * @return Complex The complex argument raised to the real power. + * @throws Exception If the power argument isn't a valid real + */ + public static function pow($complex, $power): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if (!is_numeric($power)) { + throw new Exception('Power argument must be a real number'); + } + + if ($complex->getImaginary() == 0.0 && $complex->getReal() >= 0.0) { + return new Complex(\pow($complex->getReal(), $power)); + } + + $rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary())); + $rPower = \pow($rValue, $power); + $theta = $complex->argument() * $power; + if ($theta == 0) { + return new Complex(1); + } + + return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix()); + } + + /** + * Returns the rho of a complex number. + * This is the distance/radius from the centrepoint to the representation of the number in polar coordinates. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return float The rho value of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function rho($complex): float + { + $complex = Complex::validateComplexArgument($complex); + + return \sqrt( + ($complex->getReal() * $complex->getReal()) + + ($complex->getImaginary() * $complex->getImaginary()) + ); + } + + /** + * Returns the secant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The secant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function sec($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return self::inverse(self::cos($complex)); + } + + /** + * Returns the hyperbolic secant of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic secant of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function sech($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + return self::inverse(self::cosh($complex)); + } + + /** + * Returns the sine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The sine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function sin($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\sin($complex->getReal())); + } + + return new Complex( + \sin($complex->getReal()) * \cosh($complex->getImaginary()), + \cos($complex->getReal()) * \sinh($complex->getImaginary()), + $complex->getSuffix() + ); + } + + /** + * Returns the hyperbolic sine of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic sine of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function sinh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\sinh($complex->getReal())); + } + + return new Complex( + \sinh($complex->getReal()) * \cos($complex->getImaginary()), + \cosh($complex->getReal()) * \sin($complex->getImaginary()), + $complex->getSuffix() + ); + } + + /** + * Returns the square root of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The Square root of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function sqrt($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + $theta = self::theta($complex); + $delta1 = \cos($theta / 2); + $delta2 = \sin($theta / 2); + $rho = \sqrt(self::rho($complex)); + + return new Complex($delta1 * $rho, $delta2 * $rho, $complex->getSuffix()); + } + + /** + * Returns the tangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The tangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws InvalidArgumentException If function would result in a division by zero + */ + public static function tan($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->isReal()) { + return new Complex(\tan($complex->getReal())); + } + + $real = $complex->getReal(); + $imaginary = $complex->getImaginary(); + $divisor = 1 + \pow(\tan($real), 2) * \pow(\tanh($imaginary), 2); + if ($divisor == 0.0) { + throw new InvalidArgumentException('Division by zero'); + } + + return new Complex( + \pow(self::sech($imaginary)->getReal(), 2) * \tan($real) / $divisor, + \pow(self::sec($real)->getReal(), 2) * \tanh($imaginary) / $divisor, + $complex->getSuffix() + ); + } + + /** + * Returns the hyperbolic tangent of a complex number. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return Complex The hyperbolic tangent of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + * @throws \InvalidArgumentException If function would result in a division by zero + */ + public static function tanh($complex): Complex + { + $complex = Complex::validateComplexArgument($complex); + $real = $complex->getReal(); + $imaginary = $complex->getImaginary(); + $divisor = \cos($imaginary) * \cos($imaginary) + \sinh($real) * \sinh($real); + if ($divisor == 0.0) { + throw new InvalidArgumentException('Division by zero'); + } + + return new Complex( + \sinh($real) * \cosh($real) / $divisor, + 0.5 * \sin(2 * $imaginary) / $divisor, + $complex->getSuffix() + ); + } + + /** + * Returns the theta of a complex number. + * This is the angle in radians from the real axis to the representation of the number in polar coordinates. + * + * @param Complex|mixed $complex Complex number or a numeric value. + * @return float The theta value of the complex argument. + * @throws Exception If argument isn't a valid real or complex number. + */ + public static function theta($complex): float + { + $complex = Complex::validateComplexArgument($complex); + + if ($complex->getReal() == 0.0) { + if ($complex->isReal()) { + return 0.0; + } elseif ($complex->getImaginary() < 0.0) { + return M_PI / -2; + } + return M_PI / 2; + } elseif ($complex->getReal() > 0.0) { + return \atan($complex->getImaginary() / $complex->getReal()); + } elseif ($complex->getImaginary() < 0.0) { + return -(M_PI - \atan(\abs($complex->getImaginary()) / \abs($complex->getReal()))); + } + + return M_PI - \atan($complex->getImaginary() / \abs($complex->getReal())); + } +} diff --git a/lib/markbaker/complex/classes/src/Operations.php b/lib/markbaker/complex/classes/src/Operations.php new file mode 100644 index 00000000..b13a8734 --- /dev/null +++ b/lib/markbaker/complex/classes/src/Operations.php @@ -0,0 +1,210 @@ +isComplex() && $complex->isComplex() && + $result->getSuffix() !== $complex->getSuffix()) { + throw new Exception('Suffix Mismatch'); + } + + $real = $result->getReal() + $complex->getReal(); + $imaginary = $result->getImaginary() + $complex->getImaginary(); + + $result = new Complex( + $real, + $imaginary, + ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) + ); + } + + return $result; + } + + /** + * Divides two or more complex numbers + * + * @param array of string|integer|float|Complex $complexValues The numbers to divide + * @return Complex + */ + public static function divideby(...$complexValues): Complex + { + if (count($complexValues) < 2) { + throw new \Exception('This function requires at least 2 arguments'); + } + + $base = array_shift($complexValues); + $result = clone Complex::validateComplexArgument($base); + + foreach ($complexValues as $complex) { + $complex = Complex::validateComplexArgument($complex); + + if ($result->isComplex() && $complex->isComplex() && + $result->getSuffix() !== $complex->getSuffix()) { + throw new Exception('Suffix Mismatch'); + } + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + throw new InvalidArgumentException('Division by zero'); + } + + $delta1 = ($result->getReal() * $complex->getReal()) + + ($result->getImaginary() * $complex->getImaginary()); + $delta2 = ($result->getImaginary() * $complex->getReal()) - + ($result->getReal() * $complex->getImaginary()); + $delta3 = ($complex->getReal() * $complex->getReal()) + + ($complex->getImaginary() * $complex->getImaginary()); + + $real = $delta1 / $delta3; + $imaginary = $delta2 / $delta3; + + $result = new Complex( + $real, + $imaginary, + ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) + ); + } + + return $result; + } + + /** + * Divides two or more complex numbers + * + * @param array of string|integer|float|Complex $complexValues The numbers to divide + * @return Complex + */ + public static function divideinto(...$complexValues): Complex + { + if (count($complexValues) < 2) { + throw new \Exception('This function requires at least 2 arguments'); + } + + $base = array_shift($complexValues); + $result = clone Complex::validateComplexArgument($base); + + foreach ($complexValues as $complex) { + $complex = Complex::validateComplexArgument($complex); + + if ($result->isComplex() && $complex->isComplex() && + $result->getSuffix() !== $complex->getSuffix()) { + throw new Exception('Suffix Mismatch'); + } + if ($result->getReal() == 0.0 && $result->getImaginary() == 0.0) { + throw new InvalidArgumentException('Division by zero'); + } + + $delta1 = ($complex->getReal() * $result->getReal()) + + ($complex->getImaginary() * $result->getImaginary()); + $delta2 = ($complex->getImaginary() * $result->getReal()) - + ($complex->getReal() * $result->getImaginary()); + $delta3 = ($result->getReal() * $result->getReal()) + + ($result->getImaginary() * $result->getImaginary()); + + $real = $delta1 / $delta3; + $imaginary = $delta2 / $delta3; + + $result = new Complex( + $real, + $imaginary, + ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) + ); + } + + return $result; + } + + /** + * Multiplies two or more complex numbers + * + * @param array of string|integer|float|Complex $complexValues The numbers to multiply + * @return Complex + */ + public static function multiply(...$complexValues): Complex + { + if (count($complexValues) < 2) { + throw new \Exception('This function requires at least 2 arguments'); + } + + $base = array_shift($complexValues); + $result = clone Complex::validateComplexArgument($base); + + foreach ($complexValues as $complex) { + $complex = Complex::validateComplexArgument($complex); + + if ($result->isComplex() && $complex->isComplex() && + $result->getSuffix() !== $complex->getSuffix()) { + throw new Exception('Suffix Mismatch'); + } + + $real = ($result->getReal() * $complex->getReal()) - + ($result->getImaginary() * $complex->getImaginary()); + $imaginary = ($result->getReal() * $complex->getImaginary()) + + ($result->getImaginary() * $complex->getReal()); + + $result = new Complex( + $real, + $imaginary, + ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) + ); + } + + return $result; + } + + /** + * Subtracts two or more complex numbers + * + * @param array of string|integer|float|Complex $complexValues The numbers to subtract + * @return Complex + */ + public static function subtract(...$complexValues): Complex + { + if (count($complexValues) < 2) { + throw new \Exception('This function requires at least 2 arguments'); + } + + $base = array_shift($complexValues); + $result = clone Complex::validateComplexArgument($base); + + foreach ($complexValues as $complex) { + $complex = Complex::validateComplexArgument($complex); + + if ($result->isComplex() && $complex->isComplex() && + $result->getSuffix() !== $complex->getSuffix()) { + throw new Exception('Suffix Mismatch'); + } + + $real = $result->getReal() - $complex->getReal(); + $imaginary = $result->getImaginary() - $complex->getImaginary(); + + $result = new Complex( + $real, + $imaginary, + ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) + ); + } + + return $result; + } +} diff --git a/lib/markbaker/complex/classes/src/functions/abs.php b/lib/markbaker/complex/classes/src/functions/abs.php deleted file mode 100644 index b66ef7cf..00000000 --- a/lib/markbaker/complex/classes/src/functions/abs.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() - $invsqrt->getImaginary(), - $complex->getImaginary() + $invsqrt->getReal() - ); - $log = ln($adjust); - - return new Complex( - $log->getImaginary(), - -1 * $log->getReal() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/acosh.php b/lib/markbaker/complex/classes/src/functions/acosh.php deleted file mode 100644 index 18a992e4..00000000 --- a/lib/markbaker/complex/classes/src/functions/acosh.php +++ /dev/null @@ -1,34 +0,0 @@ -isReal() && ($complex->getReal() > 1)) { - return new Complex(\acosh($complex->getReal())); - } - - $acosh = acos($complex) - ->reverse(); - if ($acosh->getReal() < 0.0) { - $acosh = $acosh->invertReal(); - } - - return $acosh; -} diff --git a/lib/markbaker/complex/classes/src/functions/acot.php b/lib/markbaker/complex/classes/src/functions/acot.php deleted file mode 100644 index 11bee466..00000000 --- a/lib/markbaker/complex/classes/src/functions/acot.php +++ /dev/null @@ -1,25 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return asin(inverse($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/acsch.php b/lib/markbaker/complex/classes/src/functions/acsch.php deleted file mode 100644 index bb45d347..00000000 --- a/lib/markbaker/complex/classes/src/functions/acsch.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return asinh(inverse($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/argument.php b/lib/markbaker/complex/classes/src/functions/argument.php deleted file mode 100644 index d7209cc4..00000000 --- a/lib/markbaker/complex/classes/src/functions/argument.php +++ /dev/null @@ -1,28 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return acos(inverse($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/asech.php b/lib/markbaker/complex/classes/src/functions/asech.php deleted file mode 100644 index b36c40e2..00000000 --- a/lib/markbaker/complex/classes/src/functions/asech.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return acosh(inverse($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/asin.php b/lib/markbaker/complex/classes/src/functions/asin.php deleted file mode 100644 index 9c982aca..00000000 --- a/lib/markbaker/complex/classes/src/functions/asin.php +++ /dev/null @@ -1,37 +0,0 @@ -getReal() - $complex->getImaginary(), - $invsqrt->getImaginary() + $complex->getReal() - ); - $log = ln($adjust); - - return new Complex( - $log->getImaginary(), - -1 * $log->getReal() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/asinh.php b/lib/markbaker/complex/classes/src/functions/asinh.php deleted file mode 100644 index c1243fd7..00000000 --- a/lib/markbaker/complex/classes/src/functions/asinh.php +++ /dev/null @@ -1,33 +0,0 @@ -isReal() && ($complex->getReal() > 1)) { - return new Complex(\asinh($complex->getReal())); - } - - $asinh = clone $complex; - $asinh = $asinh->reverse() - ->invertReal(); - $asinh = asin($asinh); - return $asinh->reverse() - ->invertImaginary(); -} diff --git a/lib/markbaker/complex/classes/src/functions/atan.php b/lib/markbaker/complex/classes/src/functions/atan.php deleted file mode 100644 index 2c75dcf8..00000000 --- a/lib/markbaker/complex/classes/src/functions/atan.php +++ /dev/null @@ -1,45 +0,0 @@ -isReal()) { - return new Complex(\atan($complex->getReal())); - } - - $t1Value = new Complex(-1 * $complex->getImaginary(), $complex->getReal()); - $uValue = new Complex(1, 0); - - $d1Value = clone $uValue; - $d1Value = subtract($d1Value, $t1Value); - $d2Value = add($t1Value, $uValue); - $uResult = $d1Value->divideBy($d2Value); - $uResult = ln($uResult); - - return new Complex( - (($uResult->getImaginary() == M_PI) ? -M_PI : $uResult->getImaginary()) * -0.5, - $uResult->getReal() * 0.5, - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/atanh.php b/lib/markbaker/complex/classes/src/functions/atanh.php deleted file mode 100644 index c53f2a9a..00000000 --- a/lib/markbaker/complex/classes/src/functions/atanh.php +++ /dev/null @@ -1,38 +0,0 @@ -isReal()) { - $real = $complex->getReal(); - if ($real >= -1.0 && $real <= 1.0) { - return new Complex(\atanh($real)); - } else { - return new Complex(\atanh(1 / $real), (($real < 0.0) ? M_PI_2 : -1 * M_PI_2)); - } - } - - $iComplex = clone $complex; - $iComplex = $iComplex->invertImaginary() - ->reverse(); - return atan($iComplex) - ->invertReal() - ->reverse(); -} diff --git a/lib/markbaker/complex/classes/src/functions/conjugate.php b/lib/markbaker/complex/classes/src/functions/conjugate.php deleted file mode 100644 index bd1984b7..00000000 --- a/lib/markbaker/complex/classes/src/functions/conjugate.php +++ /dev/null @@ -1,28 +0,0 @@ -getReal(), - -1 * $complex->getImaginary(), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/cos.php b/lib/markbaker/complex/classes/src/functions/cos.php deleted file mode 100644 index 80a4683d..00000000 --- a/lib/markbaker/complex/classes/src/functions/cos.php +++ /dev/null @@ -1,34 +0,0 @@ -isReal()) { - return new Complex(\cos($complex->getReal())); - } - - return conjugate( - new Complex( - \cos($complex->getReal()) * \cosh($complex->getImaginary()), - \sin($complex->getReal()) * \sinh($complex->getImaginary()), - $complex->getSuffix() - ) - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/cosh.php b/lib/markbaker/complex/classes/src/functions/cosh.php deleted file mode 100644 index a4bea653..00000000 --- a/lib/markbaker/complex/classes/src/functions/cosh.php +++ /dev/null @@ -1,32 +0,0 @@ -isReal()) { - return new Complex(\cosh($complex->getReal())); - } - - return new Complex( - \cosh($complex->getReal()) * \cos($complex->getImaginary()), - \sinh($complex->getReal()) * \sin($complex->getImaginary()), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/cot.php b/lib/markbaker/complex/classes/src/functions/cot.php deleted file mode 100644 index 339101e1..00000000 --- a/lib/markbaker/complex/classes/src/functions/cot.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return new Complex(INF); - } - - return inverse(tan($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/coth.php b/lib/markbaker/complex/classes/src/functions/coth.php deleted file mode 100644 index 7fe705a4..00000000 --- a/lib/markbaker/complex/classes/src/functions/coth.php +++ /dev/null @@ -1,24 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return inverse(sin($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/csch.php b/lib/markbaker/complex/classes/src/functions/csch.php deleted file mode 100644 index f4500981..00000000 --- a/lib/markbaker/complex/classes/src/functions/csch.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return INF; - } - - return inverse(sinh($complex)); -} diff --git a/lib/markbaker/complex/classes/src/functions/exp.php b/lib/markbaker/complex/classes/src/functions/exp.php deleted file mode 100644 index 4cac6967..00000000 --- a/lib/markbaker/complex/classes/src/functions/exp.php +++ /dev/null @@ -1,34 +0,0 @@ -getReal() == 0.0) && (\abs($complex->getImaginary()) == M_PI)) { - return new Complex(-1.0, 0.0); - } - - $rho = \exp($complex->getReal()); - - return new Complex( - $rho * \cos($complex->getImaginary()), - $rho * \sin($complex->getImaginary()), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/inverse.php b/lib/markbaker/complex/classes/src/functions/inverse.php deleted file mode 100644 index 7d3182ad..00000000 --- a/lib/markbaker/complex/classes/src/functions/inverse.php +++ /dev/null @@ -1,29 +0,0 @@ -getReal() == 0.0 && $complex->getImaginary() == 0.0) { - throw new \InvalidArgumentException('Division by zero'); - } - - return $complex->divideInto(1.0); -} diff --git a/lib/markbaker/complex/classes/src/functions/ln.php b/lib/markbaker/complex/classes/src/functions/ln.php deleted file mode 100644 index 39071cf6..00000000 --- a/lib/markbaker/complex/classes/src/functions/ln.php +++ /dev/null @@ -1,33 +0,0 @@ -getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { - throw new \InvalidArgumentException(); - } - - return new Complex( - \log(rho($complex)), - theta($complex), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/log10.php b/lib/markbaker/complex/classes/src/functions/log10.php deleted file mode 100644 index 694d3d08..00000000 --- a/lib/markbaker/complex/classes/src/functions/log10.php +++ /dev/null @@ -1,32 +0,0 @@ -getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { - throw new \InvalidArgumentException(); - } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) { - return new Complex(\log10($complex->getReal()), 0.0, $complex->getSuffix()); - } - - return ln($complex) - ->multiply(\log10(Complex::EULER)); -} diff --git a/lib/markbaker/complex/classes/src/functions/log2.php b/lib/markbaker/complex/classes/src/functions/log2.php deleted file mode 100644 index 081f2c49..00000000 --- a/lib/markbaker/complex/classes/src/functions/log2.php +++ /dev/null @@ -1,32 +0,0 @@ -getReal() == 0.0) && ($complex->getImaginary() == 0.0)) { - throw new \InvalidArgumentException(); - } elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) { - return new Complex(\log($complex->getReal(), 2), 0.0, $complex->getSuffix()); - } - - return ln($complex) - ->multiply(\log(Complex::EULER, 2)); -} diff --git a/lib/markbaker/complex/classes/src/functions/negative.php b/lib/markbaker/complex/classes/src/functions/negative.php deleted file mode 100644 index dbd11922..00000000 --- a/lib/markbaker/complex/classes/src/functions/negative.php +++ /dev/null @@ -1,31 +0,0 @@ -getReal(), - -1 * $complex->getImaginary(), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/pow.php b/lib/markbaker/complex/classes/src/functions/pow.php deleted file mode 100644 index 18ee2690..00000000 --- a/lib/markbaker/complex/classes/src/functions/pow.php +++ /dev/null @@ -1,40 +0,0 @@ -getImaginary() == 0.0 && $complex->getReal() >= 0.0) { - return new Complex(\pow($complex->getReal(), $power)); - } - - $rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary())); - $rPower = \pow($rValue, $power); - $theta = $complex->argument() * $power; - if ($theta == 0) { - return new Complex(1); - } - - return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix()); -} diff --git a/lib/markbaker/complex/classes/src/functions/rho.php b/lib/markbaker/complex/classes/src/functions/rho.php deleted file mode 100644 index 750f3f99..00000000 --- a/lib/markbaker/complex/classes/src/functions/rho.php +++ /dev/null @@ -1,28 +0,0 @@ -getReal() * $complex->getReal()) + - ($complex->getImaginary() * $complex->getImaginary()) - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/sec.php b/lib/markbaker/complex/classes/src/functions/sec.php deleted file mode 100644 index 7dd43eaf..00000000 --- a/lib/markbaker/complex/classes/src/functions/sec.php +++ /dev/null @@ -1,25 +0,0 @@ -isReal()) { - return new Complex(\sin($complex->getReal())); - } - - return new Complex( - \sin($complex->getReal()) * \cosh($complex->getImaginary()), - \cos($complex->getReal()) * \sinh($complex->getImaginary()), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/sinh.php b/lib/markbaker/complex/classes/src/functions/sinh.php deleted file mode 100644 index 4c0f6503..00000000 --- a/lib/markbaker/complex/classes/src/functions/sinh.php +++ /dev/null @@ -1,32 +0,0 @@ -isReal()) { - return new Complex(\sinh($complex->getReal())); - } - - return new Complex( - \sinh($complex->getReal()) * \cos($complex->getImaginary()), - \cosh($complex->getReal()) * \sin($complex->getImaginary()), - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/sqrt.php b/lib/markbaker/complex/classes/src/functions/sqrt.php deleted file mode 100644 index 9c171b88..00000000 --- a/lib/markbaker/complex/classes/src/functions/sqrt.php +++ /dev/null @@ -1,29 +0,0 @@ -getSuffix()); -} diff --git a/lib/markbaker/complex/classes/src/functions/tan.php b/lib/markbaker/complex/classes/src/functions/tan.php deleted file mode 100644 index 014d7981..00000000 --- a/lib/markbaker/complex/classes/src/functions/tan.php +++ /dev/null @@ -1,40 +0,0 @@ -isReal()) { - return new Complex(\tan($complex->getReal())); - } - - $real = $complex->getReal(); - $imaginary = $complex->getImaginary(); - $divisor = 1 + \pow(\tan($real), 2) * \pow(\tanh($imaginary), 2); - if ($divisor == 0.0) { - throw new \InvalidArgumentException('Division by zero'); - } - - return new Complex( - \pow(sech($imaginary)->getReal(), 2) * \tan($real) / $divisor, - \pow(sec($real)->getReal(), 2) * \tanh($imaginary) / $divisor, - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/tanh.php b/lib/markbaker/complex/classes/src/functions/tanh.php deleted file mode 100644 index 028741d6..00000000 --- a/lib/markbaker/complex/classes/src/functions/tanh.php +++ /dev/null @@ -1,35 +0,0 @@ -getReal(); - $imaginary = $complex->getImaginary(); - $divisor = \cos($imaginary) * \cos($imaginary) + \sinh($real) * \sinh($real); - if ($divisor == 0.0) { - throw new \InvalidArgumentException('Division by zero'); - } - - return new Complex( - \sinh($real) * \cosh($real) / $divisor, - 0.5 * \sin(2 * $imaginary) / $divisor, - $complex->getSuffix() - ); -} diff --git a/lib/markbaker/complex/classes/src/functions/theta.php b/lib/markbaker/complex/classes/src/functions/theta.php deleted file mode 100644 index d12866cd..00000000 --- a/lib/markbaker/complex/classes/src/functions/theta.php +++ /dev/null @@ -1,38 +0,0 @@ -getReal() == 0.0) { - if ($complex->isReal()) { - return 0.0; - } elseif ($complex->getImaginary() < 0.0) { - return M_PI / -2; - } - return M_PI / 2; - } elseif ($complex->getReal() > 0.0) { - return \atan($complex->getImaginary() / $complex->getReal()); - } elseif ($complex->getImaginary() < 0.0) { - return -(M_PI - \atan(\abs($complex->getImaginary()) / \abs($complex->getReal()))); - } - - return M_PI - \atan($complex->getImaginary() / \abs($complex->getReal())); -} diff --git a/lib/markbaker/complex/classes/src/operations/add.php b/lib/markbaker/complex/classes/src/operations/add.php deleted file mode 100644 index 10bd42f4..00000000 --- a/lib/markbaker/complex/classes/src/operations/add.php +++ /dev/null @@ -1,46 +0,0 @@ -isComplex() && $complex->isComplex() && - $result->getSuffix() !== $complex->getSuffix()) { - throw new Exception('Suffix Mismatch'); - } - - $real = $result->getReal() + $complex->getReal(); - $imaginary = $result->getImaginary() + $complex->getImaginary(); - - $result = new Complex( - $real, - $imaginary, - ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) - ); - } - - return $result; -} diff --git a/lib/markbaker/complex/classes/src/operations/divideby.php b/lib/markbaker/complex/classes/src/operations/divideby.php deleted file mode 100644 index 089e0ef9..00000000 --- a/lib/markbaker/complex/classes/src/operations/divideby.php +++ /dev/null @@ -1,56 +0,0 @@ -isComplex() && $complex->isComplex() && - $result->getSuffix() !== $complex->getSuffix()) { - throw new Exception('Suffix Mismatch'); - } - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - throw new \InvalidArgumentException('Division by zero'); - } - - $delta1 = ($result->getReal() * $complex->getReal()) + - ($result->getImaginary() * $complex->getImaginary()); - $delta2 = ($result->getImaginary() * $complex->getReal()) - - ($result->getReal() * $complex->getImaginary()); - $delta3 = ($complex->getReal() * $complex->getReal()) + - ($complex->getImaginary() * $complex->getImaginary()); - - $real = $delta1 / $delta3; - $imaginary = $delta2 / $delta3; - - $result = new Complex( - $real, - $imaginary, - ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) - ); - } - - return $result; -} diff --git a/lib/markbaker/complex/classes/src/operations/divideinto.php b/lib/markbaker/complex/classes/src/operations/divideinto.php deleted file mode 100644 index 3dfe085e..00000000 --- a/lib/markbaker/complex/classes/src/operations/divideinto.php +++ /dev/null @@ -1,56 +0,0 @@ -isComplex() && $complex->isComplex() && - $result->getSuffix() !== $complex->getSuffix()) { - throw new Exception('Suffix Mismatch'); - } - if ($result->getReal() == 0.0 && $result->getImaginary() == 0.0) { - throw new \InvalidArgumentException('Division by zero'); - } - - $delta1 = ($complex->getReal() * $result->getReal()) + - ($complex->getImaginary() * $result->getImaginary()); - $delta2 = ($complex->getImaginary() * $result->getReal()) - - ($complex->getReal() * $result->getImaginary()); - $delta3 = ($result->getReal() * $result->getReal()) + - ($result->getImaginary() * $result->getImaginary()); - - $real = $delta1 / $delta3; - $imaginary = $delta2 / $delta3; - - $result = new Complex( - $real, - $imaginary, - ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) - ); - } - - return $result; -} diff --git a/lib/markbaker/complex/classes/src/operations/multiply.php b/lib/markbaker/complex/classes/src/operations/multiply.php deleted file mode 100644 index bf2473ea..00000000 --- a/lib/markbaker/complex/classes/src/operations/multiply.php +++ /dev/null @@ -1,48 +0,0 @@ -isComplex() && $complex->isComplex() && - $result->getSuffix() !== $complex->getSuffix()) { - throw new Exception('Suffix Mismatch'); - } - - $real = ($result->getReal() * $complex->getReal()) - - ($result->getImaginary() * $complex->getImaginary()); - $imaginary = ($result->getReal() * $complex->getImaginary()) + - ($result->getImaginary() * $complex->getReal()); - - $result = new Complex( - $real, - $imaginary, - ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) - ); - } - - return $result; -} diff --git a/lib/markbaker/complex/classes/src/operations/subtract.php b/lib/markbaker/complex/classes/src/operations/subtract.php deleted file mode 100644 index 075ef443..00000000 --- a/lib/markbaker/complex/classes/src/operations/subtract.php +++ /dev/null @@ -1,46 +0,0 @@ -isComplex() && $complex->isComplex() && - $result->getSuffix() !== $complex->getSuffix()) { - throw new Exception('Suffix Mismatch'); - } - - $real = $result->getReal() - $complex->getReal(); - $imaginary = $result->getImaginary() - $complex->getImaginary(); - - $result = new Complex( - $real, - $imaginary, - ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix()) - ); - } - - return $result; -} diff --git a/lib/markbaker/complex/composer.json b/lib/markbaker/complex/composer.json index fdf9a08f..ea1d06f5 100644 --- a/lib/markbaker/complex/composer.json +++ b/lib/markbaker/complex/composer.json @@ -12,83 +12,22 @@ } ], "require": { - "php": "^5.6.0|^7.0.0" + "php": "^7.2 || ^8.0" }, "require-dev": { - "phpunit/phpunit": "^4.8.35|^5.4.0", - "phpdocumentor/phpdocumentor":"2.*", - "phpmd/phpmd": "2.*", - "sebastian/phpcpd": "2.*", - "phploc/phploc": "2.*", - "squizlabs/php_codesniffer": "^3.4.0", + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.3", + "squizlabs/php_codesniffer": "^3.4", "phpcompatibility/php-compatibility": "^9.0", - "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0" + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0" }, "autoload": { "psr-4": { "Complex\\": "classes/src/" - }, - "files": [ - "classes/src/functions/abs.php", - "classes/src/functions/acos.php", - "classes/src/functions/acosh.php", - "classes/src/functions/acot.php", - "classes/src/functions/acoth.php", - "classes/src/functions/acsc.php", - "classes/src/functions/acsch.php", - "classes/src/functions/argument.php", - "classes/src/functions/asec.php", - "classes/src/functions/asech.php", - "classes/src/functions/asin.php", - "classes/src/functions/asinh.php", - "classes/src/functions/atan.php", - "classes/src/functions/atanh.php", - "classes/src/functions/conjugate.php", - "classes/src/functions/cos.php", - "classes/src/functions/cosh.php", - "classes/src/functions/cot.php", - "classes/src/functions/coth.php", - "classes/src/functions/csc.php", - "classes/src/functions/csch.php", - "classes/src/functions/exp.php", - "classes/src/functions/inverse.php", - "classes/src/functions/ln.php", - "classes/src/functions/log2.php", - "classes/src/functions/log10.php", - "classes/src/functions/negative.php", - "classes/src/functions/pow.php", - "classes/src/functions/rho.php", - "classes/src/functions/sec.php", - "classes/src/functions/sech.php", - "classes/src/functions/sin.php", - "classes/src/functions/sinh.php", - "classes/src/functions/sqrt.php", - "classes/src/functions/tan.php", - "classes/src/functions/tanh.php", - "classes/src/functions/theta.php", - "classes/src/operations/add.php", - "classes/src/operations/subtract.php", - "classes/src/operations/multiply.php", - "classes/src/operations/divideby.php", - "classes/src/operations/divideinto.php" - ] + } }, "scripts": { - "style": [ - "phpcs --report-width=200 --report=summary,full -n" - ], - "mess": [ - "phpmd classes/src/ xml codesize,unusedcode,design,naming -n" - ], - "lines": [ - "phploc classes/src/ -n" - ], - "cpd": [ - "phpcpd classes/src/ -n" - ], - "versions": [ - "phpcs --report-width=200 --report=summary,full classes/src/ --standard=PHPCompatibility --runtime-set testVersion 5.6- -n" - ] + "style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n", + "versions": "phpcs --report-width=200 --standard=PHPCompatibility --report=summary,full classes/src/ --runtime-set testVersion 7.2- -n" }, "minimum-stability": "dev" -} \ No newline at end of file +} diff --git a/lib/markbaker/complex/examples/complexTest.php b/lib/markbaker/complex/examples/complexTest.php new file mode 100644 index 00000000..9a5e1238 --- /dev/null +++ b/lib/markbaker/complex/examples/complexTest.php @@ -0,0 +1,154 @@ +add(456); +echo $x, PHP_EOL; + +$x = new Complex(123.456); +$x->add(789.012); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->add(new Complex(-987.654, -32.1)); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->add(-987.654); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->add(new Complex(0, 1)); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->add(new Complex(0, -1)); +echo $x, PHP_EOL; + + +echo PHP_EOL, 'Subtract', PHP_EOL; + +$x = new Complex(123); +$x->subtract(456); +echo $x, PHP_EOL; + +$x = new Complex(123.456); +$x->subtract(789.012); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->subtract(new Complex(-987.654, -32.1)); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->subtract(-987.654); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->subtract(new Complex(0, 1)); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->subtract(new Complex(0, -1)); +echo $x, PHP_EOL; + + +echo PHP_EOL, 'Multiply', PHP_EOL; + +$x = new Complex(123); +$x->multiply(456); +echo $x, PHP_EOL; + +$x = new Complex(123.456); +$x->multiply(789.012); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->multiply(new Complex(-987.654, -32.1)); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->multiply(-987.654); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->multiply(new Complex(0, 1)); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->multiply(new Complex(0, -1)); +echo $x, PHP_EOL; + + +echo PHP_EOL, 'Divide By', PHP_EOL; + +$x = new Complex(123); +$x->divideBy(456); +echo $x, PHP_EOL; + +$x = new Complex(123.456); +$x->divideBy(789.012); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->divideBy(new Complex(-987.654, -32.1)); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->divideBy(-987.654); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->divideBy(new Complex(0, 1)); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->divideBy(new Complex(0, -1)); +echo $x, PHP_EOL; + + +echo PHP_EOL, 'Divide Into', PHP_EOL; + +$x = new Complex(123); +$x->divideInto(456); +echo $x, PHP_EOL; + +$x = new Complex(123.456); +$x->divideInto(789.012); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->divideInto(new Complex(-987.654, -32.1)); +echo $x, PHP_EOL; + +$x = new Complex(123.456, 78.90); +$x->divideInto(-987.654); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->divideInto(new Complex(0, 1)); +echo $x, PHP_EOL; + +$x = new Complex(-987.654, -32.1); +$x->divideInto(new Complex(0, -1)); +echo $x, PHP_EOL; diff --git a/lib/markbaker/complex/examples/testFunctions.php b/lib/markbaker/complex/examples/testFunctions.php new file mode 100644 index 00000000..bad1c03d --- /dev/null +++ b/lib/markbaker/complex/examples/testFunctions.php @@ -0,0 +1,52 @@ +getMessage(), PHP_EOL; + } + } + echo PHP_EOL; + } +} diff --git a/lib/markbaker/complex/examples/testOperations.php b/lib/markbaker/complex/examples/testOperations.php new file mode 100644 index 00000000..2b7e0ba4 --- /dev/null +++ b/lib/markbaker/complex/examples/testOperations.php @@ -0,0 +1,35 @@ + ', $result, PHP_EOL; + +echo PHP_EOL; + +echo 'Subtraction', PHP_EOL; + +$result = Operations::subtract(...$values); +echo '=> ', $result, PHP_EOL; + +echo PHP_EOL; + +echo 'Multiplication', PHP_EOL; + +$result = Operations::multiply(...$values); +echo '=> ', $result, PHP_EOL; diff --git a/lib/markbaker/matrix/.github/workflows/main.yaml b/lib/markbaker/matrix/.github/workflows/main.yaml new file mode 100644 index 00000000..158fcdfc --- /dev/null +++ b/lib/markbaker/matrix/.github/workflows/main.yaml @@ -0,0 +1,118 @@ +name: main +on: [ push, pull_request ] +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + php-version: + - '7.1' + - '7.2' + - '7.3' + - '7.4' + - '8.0' + - '8.1' + + name: PHP ${{ matrix.php-version }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib + coverage: none + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Set composer flags + id: composer-lock + if: ${{ matrix.php-version == '8.0' || matrix.php-version == '8.1' }} + run: | + echo "::set-output name=flags::--ignore-platform-reqs" + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader ${{ steps.composer-lock.outputs.flags }} + + - name: Setup problem matchers for PHP + run: echo "::add-matcher::${{ runner.tool_cache }}/php.json" + + - name: Setup problem matchers for PHPUnit + run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Test with PHPUnit + run: ./vendor/bin/phpunit + + phpcs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib + coverage: none + tools: cs2pr + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Code style with PHP_CodeSniffer + run: ./vendor/bin/phpcs -q --report=checkstyle | cs2pr --graceful-warnings --colorize + + coverage: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Setup PHP, with composer and extensions + uses: shivammathur/setup-php@v2 + with: + php-version: 7.4 + extensions: ctype, dom, gd, iconv, fileinfo, libxml, mbstring, simplexml, xml, xmlreader, xmlwriter, zip, zlib + coverage: pcov + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache composer dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: ${{ runner.os }}-composer- + + - name: Install dependencies + run: composer install --no-progress --prefer-dist --optimize-autoloader + + - name: Coverage + run: | + ./vendor/bin/phpunit --coverage-text diff --git a/lib/markbaker/matrix/README.md b/lib/markbaker/matrix/README.md index 66a1de4d..d0dc9145 100644 --- a/lib/markbaker/matrix/README.md +++ b/lib/markbaker/matrix/README.md @@ -5,9 +5,11 @@ PHPMatrix PHP Class for handling Matrices -Master: [![Build Status](https://travis-ci.org/MarkBaker/PHPMatrix.png?branch=master)](http://travis-ci.org/MarkBaker/PHPMatrix) +[![Build Status](https://github.com/MarkBaker/PHPMatrix/workflows/main/badge.svg)](https://github.com/MarkBaker/PHPMatrix/actions) +[![Total Downloads](https://img.shields.io/packagist/dt/markbaker/matrix)](https://packagist.org/packages/markbaker/matrix) +[![Latest Stable Version](https://img.shields.io/github/v/release/MarkBaker/PHPMatrix)](https://packagist.org/packages/markbaker/matrix) +[![License](https://img.shields.io/github/license/MarkBaker/PHPMatrix)](https://packagist.org/packages/markbaker/matrix) -Develop: [![Build Status](https://travis-ci.org/MarkBaker/PHPMatrix.png?branch=develop)](http://travis-ci.org/MarkBaker/PHPMatrix) [![Matrix Transform](https://imgs.xkcd.com/comics/matrix_transform.png)](https://xkcd.com/184/) @@ -37,22 +39,54 @@ together with functions for - minors - trace - transpose + - solve + Given Matrices A and B, calculate X for A.X = B + +and classes for + + - Decomposition + - LU Decomposition with partial row pivoting, + + such that [P].[A] = [L].[U] and [A] = [P]|.[L].[U] + - QR Decomposition + + such that [A] = [Q].[R] ## TO DO - - power() - - EigenValues - - EigenVectors + - power() function - Decomposition + - Cholesky Decomposition + - EigenValue Decomposition + - EigenValues + - EigenVectors --- +# Installation + +```shell +composer require markbaker/matrix:^3.0 +``` + +# Important BC Note + +If you've previously been using procedural calls to functions and operations using this library, then from version 3.0 you should use [MarkBaker/PHPMatrixFunctions](https://github.com/MarkBaker/PHPMatrixFunctions) instead (available on packagist as [markbaker/matrix-functions](https://packagist.org/packages/markbaker/matrix-functions)). + +You'll need to replace `markbaker/matrix`in your `composer.json` file with the new library, but otherwise there should be no difference in the namespacing, or in the way that you have called the Matrix functions in the past, so no actual code changes are required. + +```shell +composer require markbaker/matrix-functions:^1.0 +``` + +You should not reference this library (`markbaker/matrix`) in your `composer.json`, composer wil take care of that for you. + # Usage To create a new Matrix object, provide an array as the constructor argument -``` +```php $grid = [ [16, 3, 2, 13], [ 5, 10, 11, 8], @@ -63,12 +97,12 @@ $grid = [ $matrix = new Matrix\Matrix($grid); ``` The `Builder` class provides helper methods for creating specific matrices, specifically an identity matrix of a specified size; or a matrix of a specified dimensions, with every cell containing a set value. -``` -$matrix = new Matrix\Builder::createFilledMatrix(1, 5, 3); +```php +$matrix = Matrix\Builder::createFilledMatrix(1, 5, 3); ``` Will create a matrix of 5 rows and 3 columns, filled with a `1` in every cell; while -``` -$matrix = new Matrix\Builder::createIdentityMatrix(3); +```php +$matrix = Matrix\Builder::createIdentityMatrix(3); ``` will create a 3x3 identity matrix. @@ -79,34 +113,34 @@ Matrix objects are immutable: whenever you call a method or pass a grid to a fun To perform mathematical operations with Matrices, you can call the appropriate method against a matrix value, passing other values as arguments -``` -$matrix1 = new Matrix([ +```php +$matrix1 = new Matrix\Matrix([ [2, 7, 6], [9, 5, 1], [4, 3, 8], ]); -$matrix2 = new Matrix([ +$matrix2 = new Matrix\Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]); -echo $matrix1->multiply($matrix2); -``` -or pass all values to the appropriate function +var_dump($matrix1->multiply($matrix2)->toArray()); ``` -$matrix1 = new Matrix([ +or pass all values to the appropriate static method +```php +$matrix1 = new Matrix\Matrix([ [2, 7, 6], [9, 5, 1], [4, 3, 8], ]); -$matrix2 = new Matrix([ +$matrix2 = new Matrix\Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]); -echo Matrix\multiply($matrix1, $matrix2); +var_dump(Matrix\Operations::multiply($matrix1, $matrix2)->toArray()); ``` You can pass in the arguments as Matrix objects, or as arrays. @@ -115,7 +149,7 @@ If you want to perform the same operation against multiple values (e.g. to add t ## Using functions When calling any of the available functions for a matrix value, you can either call the relevant method for the Matrix object -``` +```php $grid = [ [16, 3, 2, 13], [ 5, 10, 11, 8], @@ -127,8 +161,8 @@ $matrix = new Matrix\Matrix($grid); echo $matrix->trace(); ``` -or you can call the function as you would in procedural code, passing the Matrix object as an argument -``` +or you can call the static method, passing the Matrix object or array as an argument +```php $grid = [ [16, 3, 2, 13], [ 5, 10, 11, 8], @@ -137,10 +171,9 @@ $grid = [ ]; $matrix = new Matrix\Matrix($grid); -echo Matrix\trace($matrix); -``` -When called procedurally using the function, you can pass in the argument as a Matrix object, or as an array. +echo Matrix\Functions::trace($matrix); ``` +```php $grid = [ [16, 3, 2, 13], [ 5, 10, 11, 8], @@ -148,18 +181,35 @@ $grid = [ [ 4, 15, 14, 1], ]; -echo Matrix\trace($grid); +echo Matrix\Functions::trace($grid); ``` -As an alternative, it is also possible to call the method directly from the `Functions` class. + +## Decomposition + +The library also provides classes for matrix decomposition. You can access these using +```php +$grid = [ + [1, 2], + [3, 4], +]; + +$matrix = new Matrix\Matrix($grid); + +$decomposition = new Matrix\Decomposition\QR($matrix); +$Q = $decomposition->getQ(); +$R = $decomposition->getR(); ``` + +or alternatively us the `Decomposition` factory, identifying which form of decomposition you want to use +```php $grid = [ - [16, 3, 2, 13], - [ 5, 10, 11, 8], - [ 9, 6, 7, 12], - [ 4, 15, 14, 1], + [1, 2], + [3, 4], ]; $matrix = new Matrix\Matrix($grid); -echo Matrix\Functions::trace($matrix); + +$decomposition = Matrix\Decomposition\Decomposition::decomposition(Matrix\Decomposition\Decomposition::QR, $matrix); +$Q = $decomposition->getQ(); +$R = $decomposition->getR(); ``` -Used this way, methods must be called statically, and the argument must be the Matrix object, and cannot be an array. diff --git a/lib/markbaker/matrix/buildPhar.php b/lib/markbaker/matrix/buildPhar.php new file mode 100644 index 00000000..e1b8f96f --- /dev/null +++ b/lib/markbaker/matrix/buildPhar.php @@ -0,0 +1,62 @@ + 'Mark Baker ', + 'Description' => 'PHP Class for working with Matrix numbers', + 'Copyright' => 'Mark Baker (c) 2013-' . date('Y'), + 'Timestamp' => time(), + 'Version' => '0.1.0', + 'Date' => date('Y-m-d') +); + +// cleanup +if (file_exists($pharName)) { + echo "Removed: {$pharName}\n"; + unlink($pharName); +} + +echo "Building phar file...\n"; + +// the phar object +$phar = new Phar($pharName, null, 'Matrix'); +$phar->buildFromDirectory($sourceDir); +$phar->setStub( +<<<'EOT' +getMessage()); + exit(1); + } + + include 'phar://functions/sqrt.php'; + + __HALT_COMPILER(); +EOT +); +$phar->setMetadata($metaData); +$phar->compressFiles(Phar::GZ); + +echo "Complete.\n"; + +exit(); diff --git a/lib/markbaker/matrix/classes/Autoloader.php b/lib/markbaker/matrix/classes/Autoloader.php deleted file mode 100644 index 279d176e..00000000 --- a/lib/markbaker/matrix/classes/Autoloader.php +++ /dev/null @@ -1,53 +0,0 @@ -regex = $regex; - parent::__construct($it, $regex); - } -} - -class FilenameFilter extends FilesystemRegexFilter -{ - // Filter files against the regex - public function accept() - { - return (!$this->isFile() || preg_match($this->regex, $this->getFilename())); - } -} - - -$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src'; -$srcDirectory = new RecursiveDirectoryIterator($srcFolder); - -$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i'); -$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Matrix|Exception)\.php).*$/i'); - -foreach (new RecursiveIteratorIterator($filteredFileList) as $file) { - if ($file->isFile()) { - include_once $file; - } -} diff --git a/lib/markbaker/matrix/classes/src/Builder.php b/lib/markbaker/matrix/classes/src/Builder.php index 6bc334ad..161bb688 100644 --- a/lib/markbaker/matrix/classes/src/Builder.php +++ b/lib/markbaker/matrix/classes/src/Builder.php @@ -21,13 +21,13 @@ class Builder * Create a new matrix of specified dimensions, and filled with a specified value * If the column argument isn't provided, then a square matrix will be created * - * @param mixed $value + * @param mixed $fillValue * @param int $rows * @param int|null $columns * @return Matrix * @throws Exception */ - public static function createFilledMatrix($value, $rows, $columns = null) + public static function createFilledMatrix($fillValue, $rows, $columns = null) { if ($columns === null) { $columns = $rows; @@ -43,7 +43,7 @@ public static function createFilledMatrix($value, $rows, $columns = null) array_fill( 0, $columns, - $value + $fillValue ) ) ); @@ -57,9 +57,9 @@ public static function createFilledMatrix($value, $rows, $columns = null) * @return Matrix * @throws Exception */ - public static function createIdentityMatrix($dimensions) + public static function createIdentityMatrix($dimensions, $fillValue = null) { - $grid = static::createFilledMatrix(null, $dimensions)->toArray(); + $grid = static::createFilledMatrix($fillValue, $dimensions)->toArray(); for ($x = 0; $x < $dimensions; ++$x) { $grid[$x][$x] = 1; diff --git a/lib/markbaker/matrix/classes/src/Decomposition/Decomposition.php b/lib/markbaker/matrix/classes/src/Decomposition/Decomposition.php new file mode 100644 index 00000000..f0144487 --- /dev/null +++ b/lib/markbaker/matrix/classes/src/Decomposition/Decomposition.php @@ -0,0 +1,27 @@ +luMatrix = $matrix->toArray(); + $this->rows = $matrix->rows; + $this->columns = $matrix->columns; + + $this->buildPivot(); + } + + /** + * Get lower triangular factor. + * + * @return Matrix Lower triangular factor + */ + public function getL(): Matrix + { + $lower = []; + + $columns = min($this->rows, $this->columns); + for ($row = 0; $row < $this->rows; ++$row) { + for ($column = 0; $column < $columns; ++$column) { + if ($row > $column) { + $lower[$row][$column] = $this->luMatrix[$row][$column]; + } elseif ($row === $column) { + $lower[$row][$column] = 1.0; + } else { + $lower[$row][$column] = 0.0; + } + } + } + + return new Matrix($lower); + } + + /** + * Get upper triangular factor. + * + * @return Matrix Upper triangular factor + */ + public function getU(): Matrix + { + $upper = []; + + $rows = min($this->rows, $this->columns); + for ($row = 0; $row < $rows; ++$row) { + for ($column = 0; $column < $this->columns; ++$column) { + if ($row <= $column) { + $upper[$row][$column] = $this->luMatrix[$row][$column]; + } else { + $upper[$row][$column] = 0.0; + } + } + } + + return new Matrix($upper); + } + + /** + * Return pivot permutation vector. + * + * @return Matrix Pivot matrix + */ + public function getP(): Matrix + { + $pMatrix = []; + + $pivots = $this->pivot; + $pivotCount = count($pivots); + foreach ($pivots as $row => $pivot) { + $pMatrix[$row] = array_fill(0, $pivotCount, 0); + $pMatrix[$row][$pivot] = 1; + } + + return new Matrix($pMatrix); + } + + /** + * Return pivot permutation vector. + * + * @return array Pivot vector + */ + public function getPivot(): array + { + return $this->pivot; + } + + /** + * Is the matrix nonsingular? + * + * @return bool true if U, and hence A, is nonsingular + */ + public function isNonsingular(): bool + { + for ($diagonal = 0; $diagonal < $this->columns; ++$diagonal) { + if ($this->luMatrix[$diagonal][$diagonal] === 0.0) { + return false; + } + } + + return true; + } + + private function buildPivot(): void + { + for ($row = 0; $row < $this->rows; ++$row) { + $this->pivot[$row] = $row; + } + + for ($column = 0; $column < $this->columns; ++$column) { + $luColumn = $this->localisedReferenceColumn($column); + + $this->applyTransformations($column, $luColumn); + + $pivot = $this->findPivot($column, $luColumn); + if ($pivot !== $column) { + $this->pivotExchange($pivot, $column); + } + + $this->computeMultipliers($column); + + unset($luColumn); + } + } + + private function localisedReferenceColumn($column): array + { + $luColumn = []; + + for ($row = 0; $row < $this->rows; ++$row) { + $luColumn[$row] = &$this->luMatrix[$row][$column]; + } + + return $luColumn; + } + + private function applyTransformations($column, array $luColumn): void + { + for ($row = 0; $row < $this->rows; ++$row) { + $luRow = $this->luMatrix[$row]; + // Most of the time is spent in the following dot product. + $kmax = min($row, $column); + $sValue = 0.0; + for ($kValue = 0; $kValue < $kmax; ++$kValue) { + $sValue += $luRow[$kValue] * $luColumn[$kValue]; + } + $luRow[$column] = $luColumn[$row] -= $sValue; + } + } + + private function findPivot($column, array $luColumn): int + { + $pivot = $column; + for ($row = $column + 1; $row < $this->rows; ++$row) { + if (abs($luColumn[$row]) > abs($luColumn[$pivot])) { + $pivot = $row; + } + } + + return $pivot; + } + + private function pivotExchange($pivot, $column): void + { + for ($kValue = 0; $kValue < $this->columns; ++$kValue) { + $tValue = $this->luMatrix[$pivot][$kValue]; + $this->luMatrix[$pivot][$kValue] = $this->luMatrix[$column][$kValue]; + $this->luMatrix[$column][$kValue] = $tValue; + } + + $lValue = $this->pivot[$pivot]; + $this->pivot[$pivot] = $this->pivot[$column]; + $this->pivot[$column] = $lValue; + } + + private function computeMultipliers($diagonal): void + { + if (($diagonal < $this->rows) && ($this->luMatrix[$diagonal][$diagonal] != 0.0)) { + for ($row = $diagonal + 1; $row < $this->rows; ++$row) { + $this->luMatrix[$row][$diagonal] /= $this->luMatrix[$diagonal][$diagonal]; + } + } + } + + private function pivotB(Matrix $B): array + { + $X = []; + foreach ($this->pivot as $rowId) { + $row = $B->getRows($rowId + 1)->toArray(); + $X[] = array_pop($row); + } + + return $X; + } + + /** + * Solve A*X = B. + * + * @param Matrix $B a Matrix with as many rows as A and any number of columns + * + * @throws Exception + * + * @return Matrix X so that L*U*X = B(piv,:) + */ + public function solve(Matrix $B): Matrix + { + if ($B->rows !== $this->rows) { + throw new Exception('Matrix row dimensions are not equal'); + } + + if ($this->rows !== $this->columns) { + throw new Exception('LU solve() only works on square matrices'); + } + + if (!$this->isNonsingular()) { + throw new Exception('Can only perform operation on singular matrix'); + } + + // Copy right hand side with pivoting + $nx = $B->columns; + $X = $this->pivotB($B); + + // Solve L*Y = B(piv,:) + for ($k = 0; $k < $this->columns; ++$k) { + for ($i = $k + 1; $i < $this->columns; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->luMatrix[$i][$k]; + } + } + } + + // Solve U*X = Y; + for ($k = $this->columns - 1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->luMatrix[$k][$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->luMatrix[$i][$k]; + } + } + } + + return new Matrix($X); + } +} diff --git a/lib/markbaker/matrix/classes/src/Decomposition/QR.php b/lib/markbaker/matrix/classes/src/Decomposition/QR.php new file mode 100644 index 00000000..4b6106f6 --- /dev/null +++ b/lib/markbaker/matrix/classes/src/Decomposition/QR.php @@ -0,0 +1,191 @@ +qrMatrix = $matrix->toArray(); + $this->rows = $matrix->rows; + $this->columns = $matrix->columns; + + $this->decompose(); + } + + public function getHouseholdVectors(): Matrix + { + $householdVectors = []; + for ($row = 0; $row < $this->rows; ++$row) { + for ($column = 0; $column < $this->columns; ++$column) { + if ($row >= $column) { + $householdVectors[$row][$column] = $this->qrMatrix[$row][$column]; + } else { + $householdVectors[$row][$column] = 0.0; + } + } + } + + return new Matrix($householdVectors); + } + + public function getQ(): Matrix + { + $qGrid = []; + + $rowCount = $this->rows; + for ($k = $this->columns - 1; $k >= 0; --$k) { + for ($i = 0; $i < $this->rows; ++$i) { + $qGrid[$i][$k] = 0.0; + } + $qGrid[$k][$k] = 1.0; + if ($this->columns > $this->rows) { + $qGrid = array_slice($qGrid, 0, $this->rows); + } + + for ($j = $k; $j < $this->columns; ++$j) { + if (isset($this->qrMatrix[$k], $this->qrMatrix[$k][$k]) && $this->qrMatrix[$k][$k] != 0.0) { + $s = 0.0; + for ($i = $k; $i < $this->rows; ++$i) { + $s += $this->qrMatrix[$i][$k] * $qGrid[$i][$j]; + } + $s = -$s / $this->qrMatrix[$k][$k]; + for ($i = $k; $i < $this->rows; ++$i) { + $qGrid[$i][$j] += $s * $this->qrMatrix[$i][$k]; + } + } + } + } + + array_walk( + $qGrid, + function (&$row) use ($rowCount) { + $row = array_reverse($row); + $row = array_slice($row, 0, $rowCount); + } + ); + + return new Matrix($qGrid); + } + + public function getR(): Matrix + { + $rGrid = []; + + for ($row = 0; $row < $this->columns; ++$row) { + for ($column = 0; $column < $this->columns; ++$column) { + if ($row < $column) { + $rGrid[$row][$column] = $this->qrMatrix[$row][$column] ?? 0.0; + } elseif ($row === $column) { + $rGrid[$row][$column] = $this->rDiagonal[$row] ?? 0.0; + } else { + $rGrid[$row][$column] = 0.0; + } + } + } + + if ($this->columns > $this->rows) { + $rGrid = array_slice($rGrid, 0, $this->rows); + } + + return new Matrix($rGrid); + } + + private function hypo($a, $b): float + { + if (abs($a) > abs($b)) { + $r = $b / $a; + $r = abs($a) * sqrt(1 + $r * $r); + } elseif ($b != 0.0) { + $r = $a / $b; + $r = abs($b) * sqrt(1 + $r * $r); + } else { + $r = 0.0; + } + + return $r; + } + + /** + * QR Decomposition computed by Householder reflections. + */ + private function decompose(): void + { + for ($k = 0; $k < $this->columns; ++$k) { + // Compute 2-norm of k-th column without under/overflow. + $norm = 0.0; + for ($i = $k; $i < $this->rows; ++$i) { + $norm = $this->hypo($norm, $this->qrMatrix[$i][$k]); + } + if ($norm != 0.0) { + // Form k-th Householder vector. + if ($this->qrMatrix[$k][$k] < 0.0) { + $norm = -$norm; + } + for ($i = $k; $i < $this->rows; ++$i) { + $this->qrMatrix[$i][$k] /= $norm; + } + $this->qrMatrix[$k][$k] += 1.0; + // Apply transformation to remaining columns. + for ($j = $k + 1; $j < $this->columns; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->rows; ++$i) { + $s += $this->qrMatrix[$i][$k] * $this->qrMatrix[$i][$j]; + } + $s = -$s / $this->qrMatrix[$k][$k]; + for ($i = $k; $i < $this->rows; ++$i) { + $this->qrMatrix[$i][$j] += $s * $this->qrMatrix[$i][$k]; + } + } + } + $this->rDiagonal[$k] = -$norm; + } + } + + public function isFullRank(): bool + { + for ($j = 0; $j < $this->columns; ++$j) { + if ($this->rDiagonal[$j] == 0.0) { + return false; + } + } + + return true; + } + + /** + * Least squares solution of A*X = B. + * + * @param Matrix $B a Matrix with as many rows as A and any number of columns + * + * @throws Exception + * + * @return Matrix matrix that minimizes the two norm of Q*R*X-B + */ + public function solve(Matrix $B): Matrix + { + if ($B->rows !== $this->rows) { + throw new Exception('Matrix row dimensions are not equal'); + } + + if (!$this->isFullRank()) { + throw new Exception('Can only perform this operation on a full-rank matrix'); + } + + // Compute Y = transpose(Q)*B + $Y = $this->getQ()->transpose() + ->multiply($B); + // Solve R*X = Y; + return $this->getR()->inverse() + ->multiply($Y); + } +} diff --git a/lib/markbaker/matrix/classes/src/Div0Exception.php b/lib/markbaker/matrix/classes/src/Div0Exception.php new file mode 100644 index 00000000..eba28f8a --- /dev/null +++ b/lib/markbaker/matrix/classes/src/Div0Exception.php @@ -0,0 +1,13 @@ +isSquare()) { throw new Exception('Adjoint can only be calculated for a square matrix'); } @@ -67,13 +88,15 @@ private static function getCofactors(Matrix $matrix) /** * Return the cofactors of this matrix * - * @param Matrix $matrix The matrix whose cofactors we wish to calculate + * @param Matrix|array $matrix The matrix whose cofactors we wish to calculate * @return Matrix * * @throws Exception */ - public static function cofactors(Matrix $matrix) + public static function cofactors($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Cofactors can only be calculated for a square matrix'); } @@ -141,12 +164,14 @@ private static function getDeterminant(Matrix $matrix) /** * Return the determinant of this matrix * - * @param Matrix $matrix The matrix whose determinant we wish to calculate + * @param Matrix|array $matrix The matrix whose determinant we wish to calculate * @return float * @throws Exception **/ - public static function determinant(Matrix $matrix) + public static function determinant($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Determinant can only be calculated for a square matrix'); } @@ -157,12 +182,14 @@ public static function determinant(Matrix $matrix) /** * Return the diagonal of this matrix * - * @param Matrix $matrix The matrix whose diagonal we wish to calculate + * @param Matrix|array $matrix The matrix whose diagonal we wish to calculate * @return Matrix * @throws Exception **/ - public static function diagonal(Matrix $matrix) + public static function diagonal($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Diagonal can only be extracted from a square matrix'); } @@ -181,12 +208,14 @@ public static function diagonal(Matrix $matrix) /** * Return the antidiagonal of this matrix * - * @param Matrix $matrix The matrix whose antidiagonal we wish to calculate + * @param Matrix|array $matrix The matrix whose antidiagonal we wish to calculate * @return Matrix * @throws Exception **/ - public static function antidiagonal(Matrix $matrix) + public static function antidiagonal($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Anti-Diagonal can only be extracted from a square matrix'); } @@ -207,12 +236,14 @@ public static function antidiagonal(Matrix $matrix) * The identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix * with ones on the main diagonal and zeros elsewhere * - * @param Matrix $matrix The matrix whose identity we wish to calculate + * @param Matrix|array $matrix The matrix whose identity we wish to calculate * @return Matrix * @throws Exception **/ - public static function identity(Matrix $matrix) + public static function identity($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Identity can only be created for a square matrix'); } @@ -225,19 +256,21 @@ public static function identity(Matrix $matrix) /** * Return the inverse of this matrix * - * @param Matrix $matrix The matrix whose inverse we wish to calculate + * @param Matrix|array $matrix The matrix whose inverse we wish to calculate * @return Matrix * @throws Exception **/ - public static function inverse(Matrix $matrix) + public static function inverse($matrix, string $type = 'inverse') { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { - throw new Exception('Inverse can only be calculated for a square matrix'); + throw new Exception(ucfirst($type) . ' can only be calculated for a square matrix'); } $determinant = self::getDeterminant($matrix); if ($determinant == 0.0) { - throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant'); + throw new Div0Exception(ucfirst($type) . ' can only be calculated for a matrix with a non-zero determinant'); } if ($matrix->rows == 1) { @@ -281,12 +314,14 @@ protected static function getMinors(Matrix $matrix) * calculating matrix cofactors, which in turn are useful for computing both the determinant and inverse of * square matrices. * - * @param Matrix $matrix The matrix whose minors we wish to calculate + * @param Matrix|array $matrix The matrix whose minors we wish to calculate * @return Matrix * @throws Exception **/ - public static function minors(Matrix $matrix) + public static function minors($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Minors can only be calculated for a square matrix'); } @@ -299,12 +334,14 @@ public static function minors(Matrix $matrix) * The trace is defined as the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) * of the matrix * - * @param Matrix $matrix The matrix whose trace we wish to calculate + * @param Matrix|array $matrix The matrix whose trace we wish to calculate * @return float * @throws Exception **/ - public static function trace(Matrix $matrix) + public static function trace($matrix) { + $matrix = self::validateMatrix($matrix); + if (!$matrix->isSquare()) { throw new Exception('Trace can only be extracted from a square matrix'); } @@ -321,11 +358,13 @@ public static function trace(Matrix $matrix) /** * Return the transpose of this matrix * - * @param Matrix $matrix The matrix whose transpose we wish to calculate + * @param Matrix|\a $matrix The matrix whose transpose we wish to calculate * @return Matrix **/ - public static function transpose(Matrix $matrix) + public static function transpose($matrix) { + $matrix = self::validateMatrix($matrix); + $array = array_values(array_merge([null], $matrix->toArray())); $grid = call_user_func_array( 'array_map', diff --git a/lib/markbaker/matrix/classes/src/Matrix.php b/lib/markbaker/matrix/classes/src/Matrix.php index a4f04951..95f55e75 100644 --- a/lib/markbaker/matrix/classes/src/Matrix.php +++ b/lib/markbaker/matrix/classes/src/Matrix.php @@ -10,6 +10,10 @@ namespace Matrix; +use Generator; +use Matrix\Decomposition\LU; +use Matrix\Decomposition\QR; + /** * Matrix object. * @@ -24,7 +28,6 @@ * @method Matrix diagonal() * @method Matrix identity() * @method Matrix inverse() - * @method Matrix pseudoInverse() * @method Matrix minors() * @method float trace() * @method Matrix transpose() @@ -33,6 +36,7 @@ * @method Matrix multiply(...$matrices) * @method Matrix divideby(...$matrices) * @method Matrix divideinto(...$matrices) + * @method Matrix directsum(...$matrices) */ class Matrix { @@ -55,7 +59,7 @@ final public function __construct(array $grid) * * @param array $grid */ - protected function buildFromArray(array $grid) + protected function buildFromArray(array $grid): void { $this->rows = count($grid); $columns = array_reduce( @@ -86,7 +90,7 @@ function (&$value) use ($columns) { * @return int * @throws Exception */ - public static function validateRow($row) + public static function validateRow(int $row): int { if ((!is_numeric($row)) || (intval($row) < 1)) { throw new Exception('Invalid Row'); @@ -102,7 +106,7 @@ public static function validateRow($row) * @return int * @throws Exception */ - public static function validateColumn($column) + public static function validateColumn(int $column): int { if ((!is_numeric($column)) || (intval($column) < 1)) { throw new Exception('Invalid Column'); @@ -118,7 +122,7 @@ public static function validateColumn($column) * @return int * @throws Exception */ - protected function validateRowInRange($row) + protected function validateRowInRange(int $row): int { $row = static::validateRow($row); if ($row > $this->rows) { @@ -135,7 +139,7 @@ protected function validateRowInRange($row) * @return int * @throws Exception */ - protected function validateColumnInRange($column) + protected function validateColumnInRange(int $column): int { $column = static::validateColumn($column); if ($column > $this->columns) { @@ -157,7 +161,7 @@ protected function validateColumnInRange($column) * @return static * @throws Exception */ - public function getRows($row, $rowCount = 1) + public function getRows(int $row, int $rowCount = 1): Matrix { $row = $this->validateRowInRange($row); if ($rowCount === 0) { @@ -179,7 +183,7 @@ public function getRows($row, $rowCount = 1) * @return Matrix * @throws Exception */ - public function getColumns($column, $columnCount = 1) + public function getColumns(int $column, int $columnCount = 1): Matrix { $column = $this->validateColumnInRange($column); if ($columnCount < 1) { @@ -207,7 +211,7 @@ public function getColumns($column, $columnCount = 1) * @return static * @throws Exception */ - public function dropRows($row, $rowCount = 1) + public function dropRows(int $row, int $rowCount = 1): Matrix { $this->validateRowInRange($row); if ($rowCount === 0) { @@ -233,7 +237,7 @@ public function dropRows($row, $rowCount = 1) * @return static * @throws Exception */ - public function dropColumns($column, $columnCount = 1) + public function dropColumns(int $column, int $columnCount = 1): Matrix { $this->validateColumnInRange($column); if ($columnCount < 1) { @@ -260,7 +264,7 @@ function (&$row) use ($column, $columnCount) { * @return mixed * @throws Exception */ - public function getValue($row, $column) + public function getValue(int $row, int $column) { $row = $this->validateRowInRange($row); $column = $this->validateColumnInRange($column); @@ -270,11 +274,11 @@ public function getValue($row, $column) /** * Returns a Generator that will yield each row of the matrix in turn as a vector matrix - * or the value of each cell if the matrix is a vector + * or the value of each cell if the matrix is a column vector * - * @return \Generator|Matrix[]|mixed[] + * @return Generator|Matrix[]|mixed[] */ - public function rows() + public function rows(): Generator { foreach ($this->grid as $i => $row) { yield $i + 1 => ($this->columns == 1) @@ -285,11 +289,11 @@ public function rows() /** * Returns a Generator that will yield each column of the matrix in turn as a vector matrix - * or the value of each cell if the matrix is a vector + * or the value of each cell if the matrix is a row vector * - * @return \Generator|Matrix[]|mixed[] + * @return Generator|Matrix[]|mixed[] */ - public function columns() + public function columns(): Generator { for ($i = 0; $i < $this->columns; ++$i) { yield $i + 1 => ($this->rows == 1) @@ -304,9 +308,9 @@ public function columns() * * @return bool */ - public function isSquare() + public function isSquare(): bool { - return $this->rows == $this->columns; + return $this->rows === $this->columns; } /** @@ -315,9 +319,9 @@ public function isSquare() * * @return bool */ - public function isVector() + public function isVector(): bool { - return $this->rows == 1 || $this->columns == 1; + return $this->rows === 1 || $this->columns === 1; } /** @@ -325,11 +329,29 @@ public function isVector() * * @return array */ - public function toArray() + public function toArray(): array { return $this->grid; } + /** + * Solve A*X = B. + * + * @param Matrix $B Right hand side + * + * @throws Exception + * + * @return Matrix ... Solution if A is square, least squares solution otherwise + */ + public function solve(Matrix $B): Matrix + { + if ($this->columns === $this->rows) { + return (new LU($this))->solve($B); + } + + return (new QR($this))->solve($B); + } + protected static $getters = [ 'rows', 'columns', @@ -342,7 +364,7 @@ public function toArray() * @return mixed * @throws Exception */ - public function __get($propertyName) + public function __get(string $propertyName) { $propertyName = strtolower($propertyName); @@ -355,8 +377,8 @@ public function __get($propertyName) } protected static $functions = [ - 'antidiagonal', 'adjoint', + 'antidiagonal', 'cofactors', 'determinant', 'diagonal', @@ -384,16 +406,17 @@ public function __get($propertyName) * @return Matrix|float * @throws Exception */ - public function __call($functionName, $arguments) + public function __call(string $functionName, $arguments) { $functionName = strtolower(str_replace('_', '', $functionName)); - if (in_array($functionName, self::$functions) || in_array($functionName, self::$operations)) { - $functionName = "\\" . __NAMESPACE__ . "\\{$functionName}"; - if (is_callable($functionName)) { - $arguments = array_values(array_merge([$this], $arguments)); - return call_user_func_array($functionName, $arguments); - } + // Test for function calls + if (in_array($functionName, self::$functions, true)) { + return Functions::$functionName($this, ...$arguments); + } + // Test for operation calls + if (in_array($functionName, self::$operations, true)) { + return Operations::$functionName($this, ...$arguments); } throw new Exception('Function or Operation does not exist'); } diff --git a/lib/markbaker/matrix/classes/src/Operations.php b/lib/markbaker/matrix/classes/src/Operations.php new file mode 100644 index 00000000..e3d88d64 --- /dev/null +++ b/lib/markbaker/matrix/classes/src/Operations.php @@ -0,0 +1,157 @@ +execute($matrix); + } + + return $result->result(); + } + + public static function directsum(...$matrixValues): Matrix + { + if (count($matrixValues) < 2) { + throw new Exception('DirectSum operation requires at least 2 arguments'); + } + + $matrix = array_shift($matrixValues); + + if (is_array($matrix)) { + $matrix = new Matrix($matrix); + } + if (!$matrix instanceof Matrix) { + throw new Exception('DirectSum arguments must be Matrix or array'); + } + + $result = new DirectSum($matrix); + + foreach ($matrixValues as $matrix) { + $result->execute($matrix); + } + + return $result->result(); + } + + public static function divideby(...$matrixValues): Matrix + { + if (count($matrixValues) < 2) { + throw new Exception('Division operation requires at least 2 arguments'); + } + + $matrix = array_shift($matrixValues); + + if (is_array($matrix)) { + $matrix = new Matrix($matrix); + } + if (!$matrix instanceof Matrix) { + throw new Exception('Division arguments must be Matrix or array'); + } + + $result = new Division($matrix); + + foreach ($matrixValues as $matrix) { + $result->execute($matrix); + } + + return $result->result(); + } + + public static function divideinto(...$matrixValues): Matrix + { + if (count($matrixValues) < 2) { + throw new Exception('Division operation requires at least 2 arguments'); + } + + $matrix = array_pop($matrixValues); + $matrixValues = array_reverse($matrixValues); + + if (is_array($matrix)) { + $matrix = new Matrix($matrix); + } + if (!$matrix instanceof Matrix) { + throw new Exception('Division arguments must be Matrix or array'); + } + + $result = new Division($matrix); + + foreach ($matrixValues as $matrix) { + $result->execute($matrix); + } + + return $result->result(); + } + + public static function multiply(...$matrixValues): Matrix + { + if (count($matrixValues) < 2) { + throw new Exception('Multiplication operation requires at least 2 arguments'); + } + + $matrix = array_shift($matrixValues); + + if (is_array($matrix)) { + $matrix = new Matrix($matrix); + } + if (!$matrix instanceof Matrix) { + throw new Exception('Multiplication arguments must be Matrix or array'); + } + + $result = new Multiplication($matrix); + + foreach ($matrixValues as $matrix) { + $result->execute($matrix); + } + + return $result->result(); + } + + public static function subtract(...$matrixValues): Matrix + { + if (count($matrixValues) < 2) { + throw new Exception('Subtraction operation requires at least 2 arguments'); + } + + $matrix = array_shift($matrixValues); + + if (is_array($matrix)) { + $matrix = new Matrix($matrix); + } + if (!$matrix instanceof Matrix) { + throw new Exception('Subtraction arguments must be Matrix or array'); + } + + $result = new Subtraction($matrix); + + foreach ($matrixValues as $matrix) { + $result->execute($matrix); + } + + return $result->result(); + } +} diff --git a/lib/markbaker/matrix/classes/src/Operators/Addition.php b/lib/markbaker/matrix/classes/src/Operators/Addition.php index e78c6d7d..543f56e9 100644 --- a/lib/markbaker/matrix/classes/src/Operators/Addition.php +++ b/lib/markbaker/matrix/classes/src/Operators/Addition.php @@ -14,7 +14,7 @@ class Addition extends Operator * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple additions to be chained **/ - public function execute($value) + public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); @@ -35,7 +35,7 @@ public function execute($value) * @param mixed $value The numeric value to add to the current base value * @return $this The operation object, allowing multiple additions to be chained **/ - protected function addScalar($value) + protected function addScalar($value): Operator { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { @@ -53,7 +53,7 @@ protected function addScalar($value) * @return $this The operation object, allowing multiple additions to be chained * @throws Exception If the provided argument is not appropriate for the operation **/ - protected function addMatrix(Matrix $value) + protected function addMatrix(Matrix $value): Operator { $this->validateMatchingDimensions($value); diff --git a/lib/markbaker/matrix/classes/src/Operators/DirectSum.php b/lib/markbaker/matrix/classes/src/Operators/DirectSum.php index 6db0853b..cc51ef96 100644 --- a/lib/markbaker/matrix/classes/src/Operators/DirectSum.php +++ b/lib/markbaker/matrix/classes/src/Operators/DirectSum.php @@ -14,7 +14,7 @@ class DirectSum extends Operator * @return $this The operation object, allowing multiple additions to be chained * @throws Exception If the provided argument is not appropriate for the operation */ - public function execute($value) + public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); @@ -33,7 +33,7 @@ public function execute($value) * @param Matrix $value The numeric value to concatenate/direct sum with the current base value * @return $this The operation object, allowing multiple additions to be chained **/ - private function directSumMatrix($value) + private function directSumMatrix($value): Operator { $originalColumnCount = count($this->matrix[0]); $originalRowCount = count($this->matrix); diff --git a/lib/markbaker/matrix/classes/src/Operators/Division.php b/lib/markbaker/matrix/classes/src/Operators/Division.php index 2a573f55..dbfec9d3 100644 --- a/lib/markbaker/matrix/classes/src/Operators/Division.php +++ b/lib/markbaker/matrix/classes/src/Operators/Division.php @@ -2,9 +2,10 @@ namespace Matrix\Operators; +use Matrix\Div0Exception; +use Matrix\Exception; use \Matrix\Matrix; use \Matrix\Functions; -use Matrix\Exception; class Division extends Multiplication { @@ -15,22 +16,18 @@ class Division extends Multiplication * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple divisions to be chained **/ - public function execute($value) + public function execute($value, string $type = 'division'): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { - try { - $value = Functions::inverse($value); - } catch (Exception $e) { - throw new Exception('Division can only be calculated using a matrix with a non-zero determinant'); - } + $value = Functions::inverse($value, $type); - return $this->multiplyMatrix($value); + return $this->multiplyMatrix($value, $type); } elseif (is_numeric($value)) { - return $this->multiplyScalar(1 / $value); + return $this->multiplyScalar(1 / $value, $type); } throw new Exception('Invalid argument for division'); diff --git a/lib/markbaker/matrix/classes/src/Operators/Multiplication.php b/lib/markbaker/matrix/classes/src/Operators/Multiplication.php index 63df162d..0761e466 100644 --- a/lib/markbaker/matrix/classes/src/Operators/Multiplication.php +++ b/lib/markbaker/matrix/classes/src/Operators/Multiplication.php @@ -5,6 +5,7 @@ use Matrix\Matrix; use \Matrix\Builder; use Matrix\Exception; +use Throwable; class Multiplication extends Operator { @@ -15,19 +16,19 @@ class Multiplication extends Operator * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple multiplications to be chained **/ - public function execute($value) + public function execute($value, string $type = 'multiplication'): Operator { if (is_array($value)) { $value = new Matrix($value); } if (is_object($value) && ($value instanceof Matrix)) { - return $this->multiplyMatrix($value); + return $this->multiplyMatrix($value, $type); } elseif (is_numeric($value)) { - return $this->multiplyScalar($value); + return $this->multiplyScalar($value, $type); } - throw new Exception('Invalid argument for multiplication'); + throw new Exception("Invalid argument for $type"); } /** @@ -36,12 +37,16 @@ public function execute($value) * @param mixed $value The numeric value to multiply with the current base value * @return $this The operation object, allowing multiple mutiplications to be chained **/ - protected function multiplyScalar($value) + protected function multiplyScalar($value, string $type = 'multiplication'): Operator { - for ($row = 0; $row < $this->rows; ++$row) { - for ($column = 0; $column < $this->columns; ++$column) { - $this->matrix[$row][$column] *= $value; + try { + for ($row = 0; $row < $this->rows; ++$row) { + for ($column = 0; $column < $this->columns; ++$column) { + $this->matrix[$row][$column] *= $value; + } } + } catch (Throwable $e) { + throw new Exception("Invalid argument for $type"); } return $this; @@ -54,7 +59,7 @@ protected function multiplyScalar($value) * @return $this The operation object, allowing multiple mutiplications to be chained * @throws Exception If the provided argument is not appropriate for the operation **/ - protected function multiplyMatrix(Matrix $value) + protected function multiplyMatrix(Matrix $value, string $type = 'multiplication'): Operator { $this->validateReflectingDimensions($value); @@ -62,13 +67,17 @@ protected function multiplyMatrix(Matrix $value) $newColumns = $value->columns; $matrix = Builder::createFilledMatrix(0, $newRows, $newColumns) ->toArray(); - for ($row = 0; $row < $newRows; ++$row) { - for ($column = 0; $column < $newColumns; ++$column) { - $columnData = $value->getColumns($column + 1)->toArray(); - foreach ($this->matrix[$row] as $key => $valueData) { - $matrix[$row][$column] += $valueData * $columnData[$key][0]; + try { + for ($row = 0; $row < $newRows; ++$row) { + for ($column = 0; $column < $newColumns; ++$column) { + $columnData = $value->getColumns($column + 1)->toArray(); + foreach ($this->matrix[$row] as $key => $valueData) { + $matrix[$row][$column] += $valueData * $columnData[$key][0]; + } } } + } catch (Throwable $e) { + throw new Exception("Invalid argument for $type"); } $this->matrix = $matrix; diff --git a/lib/markbaker/matrix/classes/src/Operators/Operator.php b/lib/markbaker/matrix/classes/src/Operators/Operator.php index 87d3f3b5..39e36c61 100644 --- a/lib/markbaker/matrix/classes/src/Operators/Operator.php +++ b/lib/markbaker/matrix/classes/src/Operators/Operator.php @@ -46,7 +46,7 @@ public function __construct(Matrix $matrix) * @param Matrix $matrix The second Matrix object on which the operation will be performed * @throws Exception */ - protected function validateMatchingDimensions(Matrix $matrix) + protected function validateMatchingDimensions(Matrix $matrix): void { if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) { throw new Exception('Matrices have mismatched dimensions'); @@ -59,7 +59,7 @@ protected function validateMatchingDimensions(Matrix $matrix) * @param Matrix $matrix The second Matrix object on which the operation will be performed * @throws Exception */ - protected function validateReflectingDimensions(Matrix $matrix) + protected function validateReflectingDimensions(Matrix $matrix): void { if ($this->columns != $matrix->rows) { throw new Exception('Matrices have mismatched dimensions'); @@ -71,7 +71,7 @@ protected function validateReflectingDimensions(Matrix $matrix) * * @return Matrix */ - public function result() + public function result(): Matrix { return new Matrix($this->matrix); } diff --git a/lib/markbaker/matrix/classes/src/Operators/Subtraction.php b/lib/markbaker/matrix/classes/src/Operators/Subtraction.php index 57c0b147..b7e14fad 100644 --- a/lib/markbaker/matrix/classes/src/Operators/Subtraction.php +++ b/lib/markbaker/matrix/classes/src/Operators/Subtraction.php @@ -14,7 +14,7 @@ class Subtraction extends Operator * @throws Exception If the provided argument is not appropriate for the operation * @return $this The operation object, allowing multiple subtractions to be chained **/ - public function execute($value) + public function execute($value): Operator { if (is_array($value)) { $value = new Matrix($value); @@ -35,7 +35,7 @@ public function execute($value) * @param mixed $value The numeric value to subtracted from the current base value * @return $this The operation object, allowing multiple additions to be chained **/ - protected function subtractScalar($value) + protected function subtractScalar($value): Operator { for ($row = 0; $row < $this->rows; ++$row) { for ($column = 0; $column < $this->columns; ++$column) { @@ -53,7 +53,7 @@ protected function subtractScalar($value) * @return $this The operation object, allowing multiple subtractions to be chained * @throws Exception If the provided argument is not appropriate for the operation **/ - protected function subtractMatrix(Matrix $value) + protected function subtractMatrix(Matrix $value): Operator { $this->validateMatchingDimensions($value); diff --git a/lib/markbaker/matrix/classes/src/functions/adjoint.php b/lib/markbaker/matrix/classes/src/functions/adjoint.php deleted file mode 100644 index fc1e1699..00000000 --- a/lib/markbaker/matrix/classes/src/functions/adjoint.php +++ /dev/null @@ -1,30 +0,0 @@ - $matrixValues The matrices to add - * @return Matrix - * @throws Exception - */ -function add(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('Addition operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('Addition arguments must be Matrix or array'); - } - - $result = new Addition($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/classes/src/operations/directsum.php b/lib/markbaker/matrix/classes/src/operations/directsum.php deleted file mode 100644 index 9d15b89b..00000000 --- a/lib/markbaker/matrix/classes/src/operations/directsum.php +++ /dev/null @@ -1,44 +0,0 @@ - $matrixValues The matrices to add - * @return Matrix - * @throws Exception - */ -function directsum(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('DirectSum operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('DirectSum arguments must be Matrix or array'); - } - - $result = new DirectSum($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/classes/src/operations/divideby.php b/lib/markbaker/matrix/classes/src/operations/divideby.php deleted file mode 100644 index 767d03a5..00000000 --- a/lib/markbaker/matrix/classes/src/operations/divideby.php +++ /dev/null @@ -1,44 +0,0 @@ - $matrixValues The matrices to divide - * @return Matrix - * @throws Exception - */ -function divideby(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('Division operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('Division arguments must be Matrix or array'); - } - - $result = new Division($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/classes/src/operations/divideinto.php b/lib/markbaker/matrix/classes/src/operations/divideinto.php deleted file mode 100644 index f5cb8dca..00000000 --- a/lib/markbaker/matrix/classes/src/operations/divideinto.php +++ /dev/null @@ -1,44 +0,0 @@ - $matrixValues The numbers to divide - * @return Matrix - * @throws Exception - */ -function divideinto(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('Division operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('Division arguments must be Matrix or array'); - } - - $result = new Division($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/classes/src/operations/multiply.php b/lib/markbaker/matrix/classes/src/operations/multiply.php deleted file mode 100644 index 1428f091..00000000 --- a/lib/markbaker/matrix/classes/src/operations/multiply.php +++ /dev/null @@ -1,44 +0,0 @@ - $matrixValues The matrices to multiply - * @return Matrix - * @throws Exception - */ -function multiply(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('Multiplication operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('Multiplication arguments must be Matrix or array'); - } - - $result = new Multiplication($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/classes/src/operations/subtract.php b/lib/markbaker/matrix/classes/src/operations/subtract.php deleted file mode 100644 index 3123b61e..00000000 --- a/lib/markbaker/matrix/classes/src/operations/subtract.php +++ /dev/null @@ -1,44 +0,0 @@ - $matrixValues The matrices to subtract - * @return Matrix - * @throws Exception - */ -function subtract(...$matrixValues) -{ - if (count($matrixValues) < 2) { - throw new Exception('Subtraction operation requires at least 2 arguments'); - } - - $matrix = array_shift($matrixValues); - - if (is_array($matrix)) { - $matrix = new Matrix($matrix); - } - if (!$matrix instanceof Matrix) { - throw new Exception('Subtraction arguments must be Matrix or array'); - } - - $result = new Subtraction($matrix); - - foreach ($matrixValues as $matrix) { - $result->execute($matrix); - } - - return $result->result(); -} diff --git a/lib/markbaker/matrix/composer.json b/lib/markbaker/matrix/composer.json index dae5c98c..fa90f563 100644 --- a/lib/markbaker/matrix/composer.json +++ b/lib/markbaker/matrix/composer.json @@ -8,74 +8,40 @@ "authors": [ { "name": "Mark Baker", - "email": "mark@lange.demon.co.uk" + "email": "mark@demon-angel.eu" } ], "require": { - "php": "^5.6.0|^7.0.0" + "php": "^7.1 || ^8.0" }, "require-dev": { - "phpunit/phpunit": "^5.7", - "phpmd/phpmd": "dev-master", - "sebastian/phpcpd": "^3.0", - "phploc/phploc": "^4", - "squizlabs/php_codesniffer": "^3.0@dev", - "phpcompatibility/php-compatibility": "dev-master", - "dealerdirect/phpcodesniffer-composer-installer": "dev-master" + "phpunit/phpunit": "^7.0 || ^8.0 || ^9.3", + "phpdocumentor/phpdocumentor": "2.*", + "phpmd/phpmd": "2.*", + "sebastian/phpcpd": "^4.0", + "phploc/phploc": "^4.0", + "squizlabs/php_codesniffer": "^3.4", + "phpcompatibility/php-compatibility": "^9.0", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0" }, "autoload": { "psr-4": { "Matrix\\": "classes/src/" - }, - "files": [ - "classes/src/functions/adjoint.php", - "classes/src/functions/antidiagonal.php", - "classes/src/functions/cofactors.php", - "classes/src/functions/determinant.php", - "classes/src/functions/diagonal.php", - "classes/src/functions/identity.php", - "classes/src/functions/inverse.php", - "classes/src/functions/minors.php", - "classes/src/functions/trace.php", - "classes/src/functions/transpose.php", - "classes/src/operations/add.php", - "classes/src/operations/directsum.php", - "classes/src/operations/subtract.php", - "classes/src/operations/multiply.php", - "classes/src/operations/divideby.php", - "classes/src/operations/divideinto.php" - ] + } }, "autoload-dev": { "psr-4": { - "Matrix\\Test\\": "unitTests/classes/src/" - }, - "files": [ - "unitTests/classes/src/functions/adjointTest.php", - "unitTests/classes/src/functions/antidiagonalTest.php", - "unitTests/classes/src/functions/cofactorsTest.php", - "unitTests/classes/src/functions/determinantTest.php", - "unitTests/classes/src/functions/diagonalTest.php", - "unitTests/classes/src/functions/identityTest.php", - "unitTests/classes/src/functions/inverseTest.php", - "unitTests/classes/src/functions/minorsTest.php", - "unitTests/classes/src/functions/traceTest.php", - "unitTests/classes/src/functions/transposeTest.php", - "unitTests/classes/src/operations/addTest.php", - "unitTests/classes/src/operations/directsumTest.php", - "unitTests/classes/src/operations/subtractTest.php", - "unitTests/classes/src/operations/multiplyTest.php", - "unitTests/classes/src/operations/dividebyTest.php", - "unitTests/classes/src/operations/divideintoTest.php" - ] + "MatrixTest\\": "unitTests/classes/src/" + } }, "scripts": { - "style": "phpcs --report-width=200 --report=summary,full -n", + "style": "phpcs --report-width=200 --standard=PSR2 --report=summary,full classes/src/ unitTests/classes/src -n", "test": "phpunit -c phpunit.xml.dist", "mess": "phpmd classes/src/ xml codesize,unusedcode,design,naming -n", "lines": "phploc classes/src/ -n", "cpd": "phpcpd classes/src/ -n", - "versions": "phpcs --report-width=200 --report=summary,full classes/src/ --standard=PHPCompatibility --runtime-set testVersion 5.6- -n" + "versions": "phpcs --report-width=200 --standard=PHPCompatibility --report=summary,full classes/src/ --runtime-set testVersion 7.2- -n", + "coverage": "phpunit -c phpunit.xml.dist --coverage-text --coverage-html ./build/coverage" }, "minimum-stability": "dev" -} +} \ No newline at end of file diff --git a/lib/markbaker/matrix/examples/test.php b/lib/markbaker/matrix/examples/test.php new file mode 100644 index 00000000..071dae91 --- /dev/null +++ b/lib/markbaker/matrix/examples/test.php @@ -0,0 +1,33 @@ +solve($target); + +echo 'X', PHP_EOL; +var_export($X->toArray()); +echo PHP_EOL; + +$resolve = $matrix->multiply($X); + +echo 'Resolve', PHP_EOL; +var_export($resolve->toArray()); +echo PHP_EOL; diff --git a/lib/markbaker/matrix/infection.json.dist b/lib/markbaker/matrix/infection.json.dist new file mode 100644 index 00000000..eddaa70a --- /dev/null +++ b/lib/markbaker/matrix/infection.json.dist @@ -0,0 +1,17 @@ +{ + "timeout": 1, + "source": { + "directories": [ + "classes\/src" + ] + }, + "logs": { + "text": "build/infection/text.log", + "summary": "build/infection/summary.log", + "debug": "build/infection/debug.log", + "perMutator": "build/infection/perMutator.md" + }, + "mutators": { + "@default": true + } +} diff --git a/lib/markbaker/matrix/phpstan.neon b/lib/markbaker/matrix/phpstan.neon new file mode 100644 index 00000000..3d90d492 --- /dev/null +++ b/lib/markbaker/matrix/phpstan.neon @@ -0,0 +1,6 @@ +parameters: + ignoreErrors: + - '#Property [A-Za-z\\]+::\$[A-Za-z]+ has no typehint specified#' + - '#Method [A-Za-z\\]+::[A-Za-z]+\(\) has no return typehint specified#' + - '#Method [A-Za-z\\]+::[A-Za-z]+\(\) has parameter \$[A-Za-z0-9]+ with no typehint specified#' + checkMissingIterableValueType: false diff --git a/lib/math/CHANGELOG.md b/lib/math/CHANGELOG.md new file mode 100644 index 00000000..03c3d824 --- /dev/null +++ b/lib/math/CHANGELOG.md @@ -0,0 +1,415 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## [0.9.3](https://github.com/brick/math/releases/tag/0.9.3) - 2021-08-15 + +🚀 **Compatibility with PHP 8.1** + +- Support for custom object serialization; this removes a warning on PHP 8.1 due to the `Serializable` interface being deprecated (thanks @TRowbotham) + +## [0.9.2](https://github.com/brick/math/releases/tag/0.9.2) - 2021-01-20 + +🐛 **Bug fix** + +- Incorrect results could be returned when using the BCMath calculator, with a default scale set with `bcscale()`, on PHP >= 7.2 (#55). + +## [0.9.1](https://github.com/brick/math/releases/tag/0.9.1) - 2020-08-19 + +✨ New features + +- `BigInteger::not()` returns the bitwise `NOT` value + +🐛 **Bug fixes** + +- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers +- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available + +## [0.9.0](https://github.com/brick/math/releases/tag/0.9.0) - 2020-08-18 + +👌 **Improvements** + +- `BigNumber::of()` now accepts `.123` and `123.` formats, both of which return a `BigDecimal` + +💥 **Breaking changes** + +- Deprecated method `BigInteger::powerMod()` has been removed - use `modPow()` instead +- Deprecated method `BigInteger::parse()` has been removed - use `fromBase()` instead + +## [0.8.17](https://github.com/brick/math/releases/tag/0.8.17) - 2020-08-19 + +🐛 **Bug fix** + +- `BigInteger::toBytes()` could return an incorrect binary representation for some numbers +- The bitwise operations `and()`, `or()`, `xor()` on `BigInteger` could return an incorrect result when the GMP extension is not available + +## [0.8.16](https://github.com/brick/math/releases/tag/0.8.16) - 2020-08-18 + +🚑 **Critical fix** + +- This version reintroduces the deprecated `BigInteger::parse()` method, that has been removed by mistake in version `0.8.9` and should have lasted for the whole `0.8` release cycle. + +✨ **New features** + +- `BigInteger::modInverse()` calculates a modular multiplicative inverse +- `BigInteger::fromBytes()` creates a `BigInteger` from a byte string +- `BigInteger::toBytes()` converts a `BigInteger` to a byte string +- `BigInteger::randomBits()` creates a pseudo-random `BigInteger` of a given bit length +- `BigInteger::randomRange()` creates a pseudo-random `BigInteger` between two bounds + +💩 **Deprecations** + +- `BigInteger::powerMod()` is now deprecated in favour of `modPow()` + +## [0.8.15](https://github.com/brick/math/releases/tag/0.8.15) - 2020-04-15 + +🐛 **Fixes** + +- added missing `ext-json` requirement, due to `BigNumber` implementing `JsonSerializable` + +⚡️ **Optimizations** + +- additional optimization in `BigInteger::remainder()` + +## [0.8.14](https://github.com/brick/math/releases/tag/0.8.14) - 2020-02-18 + +✨ **New features** + +- `BigInteger::getLowestSetBit()` returns the index of the rightmost one bit + +## [0.8.13](https://github.com/brick/math/releases/tag/0.8.13) - 2020-02-16 + +✨ **New features** + +- `BigInteger::isEven()` tests whether the number is even +- `BigInteger::isOdd()` tests whether the number is odd +- `BigInteger::testBit()` tests if a bit is set +- `BigInteger::getBitLength()` returns the number of bits in the minimal representation of the number + +## [0.8.12](https://github.com/brick/math/releases/tag/0.8.12) - 2020-02-03 + +🛠️ **Maintenance release** + +Classes are now annotated for better static analysis with [psalm](https://psalm.dev/). + +This is a maintenance release: no bug fixes, no new features, no breaking changes. + +## [0.8.11](https://github.com/brick/math/releases/tag/0.8.11) - 2020-01-23 + +✨ **New feature** + +`BigInteger::powerMod()` performs a power-with-modulo operation. Useful for crypto. + +## [0.8.10](https://github.com/brick/math/releases/tag/0.8.10) - 2020-01-21 + +✨ **New feature** + +`BigInteger::mod()` returns the **modulo** of two numbers. The *modulo* differs from the *remainder* when the signs of the operands are different. + +## [0.8.9](https://github.com/brick/math/releases/tag/0.8.9) - 2020-01-08 + +⚡️ **Performance improvements** + +A few additional optimizations in `BigInteger` and `BigDecimal` when one of the operands can be returned as is. Thanks to @tomtomsen in #24. + +## [0.8.8](https://github.com/brick/math/releases/tag/0.8.8) - 2019-04-25 + +🐛 **Bug fixes** + +- `BigInteger::toBase()` could return an empty string for zero values (BCMath & Native calculators only, GMP calculator unaffected) + +✨ **New features** + +- `BigInteger::toArbitraryBase()` converts a number to an arbitrary base, using a custom alphabet +- `BigInteger::fromArbitraryBase()` converts a string in an arbitrary base, using a custom alphabet, back to a number + +These methods can be used as the foundation to convert strings between different bases/alphabets, using BigInteger as an intermediate representation. + +💩 **Deprecations** + +- `BigInteger::parse()` is now deprecated in favour of `fromBase()` + +`BigInteger::fromBase()` works the same way as `parse()`, with 2 minor differences: + +- the `$base` parameter is required, it does not default to `10` +- it throws a `NumberFormatException` instead of an `InvalidArgumentException` when the number is malformed + +## [0.8.7](https://github.com/brick/math/releases/tag/0.8.7) - 2019-04-20 + +**Improvements** + +- Safer conversion from `float` when using custom locales +- **Much faster** `NativeCalculator` implementation 🚀 + +You can expect **at least a 3x performance improvement** for common arithmetic operations when using the library on systems without GMP or BCMath; it gets exponentially faster on multiplications with a high number of digits. This is due to calculations now being performed on whole blocks of digits (the block size depending on the platform, 32-bit or 64-bit) instead of digit-by-digit as before. + +## [0.8.6](https://github.com/brick/math/releases/tag/0.8.6) - 2019-04-11 + +**New method** + +`BigNumber::sum()` returns the sum of one or more numbers. + +## [0.8.5](https://github.com/brick/math/releases/tag/0.8.5) - 2019-02-12 + +**Bug fix**: `of()` factory methods could fail when passing a `float` in environments using a `LC_NUMERIC` locale with a decimal separator other than `'.'` (#20). + +Thanks @manowark 👍 + +## [0.8.4](https://github.com/brick/math/releases/tag/0.8.4) - 2018-12-07 + +**New method** + +`BigDecimal::sqrt()` calculates the square root of a decimal number, to a given scale. + +## [0.8.3](https://github.com/brick/math/releases/tag/0.8.3) - 2018-12-06 + +**New method** + +`BigInteger::sqrt()` calculates the square root of a number (thanks @peter279k). + +**New exception** + +`NegativeNumberException` is thrown when calling `sqrt()` on a negative number. + +## [0.8.2](https://github.com/brick/math/releases/tag/0.8.2) - 2018-11-08 + +**Performance update** + +- Further improvement of `toInt()` performance +- `NativeCalculator` can now perform some multiplications more efficiently + +## [0.8.1](https://github.com/brick/math/releases/tag/0.8.1) - 2018-11-07 + +Performance optimization of `toInt()` methods. + +## [0.8.0](https://github.com/brick/math/releases/tag/0.8.0) - 2018-10-13 + +**Breaking changes** + +The following deprecated methods have been removed. Use the new method name instead: + +| Method removed | Replacement method | +| --- | --- | +| `BigDecimal::getIntegral()` | `BigDecimal::getIntegralPart()` | +| `BigDecimal::getFraction()` | `BigDecimal::getFractionalPart()` | + +--- + +**New features** + +`BigInteger` has been augmented with 5 new methods for bitwise operations: + +| New method | Description | +| --- | --- | +| `and()` | performs a bitwise `AND` operation on two numbers | +| `or()` | performs a bitwise `OR` operation on two numbers | +| `xor()` | performs a bitwise `XOR` operation on two numbers | +| `shiftedLeft()` | returns the number shifted left by a number of bits | +| `shiftedRight()` | returns the number shifted right by a number of bits | + +Thanks to @DASPRiD 👍 + +## [0.7.3](https://github.com/brick/math/releases/tag/0.7.3) - 2018-08-20 + +**New method:** `BigDecimal::hasNonZeroFractionalPart()` + +**Renamed/deprecated methods:** + +- `BigDecimal::getIntegral()` has been renamed to `getIntegralPart()` and is now deprecated +- `BigDecimal::getFraction()` has been renamed to `getFractionalPart()` and is now deprecated + +## [0.7.2](https://github.com/brick/math/releases/tag/0.7.2) - 2018-07-21 + +**Performance update** + +`BigInteger::parse()` and `toBase()` now use GMP's built-in base conversion features when available. + +## [0.7.1](https://github.com/brick/math/releases/tag/0.7.1) - 2018-03-01 + +This is a maintenance release, no code has been changed. + +- When installed with `--no-dev`, the autoloader does not autoload tests anymore +- Tests and other files unnecessary for production are excluded from the dist package + +This will help make installations more compact. + +## [0.7.0](https://github.com/brick/math/releases/tag/0.7.0) - 2017-10-02 + +Methods renamed: + +- `BigNumber:sign()` has been renamed to `getSign()` +- `BigDecimal::unscaledValue()` has been renamed to `getUnscaledValue()` +- `BigDecimal::scale()` has been renamed to `getScale()` +- `BigDecimal::integral()` has been renamed to `getIntegral()` +- `BigDecimal::fraction()` has been renamed to `getFraction()` +- `BigRational::numerator()` has been renamed to `getNumerator()` +- `BigRational::denominator()` has been renamed to `getDenominator()` + +Classes renamed: + +- `ArithmeticException` has been renamed to `MathException` + +## [0.6.2](https://github.com/brick/math/releases/tag/0.6.2) - 2017-10-02 + +The base class for all exceptions is now `MathException`. +`ArithmeticException` has been deprecated, and will be removed in 0.7.0. + +## [0.6.1](https://github.com/brick/math/releases/tag/0.6.1) - 2017-10-02 + +A number of methods have been renamed: + +- `BigNumber:sign()` is deprecated; use `getSign()` instead +- `BigDecimal::unscaledValue()` is deprecated; use `getUnscaledValue()` instead +- `BigDecimal::scale()` is deprecated; use `getScale()` instead +- `BigDecimal::integral()` is deprecated; use `getIntegral()` instead +- `BigDecimal::fraction()` is deprecated; use `getFraction()` instead +- `BigRational::numerator()` is deprecated; use `getNumerator()` instead +- `BigRational::denominator()` is deprecated; use `getDenominator()` instead + +The old methods will be removed in version 0.7.0. + +## [0.6.0](https://github.com/brick/math/releases/tag/0.6.0) - 2017-08-25 + +- Minimum PHP version is now [7.1](https://gophp71.org/); for PHP 5.6 and PHP 7.0 support, use version `0.5` +- Deprecated method `BigDecimal::withScale()` has been removed; use `toScale()` instead +- Method `BigNumber::toInteger()` has been renamed to `toInt()` + +## [0.5.4](https://github.com/brick/math/releases/tag/0.5.4) - 2016-10-17 + +`BigNumber` classes now implement [JsonSerializable](http://php.net/manual/en/class.jsonserializable.php). +The JSON output is always a string. + +## [0.5.3](https://github.com/brick/math/releases/tag/0.5.3) - 2016-03-31 + +This is a bugfix release. Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.5.2](https://github.com/brick/math/releases/tag/0.5.2) - 2015-08-06 + +The `$scale` parameter of `BigDecimal::dividedBy()` is now optional again. + +## [0.5.1](https://github.com/brick/math/releases/tag/0.5.1) - 2015-07-05 + +**New method: `BigNumber::toScale()`** + +This allows to convert any `BigNumber` to a `BigDecimal` with a given scale, using rounding if necessary. + +## [0.5.0](https://github.com/brick/math/releases/tag/0.5.0) - 2015-07-04 + +**New features** +- Common `BigNumber` interface for all classes, with the following methods: + - `sign()` and derived methods (`isZero()`, `isPositive()`, ...) + - `compareTo()` and derived methods (`isEqualTo()`, `isGreaterThan()`, ...) that work across different `BigNumber` types + - `toBigInteger()`, `toBigDecimal()`, `toBigRational`() conversion methods + - `toInteger()` and `toFloat()` conversion methods to native types +- Unified `of()` behaviour: every class now accepts any type of number, provided that it can be safely converted to the current type +- New method: `BigDecimal::exactlyDividedBy()`; this method automatically computes the scale of the result, provided that the division yields a finite number of digits +- New methods: `BigRational::quotient()` and `remainder()` +- Fine-grained exceptions: `DivisionByZeroException`, `RoundingNecessaryException`, `NumberFormatException` +- Factory methods `zero()`, `one()` and `ten()` available in all classes +- Rounding mode reintroduced in `BigInteger::dividedBy()` + +This release also comes with many performance improvements. + +--- + +**Breaking changes** +- `BigInteger`: + - `getSign()` is renamed to `sign()` + - `toString()` is renamed to `toBase()` + - `BigInteger::dividedBy()` now throws an exception by default if the remainder is not zero; use `quotient()` to get the previous behaviour +- `BigDecimal`: + - `getSign()` is renamed to `sign()` + - `getUnscaledValue()` is renamed to `unscaledValue()` + - `getScale()` is renamed to `scale()` + - `getIntegral()` is renamed to `integral()` + - `getFraction()` is renamed to `fraction()` + - `divideAndRemainder()` is renamed to `quotientAndRemainder()` + - `dividedBy()` now takes a **mandatory** `$scale` parameter **before** the rounding mode + - `toBigInteger()` does not accept a `$roundingMode` parameter any more + - `toBigRational()` does not simplify the fraction any more; explicitly add `->simplified()` to get the previous behaviour +- `BigRational`: + - `getSign()` is renamed to `sign()` + - `getNumerator()` is renamed to `numerator()` + - `getDenominator()` is renamed to `denominator()` + - `of()` is renamed to `nd()`, while `parse()` is renamed to `of()` +- Miscellaneous: + - `ArithmeticException` is moved to an `Exception\` sub-namespace + - `of()` factory methods now throw `NumberFormatException` instead of `InvalidArgumentException` + +## [0.4.3](https://github.com/brick/math/releases/tag/0.4.3) - 2016-03-31 + +Backport of two bug fixes from the 0.5 branch: +- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected +- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.4.2](https://github.com/brick/math/releases/tag/0.4.2) - 2015-06-16 + +New method: `BigDecimal::stripTrailingZeros()` + +## [0.4.1](https://github.com/brick/math/releases/tag/0.4.1) - 2015-06-12 + +Introducing a `BigRational` class, to perform calculations on fractions of any size. + +## [0.4.0](https://github.com/brick/math/releases/tag/0.4.0) - 2015-06-12 + +Rounding modes have been removed from `BigInteger`, and are now a concept specific to `BigDecimal`. + +`BigInteger::dividedBy()` now always returns the quotient of the division. + +## [0.3.5](https://github.com/brick/math/releases/tag/0.3.5) - 2016-03-31 + +Backport of two bug fixes from the 0.5 branch: + +- `BigInteger::parse()` did not always throw `InvalidArgumentException` as expected +- Dividing by a negative power of 1 with the same scale as the dividend could trigger an incorrect optimization which resulted in a wrong result. See #6. + +## [0.3.4](https://github.com/brick/math/releases/tag/0.3.4) - 2015-06-11 + +New methods: +- `BigInteger::remainder()` returns the remainder of a division only +- `BigInteger::gcd()` returns the greatest common divisor of two numbers + +## [0.3.3](https://github.com/brick/math/releases/tag/0.3.3) - 2015-06-07 + +Fix `toString()` not handling negative numbers. + +## [0.3.2](https://github.com/brick/math/releases/tag/0.3.2) - 2015-06-07 + +`BigInteger` and `BigDecimal` now have a `getSign()` method that returns: +- `-1` if the number is negative +- `0` if the number is zero +- `1` if the number is positive + +## [0.3.1](https://github.com/brick/math/releases/tag/0.3.1) - 2015-06-05 + +Minor performance improvements + +## [0.3.0](https://github.com/brick/math/releases/tag/0.3.0) - 2015-06-04 + +The `$roundingMode` and `$scale` parameters have been swapped in `BigDecimal::dividedBy()`. + +## [0.2.2](https://github.com/brick/math/releases/tag/0.2.2) - 2015-06-04 + +Stronger immutability guarantee for `BigInteger` and `BigDecimal`. + +So far, it would have been possible to break immutability of these classes by calling the `unserialize()` internal function. This release fixes that. + +## [0.2.1](https://github.com/brick/math/releases/tag/0.2.1) - 2015-06-02 + +Added `BigDecimal::divideAndRemainder()` + +## [0.2.0](https://github.com/brick/math/releases/tag/0.2.0) - 2015-05-22 + +- `min()` and `max()` do not accept an `array` any more, but a variable number of parameters +- **minimum PHP version is now 5.6** +- continuous integration with PHP 7 + +## [0.1.1](https://github.com/brick/math/releases/tag/0.1.1) - 2014-09-01 + +- Added `BigInteger::power()` +- Added HHVM support + +## [0.1.0](https://github.com/brick/math/releases/tag/0.1.0) - 2014-08-31 + +First beta release. + diff --git a/lib/math/SECURITY.md b/lib/math/SECURITY.md index 6bdc74f0..cc8289bb 100644 --- a/lib/math/SECURITY.md +++ b/lib/math/SECURITY.md @@ -2,10 +2,11 @@ ## Supported Versions -Only the latest release stream is supported. +Only the last two release streams are supported. | Version | Supported | | ------- | ------------------ | +| 0.9.x | :white_check_mark: | | 0.8.x | :white_check_mark: | | < 0.8 | :x: | diff --git a/lib/math/composer.json b/lib/math/composer.json index d347b6bd..ec196632 100644 --- a/lib/math/composer.json +++ b/lib/math/composer.json @@ -14,13 +14,13 @@ ], "license": "MIT", "require": { - "php": "^7.1|^8.0", + "php": "^7.1 || ^8.0", "ext-json": "*" }, "require-dev": { - "phpunit/phpunit": "^7.5.15|^8.5", + "phpunit/phpunit": "^7.5.15 || ^8.5 || ^9.0", "php-coveralls/php-coveralls": "^2.2", - "vimeo/psalm": "^3.5" + "vimeo/psalm": "4.9.2" }, "autoload": { "psr-4": { diff --git a/lib/math/psalm-baseline.xml b/lib/math/psalm-baseline.xml deleted file mode 100644 index fe05b998..00000000 --- a/lib/math/psalm-baseline.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - string - string - string - - - [$q, $r] - - - array - - - \bcdiv($a, $b, 0) - \bcmod($a, $b) - \bcpowmod($base, $exp, $mod, 0) - - - - - $a - $a - $a - $b - $blockA - $blockA - - - $i - $i - $i - $j - - - $e / 2 - - - diff --git a/lib/math/random-tests.php b/lib/math/random-tests.php deleted file mode 100644 index c59529f6..00000000 --- a/lib/math/random-tests.php +++ /dev/null @@ -1,184 +0,0 @@ -gmp = new Calculator\GmpCalculator(); - $this->bcmath = new Calculator\BcMathCalculator(); - $this->native = new Calculator\NativeCalculator(); - - $this->maxDigits = $maxDigits; - } - - public function __invoke() : void - { - for (;;) { - $a = $this->generateRandomNumber(); - $b = $this->generateRandomNumber(); - $c = $this->generateRandomNumber(); - - $this->runTests($a, $b); - $this->runTests($b, $a); - - if ($a !== '0') { - $this->runTests("-$a", $b); - $this->runTests($b, "-$a"); - } - - if ($b !== '0') { - $this->runTests($a, "-$b"); - $this->runTests("-$b", $a); - } - - if ($a !== '0' && $b !== '0') { - $this->runTests("-$a", "-$b"); - $this->runTests("-$b", "-$a"); - } - - if ($c !== '0') { - $this->test("$a POW $b MOD $c", function(Calculator $calc) use($a, $b, $c) { - return $calc->modPow($a, $b, $c); - }); - } - } - } - - /** - * @param string $a The left operand. - * @param string $b The right operand. - */ - function runTests(string $a, string $b) : void - { - $this->test("$a + $b", function(Calculator $c) use($a, $b) { - return $c->add($a, $b); - }); - - $this->test("$a - $b", function(Calculator $c) use($a, $b) { - return $c->sub($a, $b); - }); - - $this->test("$a * $b", function(Calculator $c) use($a, $b) { - return $c->mul($a, $b); - }); - - if ($b !== '0') { - $this->test("$a / $b", function(Calculator $c) use($a, $b) { - return $c->divQR($a, $b); - }); - - $this->test("$a MOD $b", function(Calculator $c) use($a, $b) { - return $c->mod($a, $b); - }); - } - - if ($b !== '0' && $b[0] !== '-') { - $this->test("INV $a MOD $b", function(Calculator $c) use($a, $b) { - return $c->modInverse($a, $b); - }); - } - - $this->test("GCD $a, $b", function(Calculator $c) use($a, $b) { - return $c->gcd($a, $b); - }); - - if ($a[0] !== '-') { - $this->test("SQRT $a", function(Calculator $c) use($a, $b) { - return $c->sqrt($a); - }); - } - - $this->test("$a AND $b", function(Calculator $c) use($a, $b) { - return $c->and($a, $b); - }); - - $this->test("$a OR $b", function(Calculator $c) use($a, $b) { - return $c->or($a, $b); - }); - - $this->test("$a XOR $b", function(Calculator $c) use($a, $b) { - return $c->xor($a, $b); - }); - } - - /** - * @param string $test A string representing the test being executed. - * @param Closure $callback A callback function accepting a Calculator instance and returning a calculation result. - */ - private function test(string $test, Closure $callback) : void - { - static $counter = 0; - static $lastOutputTime = null; - - $gmpResult = $callback($this->gmp); - $bcmathResult = $callback($this->bcmath); - $nativeResult = $callback($this->native); - - if ($gmpResult !== $bcmathResult) { - self::failure('GMP', 'BCMath', $test); - } - - if ($gmpResult !== $nativeResult) { - self::failure('GMP', 'Native', $test); - } - - $counter++; - $time = microtime(true); - - if ($lastOutputTime === null) { - $lastOutputTime = $time; - } elseif ($time - $lastOutputTime >= 0.1) { - echo "\r", number_format($counter); - $lastOutputTime = $time; - } - } - - /** - * @param string $c1 The name of the first calculator. - * @param string $c2 The name of the second calculator. - * @param string $test A string representing the test being executed. - */ - private static function failure(string $c1, string $c2, string $test) : void - { - echo PHP_EOL; - echo 'FAILURE!', PHP_EOL; - echo $c1, ' vs ', $c2, PHP_EOL; - echo $test, PHP_EOL; - die; - } - - private function generateRandomNumber() : string - { - $length = random_int(1, $this->maxDigits); - - $number = ''; - - for ($i = 0; $i < $length; $i++) { - $number .= random_int(0, 9); - } - - $number = ltrim($number, '0'); - - if ($number === '') { - return '0'; - } - - return $number; - } -})(); diff --git a/lib/math/src/BigDecimal.php b/lib/math/src/BigDecimal.php index 28717714..78246500 100644 --- a/lib/math/src/BigDecimal.php +++ b/lib/math/src/BigDecimal.php @@ -96,7 +96,10 @@ public static function ofUnscaledValue($value, int $scale = 0) : BigDecimal */ public static function zero() : BigDecimal { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $zero + */ static $zero; if ($zero === null) { @@ -115,7 +118,10 @@ public static function zero() : BigDecimal */ public static function one() : BigDecimal { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $one + */ static $one; if ($one === null) { @@ -134,7 +140,10 @@ public static function one() : BigDecimal */ public static function ten() : BigDecimal { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigDecimal|null $ten + */ static $ten; if ($ten === null) { @@ -677,11 +686,7 @@ public function hasNonZeroFractionalPart() : bool */ public function toBigInteger() : BigInteger { - if ($this->scale === 0) { - $zeroScaleDecimal = $this; - } else { - $zeroScaleDecimal = $this->dividedBy(1, 0); - } + $zeroScaleDecimal = $this->scale === 0 ? $this : $this->dividedBy(1, 0); return BigInteger::create($zeroScaleDecimal->value); } @@ -747,6 +752,40 @@ public function __toString() : string return \substr($value, 0, -$this->scale) . '.' . \substr($value, -$this->scale); } + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{value: string, scale: int} + */ + public function __serialize(): array + { + return ['value' => $this->value, 'scale' => $this->scale]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{value: string, scale: int} $data + * + * @return void + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->value)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->value = $data['value']; + $this->scale = $data['scale']; + } + /** * This method is required by interface Serializable and SHOULD NOT be accessed directly. * @@ -763,6 +802,7 @@ public function serialize() : string * This method is only here to implement interface Serializable and cannot be accessed directly. * * @internal + * @psalm-suppress RedundantPropertyInitializationCheck * * @param string $value * @@ -788,7 +828,7 @@ public function unserialize($value) : void * @param BigDecimal $x The first decimal number. * @param BigDecimal $y The second decimal number. * - * @return array{0: string, 1: string} The scaled integer values of $x and $y. + * @return array{string, string} The scaled integer values of $x and $y. */ private function scaleValues(BigDecimal $x, BigDecimal $y) : array { diff --git a/lib/math/src/BigInteger.php b/lib/math/src/BigInteger.php index cee3ce82..f213fbed 100644 --- a/lib/math/src/BigInteger.php +++ b/lib/math/src/BigInteger.php @@ -217,6 +217,8 @@ public static function fromBytes(string $value, bool $signed = true) : BigIntege * * Using the default random bytes generator, this method is suitable for cryptographic use. * + * @psalm-param callable(int): string $randomBytesGenerator + * * @param int $numBits The number of bits. * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, and returns a * string of random bytes of the given length. Defaults to the @@ -256,6 +258,8 @@ public static function randomBits(int $numBits, ?callable $randomBytesGenerator * * Using the default random bytes generator, this method is suitable for cryptographic use. * + * @psalm-param (callable(int): string)|null $randomBytesGenerator + * * @param BigNumber|int|float|string $min The lower bound. Must be convertible to a BigInteger. * @param BigNumber|int|float|string $max The upper bound. Must be convertible to a BigInteger. * @param callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer, @@ -300,7 +304,10 @@ public static function randomRange($min, $max, ?callable $randomBytesGenerator = */ public static function zero() : BigInteger { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $zero + */ static $zero; if ($zero === null) { @@ -319,7 +326,10 @@ public static function zero() : BigInteger */ public static function one() : BigInteger { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $one + */ static $one; if ($one === null) { @@ -338,7 +348,10 @@ public static function one() : BigInteger */ public static function ten() : BigInteger { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigInteger|null $ten + */ static $ten; if ($ten === null) { @@ -1070,7 +1083,10 @@ public function toBytes(bool $signed = true) : string if ($signed) { if ($this->isNegative()) { - $hex = \bin2hex(~\hex2bin($hex)); + $bin = \hex2bin($hex); + assert($bin !== false); + + $hex = \bin2hex(~$bin); $hex = self::fromBase($hex, 16)->plus(1)->toBase(16); $hexLength = \strlen($hex); @@ -1100,6 +1116,39 @@ public function __toString() : string return $this->value; } + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{value: string} + */ + public function __serialize(): array + { + return ['value' => $this->value]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{value: string} $data + * + * @return void + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->value)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->value = $data['value']; + } + /** * This method is required by interface Serializable and SHOULD NOT be accessed directly. * @@ -1116,6 +1165,7 @@ public function serialize() : string * This method is only here to implement interface Serializable and cannot be accessed directly. * * @internal + * @psalm-suppress RedundantPropertyInitializationCheck * * @param string $value * diff --git a/lib/math/src/BigNumber.php b/lib/math/src/BigNumber.php index 59fcc7ce..38c8c554 100644 --- a/lib/math/src/BigNumber.php +++ b/lib/math/src/BigNumber.php @@ -67,13 +67,10 @@ public static function of($value) : BigNumber return new BigInteger((string) $value); } - if (\is_float($value)) { - $value = self::floatToString($value); - } else { - $value = (string) $value; - } + /** @psalm-suppress RedundantCastGivenDocblockType We cannot trust the untyped $value here! */ + $value = \is_float($value) ? self::floatToString($value) : (string) $value; - $throw = function() use ($value) : void { + $throw = static function() use ($value) : void { throw new NumberFormatException(\sprintf( 'The given value "%s" does not represent a valid number.', $value @@ -84,7 +81,7 @@ public static function of($value) : BigNumber $throw(); } - $getMatch = function(string $value) use ($matches) : ?string { + $getMatch = static function(string $value) use ($matches) : ?string { return isset($matches[$value]) && $matches[$value] !== '' ? $matches[$value] : null; }; @@ -93,7 +90,13 @@ public static function of($value) : BigNumber $denominator = $getMatch('denominator'); if ($numerator !== null) { - $numerator = self::cleanUp($sign . $numerator); + assert($denominator !== null); + + if ($sign !== null) { + $numerator = $sign . $numerator; + } + + $numerator = self::cleanUp($numerator); $denominator = self::cleanUp($denominator); if ($denominator === '0') { @@ -121,14 +124,14 @@ public static function of($value) : BigNumber } if ($point !== null || $exponent !== null) { - $fractional = $fractional ?? ''; - $exponent = $exponent !== null ? (int) $exponent : 0; + $fractional = ($fractional ?? ''); + $exponent = ($exponent !== null) ? (int) $exponent : 0; if ($exponent === PHP_INT_MIN || $exponent === PHP_INT_MAX) { throw new NumberFormatException('Exponent too large.'); } - $unscaledValue = self::cleanUp($sign . $integral . $fractional); + $unscaledValue = self::cleanUp(($sign ?? ''). $integral . $fractional); $scale = \strlen($fractional) - $exponent; @@ -142,7 +145,7 @@ public static function of($value) : BigNumber return new BigDecimal($unscaledValue, $scale); } - $integral = self::cleanUp($sign . $integral); + $integral = self::cleanUp(($sign ?? '') . $integral); return new BigInteger($integral); } @@ -181,10 +184,11 @@ private static function floatToString(float $float) : string * @return static * * @psalm-pure + * @psalm-suppress TooManyArguments + * @psalm-suppress UnsafeInstantiation */ protected static function create(... $args) : BigNumber { - /** @psalm-suppress TooManyArguments */ return new static(... $args); } @@ -199,6 +203,8 @@ protected static function create(... $args) : BigNumber * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ public static function min(...$values) : BigNumber @@ -231,6 +237,8 @@ public static function min(...$values) : BigNumber * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ public static function max(...$values) : BigNumber @@ -263,6 +271,8 @@ public static function max(...$values) : BigNumber * @throws \InvalidArgumentException If no values are given. * @throws MathException If an argument is not valid. * + * @psalm-suppress LessSpecificReturnStatement + * @psalm-suppress MoreSpecificReturnType * @psalm-pure */ public static function sum(...$values) : BigNumber @@ -273,11 +283,7 @@ public static function sum(...$values) : BigNumber foreach ($values as $value) { $value = static::of($value); - if ($sum === null) { - $sum = $value; - } else { - $sum = self::add($sum, $value); - } + $sum = $sum === null ? $value : self::add($sum, $value); } if ($sum === null) { diff --git a/lib/math/src/BigRational.php b/lib/math/src/BigRational.php index ff035c5c..bee094f7 100644 --- a/lib/math/src/BigRational.php +++ b/lib/math/src/BigRational.php @@ -108,7 +108,10 @@ public static function nd($numerator, $denominator) : BigRational */ public static function zero() : BigRational { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $zero + */ static $zero; if ($zero === null) { @@ -127,7 +130,10 @@ public static function zero() : BigRational */ public static function one() : BigRational { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $one + */ static $one; if ($one === null) { @@ -146,7 +152,10 @@ public static function one() : BigRational */ public static function ten() : BigRational { - /** @psalm-suppress ImpureStaticVariable */ + /** + * @psalm-suppress ImpureStaticVariable + * @var BigRational|null $ten + */ static $ten; if ($ten === null) { @@ -442,6 +451,40 @@ public function __toString() : string return $this->numerator . '/' . $this->denominator; } + /** + * This method is required for serializing the object and SHOULD NOT be accessed directly. + * + * @internal + * + * @return array{numerator: BigInteger, denominator: BigInteger} + */ + public function __serialize(): array + { + return ['numerator' => $this->numerator, 'denominator' => $this->denominator]; + } + + /** + * This method is only here to allow unserializing the object and cannot be accessed directly. + * + * @internal + * @psalm-suppress RedundantPropertyInitializationCheck + * + * @param array{numerator: BigInteger, denominator: BigInteger} $data + * + * @return void + * + * @throws \LogicException + */ + public function __unserialize(array $data): void + { + if (isset($this->numerator)) { + throw new \LogicException('__unserialize() is an internal function, it must not be called directly.'); + } + + $this->numerator = $data['numerator']; + $this->denominator = $data['denominator']; + } + /** * This method is required by interface Serializable and SHOULD NOT be accessed directly. * @@ -458,6 +501,7 @@ public function serialize() : string * This method is only here to implement interface Serializable and cannot be accessed directly. * * @internal + * @psalm-suppress RedundantPropertyInitializationCheck * * @param string $value * diff --git a/lib/math/src/Internal/Calculator.php b/lib/math/src/Internal/Calculator.php index 44795acb..a6eac799 100644 --- a/lib/math/src/Internal/Calculator.php +++ b/lib/math/src/Internal/Calculator.php @@ -99,7 +99,7 @@ private static function detect() : Calculator * @param string $a The first operand. * @param string $b The second operand. * - * @return array{0: bool, 1: bool, 2: string, 3: string} Whether $a and $b are negative, followed by their digits. + * @return array{bool, bool, string, string} Whether $a and $b are negative, followed by their digits. */ final protected function init(string $a, string $b) : array { @@ -685,7 +685,7 @@ private function twosComplement(string $number) : string { $xor = \str_repeat("\xff", \strlen($number)); - $number = $number ^ $xor; + $number ^= $xor; for ($i = \strlen($number) - 1; $i >= 0; $i--) { $byte = \ord($number[$i]); diff --git a/lib/math/src/Internal/Calculator/BcMathCalculator.php b/lib/math/src/Internal/Calculator/BcMathCalculator.php index c087245b..6632b378 100644 --- a/lib/math/src/Internal/Calculator/BcMathCalculator.php +++ b/lib/math/src/Internal/Calculator/BcMathCalculator.php @@ -41,6 +41,9 @@ public function mul(string $a, string $b) : string /** * {@inheritdoc} + * + * @psalm-suppress InvalidNullableReturnType + * @psalm-suppress NullableReturnStatement */ public function divQ(string $a, string $b) : string { @@ -49,9 +52,16 @@ public function divQ(string $a, string $b) : string /** * {@inheritdoc} + * + * @psalm-suppress InvalidNullableReturnType + * @psalm-suppress NullableReturnStatement */ public function divR(string $a, string $b) : string { + if (version_compare(PHP_VERSION, '7.2') >= 0) { + return \bcmod($a, $b, 0); + } + return \bcmod($a, $b); } @@ -61,7 +71,15 @@ public function divR(string $a, string $b) : string public function divQR(string $a, string $b) : array { $q = \bcdiv($a, $b, 0); - $r = \bcmod($a, $b); + + if (version_compare(PHP_VERSION, '7.2') >= 0) { + $r = \bcmod($a, $b, 0); + } else { + $r = \bcmod($a, $b); + } + + assert($q !== null); + assert($r !== null); return [$q, $r]; } @@ -76,6 +94,9 @@ public function pow(string $a, int $e) : string /** * {@inheritdoc} + * + * @psalm-suppress InvalidNullableReturnType + * @psalm-suppress NullableReturnStatement */ public function modPow(string $base, string $exp, string $mod) : string { @@ -84,6 +105,9 @@ public function modPow(string $base, string $exp, string $mod) : string /** * {@inheritDoc} + * + * @psalm-suppress NullableReturnStatement + * @psalm-suppress InvalidNullableReturnType */ public function sqrt(string $n) : string { diff --git a/lib/math/src/Internal/Calculator/NativeCalculator.php b/lib/math/src/Internal/Calculator/NativeCalculator.php index d248e684..020a6338 100644 --- a/lib/math/src/Internal/Calculator/NativeCalculator.php +++ b/lib/math/src/Internal/Calculator/NativeCalculator.php @@ -53,6 +53,10 @@ public function __construct() */ public function add(string $a, string $b) : string { + /** + * @psalm-var numeric-string $a + * @psalm-var numeric-string $b + */ $result = $a + $b; if (is_int($result)) { @@ -69,11 +73,7 @@ public function add(string $a, string $b) : string [$aNeg, $bNeg, $aDig, $bDig] = $this->init($a, $b); - if ($aNeg === $bNeg) { - $result = $this->doAdd($aDig, $bDig); - } else { - $result = $this->doSub($aDig, $bDig); - } + $result = $aNeg === $bNeg ? $this->doAdd($aDig, $bDig) : $this->doSub($aDig, $bDig); if ($aNeg) { $result = $this->neg($result); @@ -95,6 +95,10 @@ public function sub(string $a, string $b) : string */ public function mul(string $a, string $b) : string { + /** + * @psalm-var numeric-string $a + * @psalm-var numeric-string $b + */ $result = $a * $b; if (is_int($result)) { @@ -169,9 +173,11 @@ public function divQR(string $a, string $b) : array return [$this->neg($a), '0']; } + /** @psalm-var numeric-string $a */ $na = $a * 1; // cast to number if (is_int($na)) { + /** @psalm-var numeric-string $b */ $nb = $b * 1; if (is_int($nb)) { @@ -221,6 +227,8 @@ public function pow(string $a, int $e) : string $e -= $odd; $aa = $this->mul($a, $a); + + /** @psalm-suppress PossiblyInvalidArgument We're sure that $e / 2 is an int now */ $result = $this->pow($aa, $e / 2); if ($odd === 1) { @@ -316,10 +324,14 @@ private function doAdd(string $a, string $b) : string if ($i < 0) { $blockLength += $i; + /** @psalm-suppress LoopInvalidation */ $i = 0; } + /** @psalm-var numeric-string $blockA */ $blockA = \substr($a, $i, $blockLength); + + /** @psalm-var numeric-string $blockB */ $blockB = \substr($b, $i, $blockLength); $sum = (string) ($blockA + $blockB + $carry); @@ -386,10 +398,14 @@ private function doSub(string $a, string $b) : string if ($i < 0) { $blockLength += $i; + /** @psalm-suppress LoopInvalidation */ $i = 0; } + /** @psalm-var numeric-string $blockA */ $blockA = \substr($a, $i, $blockLength); + + /** @psalm-var numeric-string $blockB */ $blockB = \substr($b, $i, $blockLength); $sum = $blockA - $blockB - $carry; @@ -450,6 +466,7 @@ private function doMul(string $a, string $b) : string if ($i < 0) { $blockALength += $i; + /** @psalm-suppress LoopInvalidation */ $i = 0; } @@ -463,6 +480,7 @@ private function doMul(string $a, string $b) : string if ($j < 0) { $blockBLength += $j; + /** @psalm-suppress LoopInvalidation */ $j = 0; } @@ -592,7 +610,7 @@ private function doCmp(string $a, string $b) : int * @param string $a The first operand. * @param string $b The second operand. * - * @return array{0: string, 1: string, 2: int} + * @return array{string, string, int} */ private function pad(string $a, string $b) : array { diff --git a/lib/module.inc.php b/lib/module.inc.php index a73cede8..dda4eca5 100755 --- a/lib/module.inc.php +++ b/lib/module.inc.php @@ -1,4 +1,5 @@ getSubMenuItems($str_module); + $menus = $this->getSubMenuItems($str_module); // iterate menu array - $header_index = 0; - foreach ($menu as $_list) { - if ($_list[0] == 'Header') { - $_submenu .= ''; - $header_index++; - } else { - if ($i > 1) $_submenu_current = ''; + foreach ($menus as $header => $menu) { + $_submenu .= ''; + + foreach ($menu as $item) { + if ($i > 0) $_submenu_current = ''; $_submenu .= '' . $_list[0] . ''; + . ' href="' . $item[1] . '"' + . ' title="' . (isset($item[2]) ? $item[2] : $item[0]) . '" href="#">' . $item[0] . ''; + $i++; } - $i++; } $_submenu .= ' '; return $_submenu; @@ -161,32 +163,113 @@ public function getSubMenuItems($str_module = '') if (file_exists($_submenu_file)) { include $_submenu_file; + } else { + include 'default/submenu.php'; + foreach ($this->get_shortcuts_menu($dbs) as $key => $value) { + $link = explode('|', $value); + // Exception for shortcut menu based on registered plugin + if (preg_match('/plugin_container/', $link[1])) { + $menu[$link[0]] = array(__($link[0]), $link[1]); + continue; + } + $menu[$link[0]] = array(__($link[0]), MWB . $link[1]); + } + } + + $menus = []; + foreach ($this->reorderMenus($menu, $plugin_menus) as $header => $items) { + foreach ($items as $item) { + $menus[$header] = $menus[$header] ?? []; + if ($_SESSION['uid'] > 1 && !in_array(md5($item[1]), $_SESSION['priv'][$str_module]['menus'] ?? [])) continue; + $menus[$header][] = $item; + } + } + $menus = array_filter($menus, fn ($m) => count($m) > 0); + return $menus; + } - $menu = array_merge($menu ?? [], $plugin_menus); + /** + * Method to order default menu and plugin menu + * + * @param array $default + * @param array $plugin + * @return array + */ + function reorderMenus($default, $plugin) + { + $groups = []; + $orders = GroupMenuOrder::getInstance()->getOrder(); + $group_menu = GroupMenu::getInstance()->getGroup(); - if ($_SESSION['uid'] > 1) { - $tmp_menu = []; - if (isset($menu) && count($menu) > 0) { - foreach ($menu as $item) { - if ($item[0] === 'Header' || in_array(md5($item[1]), $_SESSION['priv'][$str_module]['menus'])) $tmp_menu[] = $item; + // collect header from default menu + $header = null; + foreach ($default as $menu) { + if (count($menu) === 2 && strtolower($menu[0]) === 'header') { + // reset header + $header = null; + // iterate orders + if (count($orders) > 0) { + // get menu before + foreach ($orders as $key => $value) { + if (count($plugin) < 1) break; + $group_menu_items = array_map(fn ($i) => $plugin[$i] ?? [], $group_menu[$key]); + if (count($group_menu_items) > 0 && strtolower($menu[1]) === $value['group'] && $value['position'] === 'before') + $groups[strtolower($key)] = $group_menu_items; } + + // main menu + $groups[strtolower($menu[1])] = []; + + // get menu after + foreach ($orders as $key => $value) { + if (count($plugin) < 1) break; + $group_menu_items = array_map(fn ($i) => $plugin[$i] ?? [], $group_menu[$key]); + if (count($group_menu_items) > 0 && strtolower($menu[1]) === $value['group'] && $value['position'] === 'after') + $groups[strtolower($key)] = $group_menu_items; + } + } else { + $groups[strtolower($menu[1])] = []; } - $menu = $tmp_menu; + $header = strtolower($menu[1]); + continue; } + if (!is_null($header)) { + $groups[strtolower($header)][] = $menu; + } + } - // clean header, remove it if not have child - foreach ($menu as $index => $item) - if ($item[0] === 'Header' && (!isset($menu[$index + 1]) || (isset($menu[$index + 1]) && $menu[$index + 1][0] === 'Header'))) - unset($menu[$index]); - - } else { - include 'default/submenu.php'; - foreach ($this->get_shortcuts_menu($dbs) as $key => $value) { - $link = explode('|', $value); - $menu[$link[0]] = array(__($link[0]), MWB . $link[1]); + foreach ($group_menu as $header => $menus) { + $tmp_menu = []; + foreach ($menus as $hash) { + if (isset($plugin[$hash])) $tmp_menu[] = $plugin[$hash]; } + + if(count($tmp_menu) > 0) $groups[$header] = $tmp_menu; } - return $menu; + + // ungrouped plugin group to "plugins" group + $ungrouped = array_filter(array_keys($plugin), fn ($p) => !in_array($p, GroupMenu::getInstance()->getPluginInGroup())); + $ungrouped = ['plugins' => array_map(fn ($i) => $plugin[$i], $ungrouped)]; + + // merge group + if (count($plugin) > 0) + $groups = array_merge($groups, $ungrouped); + + return $groups; + } + + /** + * Method to get a first submenu of module + * + * @param string $str_module + * @return mixed + */ + public function getFirstMenu($str_module = '') + { + $menus = $this->getSubMenuItems($str_module); + $key = array_keys($menus)[0] ?? false; + if ($key) return $menus[$key][0] ?? null; + return null; } /** @@ -206,5 +289,4 @@ function get_shortcuts_menu() } return $shortcuts; } - } diff --git a/lib/myclabs/php-enum/LICENSE b/lib/myclabs/php-enum/LICENSE new file mode 100644 index 00000000..2a8cf22e --- /dev/null +++ b/lib/myclabs/php-enum/LICENSE @@ -0,0 +1,18 @@ +The MIT License (MIT) + +Copyright (c) 2015 My C-Labs + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/myclabs/php-enum/README.md b/lib/myclabs/php-enum/README.md new file mode 100644 index 00000000..1e4d1ff4 --- /dev/null +++ b/lib/myclabs/php-enum/README.md @@ -0,0 +1,138 @@ +# PHP Enum implementation inspired from SplEnum + +[![Build Status](https://travis-ci.org/myclabs/php-enum.png?branch=master)](https://travis-ci.org/myclabs/php-enum) +[![Latest Stable Version](https://poser.pugx.org/myclabs/php-enum/version.png)](https://packagist.org/packages/myclabs/php-enum) +[![Total Downloads](https://poser.pugx.org/myclabs/php-enum/downloads.png)](https://packagist.org/packages/myclabs/php-enum) +[![psalm](https://shepherd.dev/github/myclabs/php-enum/coverage.svg)](https://shepherd.dev/github/myclabs/php-enum) + +Maintenance for this project is [supported via Tidelift](https://tidelift.com/subscription/pkg/packagist-myclabs-php-enum?utm_source=packagist-myclabs-php-enum&utm_medium=referral&utm_campaign=readme). + +## Why? + +First, and mainly, `SplEnum` is not integrated to PHP, you have to install the extension separately. + +Using an enum instead of class constants provides the following advantages: + +- You can use an enum as a parameter type: `function setAction(Action $action) {` +- You can use an enum as a return type: `function getAction() : Action {` +- You can enrich the enum with methods (e.g. `format`, `parse`, …) +- You can extend the enum to add new values (make your enum `final` to prevent it) +- You can get a list of all the possible values (see below) + +This Enum class is not intended to replace class constants, but only to be used when it makes sense. + +## Installation + +``` +composer require myclabs/php-enum +``` + +## Declaration + +```php +use MyCLabs\Enum\Enum; + +/** + * Action enum + */ +final class Action extends Enum +{ + private const VIEW = 'view'; + private const EDIT = 'edit'; +} +``` + +## Usage + +```php +$action = Action::VIEW(); + +// or with a dynamic key: +$action = Action::$key(); +// or with a dynamic value: +$action = Action::from($value); +// or +$action = new Action($value); +``` + +As you can see, static methods are automatically implemented to provide quick access to an enum value. + +One advantage over using class constants is to be able to use an enum as a parameter type: + +```php +function setAction(Action $action) { + // ... +} +``` + +## Documentation + +- `__construct()` The constructor checks that the value exist in the enum +- `__toString()` You can `echo $myValue`, it will display the enum value (value of the constant) +- `getValue()` Returns the current value of the enum +- `getKey()` Returns the key of the current value on Enum +- `equals()` Tests whether enum instances are equal (returns `true` if enum values are equal, `false` otherwise) + +Static methods: + +- `from()` Creates an Enum instance, checking that the value exist in the enum +- `toArray()` method Returns all possible values as an array (constant name in key, constant value in value) +- `keys()` Returns the names (keys) of all constants in the Enum class +- `values()` Returns instances of the Enum class of all Enum constants (constant name in key, Enum instance in value) +- `isValid()` Check if tested value is valid on enum set +- `isValidKey()` Check if tested key is valid on enum set +- `assertValidValue()` Assert the value is valid on enum set, throwing exception otherwise +- `search()` Return key for searched value + +### Static methods + +```php +final class Action extends Enum +{ + private const VIEW = 'view'; + private const EDIT = 'edit'; +} + +// Static method: +$action = Action::VIEW(); +$action = Action::EDIT(); +``` + +Static method helpers are implemented using [`__callStatic()`](http://www.php.net/manual/en/language.oop5.overloading.php#object.callstatic). + +If you care about IDE autocompletion, you can either implement the static methods yourself: + +```php +final class Action extends Enum +{ + private const VIEW = 'view'; + + /** + * @return Action + */ + public static function VIEW() { + return new Action(self::VIEW); + } +} +``` + +or you can use phpdoc (this is supported in PhpStorm for example): + +```php +/** + * @method static Action VIEW() + * @method static Action EDIT() + */ +final class Action extends Enum +{ + private const VIEW = 'view'; + private const EDIT = 'edit'; +} +``` + +## Related projects + +- [Doctrine enum mapping](https://github.com/acelaya/doctrine-enum-type) +- [Symfony ParamConverter integration](https://github.com/Ex3v/MyCLabsEnumParamConverter) +- [PHPStan integration](https://github.com/timeweb/phpstan-enum) +- [Yii2 enum mapping](https://github.com/KartaviK/yii2-enum) diff --git a/lib/myclabs/php-enum/SECURITY.md b/lib/myclabs/php-enum/SECURITY.md new file mode 100644 index 00000000..84fd4e32 --- /dev/null +++ b/lib/myclabs/php-enum/SECURITY.md @@ -0,0 +1,11 @@ +# Security Policy + +## Supported Versions + +Only the latest stable release is supported. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). + +Tidelift will coordinate the fix and disclosure. diff --git a/lib/myclabs/php-enum/composer.json b/lib/myclabs/php-enum/composer.json new file mode 100644 index 00000000..924f924b --- /dev/null +++ b/lib/myclabs/php-enum/composer.json @@ -0,0 +1,33 @@ +{ + "name": "myclabs/php-enum", + "type": "library", + "description": "PHP Enum implementation", + "keywords": ["enum"], + "homepage": "http://github.com/myclabs/php-enum", + "license": "MIT", + "authors": [ + { + "name": "PHP Enum contributors", + "homepage": "https://github.com/myclabs/php-enum/graphs/contributors" + } + ], + "autoload": { + "psr-4": { + "MyCLabs\\Enum\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "MyCLabs\\Tests\\Enum\\": "tests/" + } + }, + "require": { + "php": "^7.3 || ^8.0", + "ext-json": "*" + }, + "require-dev": { + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "1.*", + "vimeo/psalm": "^4.6.2" + } +} diff --git a/lib/myclabs/php-enum/psalm.xml b/lib/myclabs/php-enum/psalm.xml new file mode 100644 index 00000000..ff06b66e --- /dev/null +++ b/lib/myclabs/php-enum/psalm.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/myclabs/php-enum/src/Enum.php b/lib/myclabs/php-enum/src/Enum.php new file mode 100644 index 00000000..89064eba --- /dev/null +++ b/lib/myclabs/php-enum/src/Enum.php @@ -0,0 +1,318 @@ + + * @author Daniel Costa + * @author Mirosław Filip + * + * @psalm-template T + * @psalm-immutable + * @psalm-consistent-constructor + */ +abstract class Enum implements \JsonSerializable +{ + /** + * Enum value + * + * @var mixed + * @psalm-var T + */ + protected $value; + + /** + * Enum key, the constant name + * + * @var string + */ + private $key; + + /** + * Store existing constants in a static cache per object. + * + * + * @var array + * @psalm-var array> + */ + protected static $cache = []; + + /** + * Cache of instances of the Enum class + * + * @var array + * @psalm-var array> + */ + protected static $instances = []; + + /** + * Creates a new value of some type + * + * @psalm-pure + * @param mixed $value + * + * @psalm-param T $value + * @throws \UnexpectedValueException if incompatible type is given. + */ + public function __construct($value) + { + if ($value instanceof static) { + /** @psalm-var T */ + $value = $value->getValue(); + } + + /** @psalm-suppress ImplicitToStringCast assertValidValueReturningKey returns always a string but psalm has currently an issue here */ + $this->key = static::assertValidValueReturningKey($value); + + /** @psalm-var T */ + $this->value = $value; + } + + /** + * This method exists only for the compatibility reason when deserializing a previously serialized version + * that didn't had the key property + */ + public function __wakeup() + { + /** @psalm-suppress DocblockTypeContradiction key can be null when deserializing an enum without the key */ + if ($this->key === null) { + /** + * @psalm-suppress InaccessibleProperty key is not readonly as marked by psalm + * @psalm-suppress PossiblyFalsePropertyAssignmentValue deserializing a case that was removed + */ + $this->key = static::search($this->value); + } + } + + /** + * @param mixed $value + * @return static + */ + public static function from($value): self + { + $key = static::assertValidValueReturningKey($value); + + return self::__callStatic($key, []); + } + + /** + * @psalm-pure + * @return mixed + * @psalm-return T + */ + public function getValue() + { + return $this->value; + } + + /** + * Returns the enum key (i.e. the constant name). + * + * @psalm-pure + * @return string + */ + public function getKey() + { + return $this->key; + } + + /** + * @psalm-pure + * @psalm-suppress InvalidCast + * @return string + */ + public function __toString() + { + return (string)$this->value; + } + + /** + * Determines if Enum should be considered equal with the variable passed as a parameter. + * Returns false if an argument is an object of different class or not an object. + * + * This method is final, for more information read https://github.com/myclabs/php-enum/issues/4 + * + * @psalm-pure + * @psalm-param mixed $variable + * @return bool + */ + final public function equals($variable = null): bool + { + return $variable instanceof self + && $this->getValue() === $variable->getValue() + && static::class === \get_class($variable); + } + + /** + * Returns the names (keys) of all constants in the Enum class + * + * @psalm-pure + * @psalm-return list + * @return array + */ + public static function keys() + { + return \array_keys(static::toArray()); + } + + /** + * Returns instances of the Enum class of all Enum constants + * + * @psalm-pure + * @psalm-return array + * @return static[] Constant name in key, Enum instance in value + */ + public static function values() + { + $values = array(); + + /** @psalm-var T $value */ + foreach (static::toArray() as $key => $value) { + $values[$key] = new static($value); + } + + return $values; + } + + /** + * Returns all possible values as an array + * + * @psalm-pure + * @psalm-suppress ImpureStaticProperty + * + * @psalm-return array + * @return array Constant name in key, constant value in value + */ + public static function toArray() + { + $class = static::class; + + if (!isset(static::$cache[$class])) { + /** @psalm-suppress ImpureMethodCall this reflection API usage has no side-effects here */ + $reflection = new \ReflectionClass($class); + /** @psalm-suppress ImpureMethodCall this reflection API usage has no side-effects here */ + static::$cache[$class] = $reflection->getConstants(); + } + + return static::$cache[$class]; + } + + /** + * Check if is valid enum value + * + * @param $value + * @psalm-param mixed $value + * @psalm-pure + * @psalm-assert-if-true T $value + * @return bool + */ + public static function isValid($value) + { + return \in_array($value, static::toArray(), true); + } + + /** + * Asserts valid enum value + * + * @psalm-pure + * @psalm-assert T $value + * @param mixed $value + */ + public static function assertValidValue($value): void + { + self::assertValidValueReturningKey($value); + } + + /** + * Asserts valid enum value + * + * @psalm-pure + * @psalm-assert T $value + * @param mixed $value + * @return string + */ + private static function assertValidValueReturningKey($value): string + { + if (false === ($key = static::search($value))) { + throw new \UnexpectedValueException("Value '$value' is not part of the enum " . static::class); + } + + return $key; + } + + /** + * Check if is valid enum key + * + * @param $key + * @psalm-param string $key + * @psalm-pure + * @return bool + */ + public static function isValidKey($key) + { + $array = static::toArray(); + + return isset($array[$key]) || \array_key_exists($key, $array); + } + + /** + * Return key for value + * + * @param mixed $value + * + * @psalm-param mixed $value + * @psalm-pure + * @return string|false + */ + public static function search($value) + { + return \array_search($value, static::toArray(), true); + } + + /** + * Returns a value when called statically like so: MyEnum::SOME_VALUE() given SOME_VALUE is a class constant + * + * @param string $name + * @param array $arguments + * + * @return static + * @throws \BadMethodCallException + * + * @psalm-pure + */ + public static function __callStatic($name, $arguments) + { + $class = static::class; + if (!isset(self::$instances[$class][$name])) { + $array = static::toArray(); + if (!isset($array[$name]) && !\array_key_exists($name, $array)) { + $message = "No static method or enum constant '$name' in class " . static::class; + throw new \BadMethodCallException($message); + } + return self::$instances[$class][$name] = new static($array[$name]); + } + return clone self::$instances[$class][$name]; + } + + /** + * Specify data which should be serialized to JSON. This method returns data that can be serialized by json_encode() + * natively. + * + * @return mixed + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + * @psalm-pure + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return $this->getValue(); + } +} diff --git a/lib/myclabs/php-enum/src/PHPUnit/Comparator.php b/lib/myclabs/php-enum/src/PHPUnit/Comparator.php new file mode 100644 index 00000000..302bf80e --- /dev/null +++ b/lib/myclabs/php-enum/src/PHPUnit/Comparator.php @@ -0,0 +1,54 @@ +register(new \MyCLabs\Enum\PHPUnit\Comparator()); + */ +final class Comparator extends \SebastianBergmann\Comparator\Comparator +{ + public function accepts($expected, $actual) + { + return $expected instanceof Enum && ( + $actual instanceof Enum || $actual === null + ); + } + + /** + * @param Enum $expected + * @param Enum|null $actual + * + * @return void + */ + public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false) + { + if ($expected->equals($actual)) { + return; + } + + throw new ComparisonFailure( + $expected, + $actual, + $this->formatEnum($expected), + $this->formatEnum($actual), + false, + 'Failed asserting that two Enums are equal.' + ); + } + + private function formatEnum(Enum $enum = null) + { + if ($enum === null) { + return "null"; + } + + return get_class($enum)."::{$enum->getKey()}()"; + } +} diff --git a/lib/oaipmh/oaidp-config.php b/lib/oaipmh/oaidp-config.php index de1dcbaa..38bc5374 100644 --- a/lib/oaipmh/oaidp-config.php +++ b/lib/oaipmh/oaidp-config.php @@ -183,7 +183,7 @@ /** After 24 hours resumptionTokens become invalid. Unit is second. */ define('TOKEN_VALID',24*3600); -$expirationdatetime = gmstrftime('%Y-%m-%dT%TZ', time()+TOKEN_VALID); +$expirationdatetime = date("Y-m-d\TH:i:s\Z", time()+TOKEN_VALID); /** Where token is saved and path is included */ define('TOKEN_PREFIX','/tmp/ANDS_DBPD-'); @@ -237,6 +237,7 @@ // change according to your local DB setup. $DB_HOST = DB_HOST; +$DB_PORT = DB_PORT; $DB_USER = DB_USERNAME; $DB_PASSWD = DB_PASSWORD; $DB_NAME = DB_NAME; @@ -245,7 +246,7 @@ // if you use something other than mysql edit accordingly. // Example for MySQL //$DSN = "mysql://$DB_USER:$DB_PASSWD@$DB_HOST/$DB_NAME"; -$DSN = "mysql:host=$DB_HOST;dbname=$DB_NAME"; +$DSN = "mysql:host=$DB_HOST;port=$DB_PORT;dbname=$DB_NAME"; // Example for Oracle // $DSN = "oci8://$DB_USER:$DB_PASSWD@$DB_NAME"; diff --git a/lib/oaipmh/record_dc.php b/lib/oaipmh/record_dc.php index 7eaaccae..12f7990e 100644 --- a/lib/oaipmh/record_dc.php +++ b/lib/oaipmh/record_dc.php @@ -62,7 +62,7 @@ function create_metadata($outputObj, $cur_record, $identifier, $setspec, $db) { } function xml_safe($string){ - return preg_replace('/[\x00-\x1f]/','',htmlspecialchars($string)); + return preg_replace('/[\x00-\x1f]/','',htmlspecialchars($string??'')); } function date_safe($string){ diff --git a/lib/phpoffice/phpspreadsheet/.php-cs-fixer.dist.php b/lib/phpoffice/phpspreadsheet/.php-cs-fixer.dist.php new file mode 100644 index 00000000..ca2feb42 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/.php-cs-fixer.dist.php @@ -0,0 +1,226 @@ +exclude('vendor') + ->in(__DIR__); + +$config = new PhpCsFixer\Config(); +$config + ->setRiskyAllowed(true) + ->setFinder($finder) + ->setCacheFile(sys_get_temp_dir() . '/php-cs-fixer' . preg_replace('~\W~', '-', __DIR__)) + ->setRules([ + 'align_multiline_comment' => true, + 'array_indentation' => true, + 'array_syntax' => ['syntax' => 'short'], + 'backtick_to_shell_exec' => true, + 'binary_operator_spaces' => true, + 'blank_line_after_namespace' => true, + 'blank_line_after_opening_tag' => true, + 'blank_line_before_statement' => true, + 'braces' => true, + 'cast_spaces' => true, + 'class_attributes_separation' => ['elements' => ['method' => 'one', 'property' => 'one']], // const are often grouped with other related const + 'class_definition' => false, + 'class_keyword_remove' => false, // ::class keyword gives us better support in IDE + 'combine_consecutive_issets' => true, + 'combine_consecutive_unsets' => true, + 'combine_nested_dirname' => true, + 'comment_to_phpdoc' => false, // interferes with annotations + 'compact_nullable_typehint' => true, + 'concat_space' => ['spacing' => 'one'], + 'constant_case' => true, + 'date_time_immutable' => false, // Break our unit tests + 'declare_equal_normalize' => true, + 'declare_strict_types' => false, // Too early to adopt strict types + 'dir_constant' => true, + 'doctrine_annotation_array_assignment' => true, + 'doctrine_annotation_braces' => true, + 'doctrine_annotation_indentation' => true, + 'doctrine_annotation_spaces' => true, + 'elseif' => true, + 'encoding' => true, + 'ereg_to_preg' => true, + 'escape_implicit_backslashes' => true, + 'explicit_indirect_variable' => false, // I feel it makes the code actually harder to read + 'explicit_string_variable' => false, // I feel it makes the code actually harder to read + 'final_class' => false, // We need non-final classes + 'final_internal_class' => true, + 'final_public_method_for_abstract_class' => false, // We need non-final methods + 'self_static_accessor' => true, + 'fopen_flag_order' => true, + 'fopen_flags' => true, + 'full_opening_tag' => true, + 'fully_qualified_strict_types' => true, + 'function_declaration' => true, + 'function_to_constant' => true, + 'function_typehint_space' => true, + 'general_phpdoc_annotation_remove' => ['annotations' => ['access', 'category', 'copyright', 'throws']], + 'global_namespace_import' => true, + 'header_comment' => false, // We don't use common header in all our files + 'heredoc_indentation' => false, // Requires PHP >= 7.3 + 'heredoc_to_nowdoc' => false, // Not sure about this one + 'implode_call' => true, + 'include' => true, + 'increment_style' => true, + 'indentation_type' => true, + 'is_null' => true, + 'line_ending' => true, + 'linebreak_after_opening_tag' => true, + 'list_syntax' => ['syntax' => 'short'], + 'logical_operators' => true, + 'lowercase_cast' => true, + 'lowercase_keywords' => true, + 'lowercase_static_reference' => true, + 'magic_constant_casing' => true, + 'magic_method_casing' => true, + 'mb_str_functions' => false, // No, too dangerous to change that + 'method_argument_space' => true, + 'method_chaining_indentation' => true, + 'modernize_types_casting' => true, + 'multiline_comment_opening_closing' => true, + 'multiline_whitespace_before_semicolons' => true, + 'native_constant_invocation' => false, // Micro optimization that look messy + 'native_function_casing' => true, + 'native_function_invocation' => false, // I suppose this would be best, but I am still unconvinced about the visual aspect of it + 'native_function_type_declaration_casing' => true, + 'new_with_braces' => true, + 'no_alias_functions' => true, + 'no_alternative_syntax' => true, + 'no_binary_string' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_blank_lines_before_namespace' => false, // we want 1 blank line before namespace + 'no_break_comment' => true, + 'no_closing_tag' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_blank_lines' => true, + 'no_homoglyph_names' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_null_property_initialization' => true, + 'no_php4_constructor' => true, + 'no_short_bool_cast' => true, + 'echo_tag_syntax' => ['format' => 'long'], + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_after_function_name' => true, + 'no_spaces_around_offset' => true, + 'no_spaces_inside_parenthesis' => true, + 'no_superfluous_elseif' => false, // Might be risky on a huge code base + 'no_superfluous_phpdoc_tags' => ['allow_mixed' => true], + 'no_trailing_comma_in_list_call' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'no_unneeded_control_parentheses' => true, + 'no_unneeded_curly_braces' => true, + 'no_unneeded_final_method' => true, + 'no_unreachable_default_argument_value' => true, + 'no_unset_cast' => true, + 'no_unset_on_property' => true, + 'no_unused_imports' => true, + 'no_useless_else' => true, + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => true, + 'no_whitespace_in_blank_line' => true, + 'non_printable_character' => true, + 'normalize_index_brace' => true, + 'not_operator_with_space' => false, // No we prefer to keep '!' without spaces + 'not_operator_with_successor_space' => false, // idem + 'nullable_type_declaration_for_default_null_value' => true, + 'object_operator_without_whitespace' => true, + 'ordered_class_elements' => false, // We prefer to keep some freedom + 'ordered_imports' => true, + 'ordered_interfaces' => true, + 'php_unit_construct' => true, + 'php_unit_dedicate_assert' => true, + 'php_unit_dedicate_assert_internal_type' => true, + 'php_unit_expectation' => true, + 'php_unit_fqcn_annotation' => true, + 'php_unit_internal_class' => false, // Because tests are excluded from package + 'php_unit_method_casing' => true, + 'php_unit_mock' => true, + 'php_unit_mock_short_will_return' => true, + 'php_unit_namespaced' => true, + 'php_unit_no_expectation_annotation' => true, + 'phpdoc_order_by_value' => ['annotations' => ['covers']], + 'php_unit_set_up_tear_down_visibility' => true, + 'php_unit_size_class' => false, // That seems extra work to maintain for little benefits + 'php_unit_strict' => false, // We sometime actually need assertEquals + 'php_unit_test_annotation' => true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage + 'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value + 'phpdoc_align' => false, // Waste of time + 'phpdoc_annotation_without_dot' => true, + 'phpdoc_indent' => true, + //'phpdoc_inline_tag' => true, + 'phpdoc_line_span' => false, // Unfortunately our old comments turn even uglier with this + 'phpdoc_no_access' => true, + 'phpdoc_no_alias_tag' => true, + 'phpdoc_no_empty_return' => true, + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_order' => true, + 'phpdoc_return_self_reference' => true, + 'phpdoc_scalar' => true, + 'phpdoc_separation' => true, + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_summary' => true, + 'phpdoc_to_comment' => false, // interferes with annotations + 'phpdoc_to_param_type' => false, // Because experimental, but interesting for one shot use + 'phpdoc_to_return_type' => false, // idem + 'phpdoc_trim' => true, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_types' => true, + 'phpdoc_types_order' => true, + 'phpdoc_var_annotation_correct_order' => true, + 'phpdoc_var_without_name' => true, + 'pow_to_exponentiation' => true, + 'protected_to_private' => true, + //'psr0' => true, + //'psr4' => true, + 'random_api_migration' => true, + 'return_assignment' => false, // Sometimes useful for clarity or debug + 'return_type_declaration' => true, + 'self_accessor' => true, + 'self_static_accessor' => true, + 'semicolon_after_instruction' => false, // Buggy in `samples/index.php` + 'set_type_to_cast' => true, + 'short_scalar_cast' => true, + 'simple_to_complex_string_variable' => false, // Would differ from TypeScript without obvious advantages + 'simplified_null_return' => false, // Even if technically correct we prefer to be explicit + 'single_blank_line_at_eof' => true, + 'single_blank_line_before_namespace' => true, + 'single_class_element_per_statement' => true, + 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'single_line_comment_style' => true, + 'single_line_throw' => false, // I don't see any reason for having a special case for Exception + 'single_quote' => true, + 'single_trait_insert_per_statement' => true, + 'space_after_semicolon' => true, + 'standardize_increment' => true, + 'standardize_not_equals' => true, + 'static_lambda' => false, // Risky if we can't guarantee nobody use `bindTo()` + 'strict_comparison' => false, // No, too dangerous to change that + 'strict_param' => false, // No, too dangerous to change that + 'string_line_ending' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + 'ternary_operator_spaces' => true, + 'ternary_to_null_coalescing' => true, + 'trailing_comma_in_multiline' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'visibility_required' => ['elements' => ['property', 'method']], // not const + 'void_return' => true, + 'whitespace_after_comma_in_array' => true, + 'yoda_style' => false, + ]); + +return $config; diff --git a/lib/phpoffice/phpspreadsheet/.phpcs.xml.dist b/lib/phpoffice/phpspreadsheet/.phpcs.xml.dist new file mode 100644 index 00000000..3eafb6ca --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/.phpcs.xml.dist @@ -0,0 +1,22 @@ + + + + samples + src + tests + + samples/Header.php + */tests/Core/*/*Test\.(inc|css|js)$ + + + + + + + + + + + + diff --git a/lib/phpoffice/phpspreadsheet/CHANGELOG.md b/lib/phpoffice/phpspreadsheet/CHANGELOG.md new file mode 100644 index 00000000..dbe61211 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/CHANGELOG.md @@ -0,0 +1,1033 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com) +and this project adheres to [Semantic Versioning](https://semver.org). + +## 1.23.0 - 2022-04-24 + +### Added + +- Ods Writer support for Freeze Pane [Issue #2013](https://github.com/PHPOffice/PhpSpreadsheet/issues/2013) [PR #2755](https://github.com/PHPOffice/PhpSpreadsheet/pull/2755) +- Ods Writer support for setting column width/row height (including the use of AutoSize) [Issue #2346](https://github.com/PHPOffice/PhpSpreadsheet/issues/2346) [PR #2753](https://github.com/PHPOffice/PhpSpreadsheet/pull/2753) +- Introduced CellAddress, CellRange, RowRange and ColumnRange value objects that can be used as an alternative to a string value (e.g. `'C5'`, `'B2:D4'`, `'2:2'` or `'B:C'`) in appropriate contexts. +- Implementation of the FILTER(), SORT(), SORTBY() and UNIQUE() Lookup/Reference (array) functions. +- Implementation of the ISREF() Information function. +- Added support for reading "formatted" numeric values from Csv files; although default behaviour of reading these values as strings is preserved. + + (i.e a value of "12,345.67" can be read as numeric `12345.67`, not simply as a string `"12,345.67"`, if the `castFormattedNumberToNumeric()` setting is enabled. + + This functionality is locale-aware, using the server's locale settings to identify the thousands and decimal separators. + +- Support for two cell anchor drawing of images. [#2532](https://github.com/PHPOffice/PhpSpreadsheet/pull/2532) [#2674](https://github.com/PHPOffice/PhpSpreadsheet/pull/2674) +- Limited support for Xls Reader to handle Conditional Formatting: + + Ranges and Rules are read, but style is currently limited to font size, weight and color; and to fill style and color. + +- Add ability to suppress Mac line ending check for CSV [#2623](https://github.com/PHPOffice/PhpSpreadsheet/pull/2623) +- Initial support for creating and writing Tables (Xlsx Writer only) [PR #2671](https://github.com/PHPOffice/PhpSpreadsheet/pull/2671) + + See `/samples/Table` for examples of use. + + Note that PreCalculateFormulas needs to be disabled when saving spreadsheets containing tables with formulae (totals or column formulae). + +### Changed + +- Gnumeric Reader now loads number formatting for cells. +- Gnumeric Reader now correctly identifies selected worksheet and selected cells in a worksheet. +- Some Refactoring of the Ods Reader, moving all formula and address translation from Ods to Excel into a separate class to eliminate code duplication and ensure consistency. +- Make Boolean Conversion in Csv Reader locale-aware when using the String Value Binder. + + This is determined by the Calculation Engine locale setting. + + (i.e. `"Vrai"` wil be converted to a boolean `true` if the Locale is set to `fr`.) +- Allow `psr/simple-cache` 2.x + +### Deprecated + +- All Excel Function implementations in `Calculation\Functions` (including the Error functions) have been moved to dedicated classes for groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. +- Worksheet methods that reference cells "byColumnandRow". All such methods have an equivalent that references the cell by its address (e.g. '`E3'` rather than `5, 3`). + + These functions now accept either a cell address string (`'E3')` or an array with columnId and rowId (`[5, 3]`) or a new `CellAddress` object as their `cellAddress`/`coordinate` argument. + This includes the methods: + - `setCellValueByColumnAndRow()` use the equivalent `setCellValue()` + - `setCellValueExplicitByColumnAndRow()` use the equivalent `setCellValueExplicit()` + - `getCellByColumnAndRow()` use the equivalent `getCell()` + - `cellExistsByColumnAndRow()` use the equivalent `cellExists()` + - `getStyleByColumnAndRow()` use the equivalent `getStyle()` + - `setBreakByColumnAndRow()` use the equivalent `setBreak()` + - `mergeCellsByColumnAndRow()` use the equivalent `mergeCells()` + - `unmergeCellsByColumnAndRow()` use the equivalent `unmergeCells()` + - `protectCellsByColumnAndRow()` use the equivalent `protectCells()` + - `unprotectCellsByColumnAndRow()` use the equivalent `unprotectCells()` + - `setAutoFilterByColumnAndRow()` use the equivalent `setAutoFilter()` + - `freezePaneByColumnAndRow()` use the equivalent `freezePane()` + - `getCommentByColumnAndRow()` use the equivalent `getComment()` + - `setSelectedCellByColumnAndRow()` use the equivalent `setSelectedCells()` + + This change provides more consistency in the methods (not every "by cell address" method has an equivalent "byColumnAndRow" method); + and the "by cell address" methods often provide more flexibility, such as allowing a range of cells, or referencing them by passing the defined name of a named range as the argument. + +### Removed + +- Nothing + +### Fixed + +- Make allowance for the AutoFilter dropdown icon in the first row of an Autofilter range when using Autosize columns. [Issue #2413](https://github.com/PHPOffice/PhpSpreadsheet/issues/2413) [PR #2754](https://github.com/PHPOffice/PhpSpreadsheet/pull/2754) +- Support for "chained" ranges (e.g. `A5:C10:C20:F1`) in the Calculation Engine; and also support for using named ranges with the Range operator (e.g. `NamedRange1:NamedRange2`) [Issue #2730](https://github.com/PHPOffice/PhpSpreadsheet/issues/2730) [PR #2746](https://github.com/PHPOffice/PhpSpreadsheet/pull/2746) +- Update Conditional Formatting ranges and rule conditions when inserting/deleting rows/columns [Issue #2678](https://github.com/PHPOffice/PhpSpreadsheet/issues/2678) [PR #2689](https://github.com/PHPOffice/PhpSpreadsheet/pull/2689) +- Allow `INDIRECT()` to accept row/column ranges as well as cell ranges [PR #2687](https://github.com/PHPOffice/PhpSpreadsheet/pull/2687) +- Fix bug when deleting cells with hyperlinks, where the hyperlink was then being "inherited" by whatever cell moved to that cell address. +- Fix bug in Conditional Formatting in the Xls Writer that resulted in a broken file when there were multiple conditional ranges in a worksheet. +- Fix Conditional Formatting in the Xls Writer to work with rules that contain string literals, cell references and formulae. +- Fix for setting Active Sheet to the first loaded worksheet when bookViews element isn't defined [Issue #2666](https://github.com/PHPOffice/PhpSpreadsheet/issues/2666) [PR #2669](https://github.com/PHPOffice/PhpSpreadsheet/pull/2669) +- Fixed behaviour of XLSX font style vertical align settings [PR #2619](https://github.com/PHPOffice/PhpSpreadsheet/pull/2619) +- Resolved formula translations to handle separators (row and column) for array functions as well as for function argument separators; and cleanly handle nesting levels. + + Note that this method is used when translating Excel functions between `en_us` and other locale languages, as well as when converting formulae between different spreadsheet formats (e.g. Ods to Excel). + + Nor is this a perfect solution, as there may still be issues when function calls have array arguments that themselves contain function calls; but it's still better than the current logic. +- Fix for escaping double quotes within a formula [Issue #1971](https://github.com/PHPOffice/PhpSpreadsheet/issues/1971) [PR #2651](https://github.com/PHPOffice/PhpSpreadsheet/pull/2651) +- Change open mode for output from `wb+` to `wb` [Issue #2372](https://github.com/PHPOffice/PhpSpreadsheet/issues/2372) [PR #2657](https://github.com/PHPOffice/PhpSpreadsheet/pull/2657) +- Use color palette if supplied [Issue #2499](https://github.com/PHPOffice/PhpSpreadsheet/issues/2499) [PR #2595](https://github.com/PHPOffice/PhpSpreadsheet/pull/2595) +- Xls reader treat drawing offsets as int rather than float [PR #2648](https://github.com/PHPOffice/PhpSpreadsheet/pull/2648) +- Handle booleans in conditional styles properly [PR #2654](https://github.com/PHPOffice/PhpSpreadsheet/pull/2654) +- Fix for reading files in the root directory of a ZipFile, which should not be prefixed by relative paths ("./") as dirname($filename) does by default. +- Fix invalid style of cells in empty columns with columnDimensions and rows with rowDimensions in added external sheet. [PR #2739](https://github.com/PHPOffice/PhpSpreadsheet/pull/2739) +- Time Interval Formatting [Issue #2768](https://github.com/PHPOffice/PhpSpreadsheet/issues/2768) [PR #2772](https://github.com/PHPOffice/PhpSpreadsheet/pull/2772) + +## 1.22.0 - 2022-02-18 + +### Added + +- Namespacing phase 2 - styles. +[PR #2471](https://github.com/PHPOffice/PhpSpreadsheet/pull/2471) + +- Improved support for passing of array arguments to Excel function implementations to return array results (where appropriate). [Issue #2551](https://github.com/PHPOffice/PhpSpreadsheet/issues/2551) + + This is the first stage in an ongoing process of adding array support to all appropriate function implementations, +- Support for the Excel365 Math/Trig SEQUENCE() function [PR #2536](https://github.com/PHPOffice/PhpSpreadsheet/pull/2536) +- Support for the Excel365 Math/Trig RANDARRAY() function [PR #2540](https://github.com/PHPOffice/PhpSpreadsheet/pull/2540) + + Note that the Spill Operator is not yet supported in the Calculation Engine; but this can still be useful for defining array constants. +- Improved support for Conditional Formatting Rules [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) + - Provide support for a wider range of Conditional Formatting Rules for Xlsx Reader/Writer: + - Cells Containing (cellIs) + - Specific Text (containing, notContaining, beginsWith, endsWith) + - Dates Occurring (all supported timePeriods) + - Blanks/NoBlanks + - Errors/NoErrors + - Duplicates/Unique + - Expression + - Provision of CF Wizards (for all the above listed rule types) to help create/modify CF Rules without having to manage all the combinations of types/operators, and the complexities of formula expressions, or the text/timePeriod attributes. + + See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/conditional-formatting/) for details + + - Full support of the above CF Rules for the Xlsx Reader and Writer; even when the file being loaded has CF rules listed in the `` element for the worksheet rather than the `` element. + - Provision of a CellMatcher to identify if rules are matched for a cell, and which matching style will be applied. + - Improved documentation and examples, covering all supported CF rule types. + - Add support for one digit decimals (FORMAT_NUMBER_0, FORMAT_PERCENTAGE_0). [PR #2525](https://github.com/PHPOffice/PhpSpreadsheet/pull/2525) + - Initial work enabling Excel function implementations for handling arrays as arguments when used in "array formulae" [#2562](https://github.com/PHPOffice/PhpSpreadsheet/issues/2562) + - Enable most of the Date/Time functions to accept array arguments [#2573](https://github.com/PHPOffice/PhpSpreadsheet/issues/2573) + - Array ready functions - Text, Math/Trig, Statistical, Engineering and Logical [#2580](https://github.com/PHPOffice/PhpSpreadsheet/issues/2580) + +### Changed + +- Additional Russian translations for Excel Functions (courtesy of aleks-samurai). +- Improved code coverage for NumberFormat. [PR #2556](https://github.com/PHPOffice/PhpSpreadsheet/pull/2556) +- Extract some methods from the Calculation Engine into dedicated classes [#2537](https://github.com/PHPOffice/PhpSpreadsheet/issues/2537) +- Eliminate calls to `flattenSingleValue()` that are no longer required when we're checking for array values as arguments [#2590](https://github.com/PHPOffice/PhpSpreadsheet/issues/2590) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Fixed `ReferenceHelper@insertNewBefore` behavior when removing column before last column with null value [PR #2541](https://github.com/PHPOffice/PhpSpreadsheet/pull/2541) +- Fix bug with `DOLLARDE()` and `DOLLARFR()` functions when the dollar value is negative [Issue #2578](https://github.com/PHPOffice/PhpSpreadsheet/issues/2578) [PR #2579](https://github.com/PHPOffice/PhpSpreadsheet/pull/2579) +- Fix partial function name matching when translating formulae from Russian to English [Issue #2533](https://github.com/PHPOffice/PhpSpreadsheet/issues/2533) [PR #2534](https://github.com/PHPOffice/PhpSpreadsheet/pull/2534) +- Various bugs related to Conditional Formatting Rules, and errors in the Xlsx Writer for Conditional Formatting [PR #2491](https://github.com/PHPOffice/PhpSpreadsheet/pull/2491) +- Xlsx Reader merge range fixes. [Issue #2501](https://github.com/PHPOffice/PhpSpreadsheet/issues/2501) [PR #2504](https://github.com/PHPOffice/PhpSpreadsheet/pull/2504) +- Handle explicit "date" type for Cell in Xlsx Reader. [Issue #2373](https://github.com/PHPOffice/PhpSpreadsheet/issues/2373) [PR #2485](https://github.com/PHPOffice/PhpSpreadsheet/pull/2485) +- Recalibrate Row/Column Dimensions after removeRow/Column. [Issue #2442](https://github.com/PHPOffice/PhpSpreadsheet/issues/2442) [PR #2486](https://github.com/PHPOffice/PhpSpreadsheet/pull/2486) +- Refinement for XIRR. [Issue #2469](https://github.com/PHPOffice/PhpSpreadsheet/issues/2469) [PR #2487](https://github.com/PHPOffice/PhpSpreadsheet/pull/2487) +- Xlsx Reader handle cell with non-null explicit type but null value. [Issue #2488](https://github.com/PHPOffice/PhpSpreadsheet/issues/2488) [PR #2489](https://github.com/PHPOffice/PhpSpreadsheet/pull/2489) +- Xlsx Reader fix height and width for oneCellAnchorDrawings. [PR #2492](https://github.com/PHPOffice/PhpSpreadsheet/pull/2492) +- Fix rounding error in NumberFormat::NUMBER_PERCENTAGE, NumberFormat::NUMBER_PERCENTAGE_00. [PR #2555](https://github.com/PHPOffice/PhpSpreadsheet/pull/2555) +- Don't treat thumbnail file as xml. [Issue #2516](https://github.com/PHPOffice/PhpSpreadsheet/issues/2516) [PR #2517](https://github.com/PHPOffice/PhpSpreadsheet/pull/2517) +- Eliminating Xlsx Reader warning when no sz tag for RichText. [Issue #2542](https://github.com/PHPOffice/PhpSpreadsheet/issues/2542) [PR #2550](https://github.com/PHPOffice/PhpSpreadsheet/pull/2550) +- Fix Xlsx/Xls Writer handling of inline strings. [Issue #353](https://github.com/PHPOffice/PhpSpreadsheet/issues/353) [PR #2569](https://github.com/PHPOffice/PhpSpreadsheet/pull/2569) +- Richtext colors were not being read correctly after namespace change [#2458](https://github.com/PHPOffice/PhpSpreadsheet/issues/2458) +- Fix discrepancy between the way markdown tables are rendered in ReadTheDocs and in PHPStorm [#2520](https://github.com/PHPOffice/PhpSpreadsheet/issues/2520) +- Update Russian Functions Text File [#2557](https://github.com/PHPOffice/PhpSpreadsheet/issues/2557) +- Fix documentation, instantiation example [#2564](https://github.com/PHPOffice/PhpSpreadsheet/issues/2564) + + +## 1.21.0 - 2022-01-06 + +### Added + +- Ability to add a picture to the background of the comment. Supports four image formats: png, jpeg, gif, bmp. New `Comment::setSizeAsBackgroundImage()` to change the size of a comment to the size of a background image. [Issue #1547](https://github.com/PHPOffice/PhpSpreadsheet/issues/1547) [PR #2422](https://github.com/PHPOffice/PhpSpreadsheet/pull/2422) +- Ability to set default paper size and orientation [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410) +- Ability to extend AutoFilter to Maximum Row [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) + +### Changed + +- Xlsx Writer will evaluate AutoFilter only if it is as yet unevaluated, or has changed since it was last evaluated [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Rounding in `NumberFormatter` [Issue #2385](https://github.com/PHPOffice/PhpSpreadsheet/issues/2385) [PR #2399](https://github.com/PHPOffice/PhpSpreadsheet/pull/2399) +- Support for themes [Issue #2075](https://github.com/PHPOffice/PhpSpreadsheet/issues/2075) [Issue #2387](https://github.com/PHPOffice/PhpSpreadsheet/issues/2387) [PR #2403](https://github.com/PHPOffice/PhpSpreadsheet/pull/2403) +- Read spreadsheet with `#` in name [Issue #2405](https://github.com/PHPOffice/PhpSpreadsheet/issues/2405) [PR #2409](https://github.com/PHPOffice/PhpSpreadsheet/pull/2409) +- Improve PDF support for page size and orientation [Issue #1691](https://github.com/PHPOffice/PhpSpreadsheet/issues/1691) [PR #2410](https://github.com/PHPOffice/PhpSpreadsheet/pull/2410) +- Wildcard handling issues in text match [Issue #2430](https://github.com/PHPOffice/PhpSpreadsheet/issues/2430) [PR #2431](https://github.com/PHPOffice/PhpSpreadsheet/pull/2431) +- Respect DataType in `insertNewBefore` [PR #2433](https://github.com/PHPOffice/PhpSpreadsheet/pull/2433) +- Handle rows explicitly hidden after AutoFilter [Issue #1641](https://github.com/PHPOffice/PhpSpreadsheet/issues/1641) [PR #2414](https://github.com/PHPOffice/PhpSpreadsheet/pull/2414) +- Special characters in image file name [Issue #1470](https://github.com/PHPOffice/PhpSpreadsheet/issues/1470) [Issue #2415](https://github.com/PHPOffice/PhpSpreadsheet/issues/2415) [PR #2416](https://github.com/PHPOffice/PhpSpreadsheet/pull/2416) +- Mpdf with very many styles [Issue #2432](https://github.com/PHPOffice/PhpSpreadsheet/issues/2432) [PR #2434](https://github.com/PHPOffice/PhpSpreadsheet/pull/2434) +- Name clashes between parsed and unparsed drawings [Issue #1767](https://github.com/PHPOffice/PhpSpreadsheet/issues/1767) [Issue #2396](https://github.com/PHPOffice/PhpSpreadsheet/issues/2396) [PR #2423](https://github.com/PHPOffice/PhpSpreadsheet/pull/2423) +- Fill pattern start and end colors [Issue #2441](https://github.com/PHPOffice/PhpSpreadsheet/issues/2441) [PR #2444](https://github.com/PHPOffice/PhpSpreadsheet/pull/2444) +- General style specified in wrong case [Issue #2450](https://github.com/PHPOffice/PhpSpreadsheet/issues/2450) [PR #2451](https://github.com/PHPOffice/PhpSpreadsheet/pull/2451) +- Null passed to `AutoFilter::setRange()` [Issue #2281](https://github.com/PHPOffice/PhpSpreadsheet/issues/2281) [PR #2454](https://github.com/PHPOffice/PhpSpreadsheet/pull/2454) +- Another undefined index in Xls reader (#2470) [Issue #2463](https://github.com/PHPOffice/PhpSpreadsheet/issues/2463) [PR #2470](https://github.com/PHPOffice/PhpSpreadsheet/pull/2470) +- Allow single-cell checks on conditional styles, even when the style is configured for a range of cells (#) [PR #2483](https://github.com/PHPOffice/PhpSpreadsheet/pull/2483) + +## 1.20.0 - 2021-11-23 + +### Added + +- Xlsx Writer Support for WMF Files [#2339](https://github.com/PHPOffice/PhpSpreadsheet/issues/2339) +- Use standard temporary file for internal use of HTMLPurifier [#2383](https://github.com/PHPOffice/PhpSpreadsheet/issues/2383) + +### Changed + +- Drop support for PHP 7.2, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support +- Use native typing for objects that were already documented as such + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Fixed null conversation for strToUpper [#2292](https://github.com/PHPOffice/PhpSpreadsheet/issues/2292) +- Fixed Trying to access array offset on value of type null (Xls Reader) [#2315](https://github.com/PHPOffice/PhpSpreadsheet/issues/2315) +- Don't corrupt XLSX files containing data validation [#2377](https://github.com/PHPOffice/PhpSpreadsheet/issues/2377) +- Non-fixed cells were not updated if shared formula has a fixed cell [#2354](https://github.com/PHPOffice/PhpSpreadsheet/issues/2354) +- Declare key of generic ArrayObject +- CSV reader better support for boolean values [#2374](https://github.com/PHPOffice/PhpSpreadsheet/pull/2374) +- Some ZIP file could not be read [#2376](https://github.com/PHPOffice/PhpSpreadsheet/pull/2376) +- Fix regression were hyperlinks could not be read [#2391](https://github.com/PHPOffice/PhpSpreadsheet/pull/2391) +- AutoFilter Improvements [#2393](https://github.com/PHPOffice/PhpSpreadsheet/pull/2393) +- Don't corrupt file when using chart with fill color [#589](https://github.com/PHPOffice/PhpSpreadsheet/pull/589) +- Restore imperfect array formula values in xlsx writer [#2343](https://github.com/PHPOffice/PhpSpreadsheet/pull/2343) +- Restore explicit list of changes to PHPExcel migration document [#1546](https://github.com/PHPOffice/PhpSpreadsheet/issues/1546) + +## 1.19.0 - 2021-10-31 + +### Added + +- Ability to set style on named range, and validate input to setSelectedCells [Issue #2279](https://github.com/PHPOffice/PhpSpreadsheet/issues/2279) [PR #2280](https://github.com/PHPOffice/PhpSpreadsheet/pull/2280) +- Process comments in Sylk file [Issue #2276](https://github.com/PHPOffice/PhpSpreadsheet/issues/2276) [PR #2277](https://github.com/PHPOffice/PhpSpreadsheet/pull/2277) +- Addition of Custom Properties to Ods Writer, and 32-bit-safe timestamps for Document Properties [PR #2113](https://github.com/PHPOffice/PhpSpreadsheet/pull/2113) +- Added callback to CSV reader to set user-specified defaults for various properties (especially for escape which has a poor PHP-inherited default of backslash which does not correspond with Excel) [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) +- Phase 1 of better namespace handling for Xlsx, resolving many open issues [PR #2173](https://github.com/PHPOffice/PhpSpreadsheet/pull/2173) [PR #2204](https://github.com/PHPOffice/PhpSpreadsheet/pull/2204) [PR #2303](https://github.com/PHPOffice/PhpSpreadsheet/pull/2303) +- Add ability to extract images if source is a URL [Issue #1997](https://github.com/PHPOffice/PhpSpreadsheet/issues/1997) [PR #2072](https://github.com/PHPOffice/PhpSpreadsheet/pull/2072) +- Support for passing flags in the Reader `load()` and Writer `save()`methods, and through the IOFactory, to set behaviours [PR #2136](https://github.com/PHPOffice/PhpSpreadsheet/pull/2136) + - See [documentation](https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/#readerwriter-flags) for details +- More flexibility in the StringValueBinder to determine what datatypes should be treated as strings [PR #2138](https://github.com/PHPOffice/PhpSpreadsheet/pull/2138) +- Helper class for conversion between css size Units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`) [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) +- Allow Row height and Column Width to be set using different units of measure (`px`, `pt`, `pc`, `in`, `cm`, `mm`), rather than only in points or MS Excel column width units [PR #2152](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145) +- Ability to stream to an Amazon S3 bucket [Issue #2249](https://github.com/PHPOffice/PhpSpreadsheet/issues/2249) +- Provided a Size Helper class to validate size values (pt, px, em) [PR #1694](https://github.com/PHPOffice/PhpSpreadsheet/pull/1694) + +### Changed + +- Nothing. + +### Deprecated + +- PHP 8.1 will deprecate auto_detect_line_endings. As a result of this change, Csv Reader using some release after PHP8.1 will no longer be able to handle a Csv with Mac line endings. + +### Removed + +- Nothing. + +### Fixed + +- Unexpected format in Xlsx Timestamp [Issue #2331](https://github.com/PHPOffice/PhpSpreadsheet/issues/2331) [PR #2332](https://github.com/PHPOffice/PhpSpreadsheet/pull/2332) +- Corrections for HLOOKUP [Issue #2123](https://github.com/PHPOffice/PhpSpreadsheet/issues/2123) [PR #2330](https://github.com/PHPOffice/PhpSpreadsheet/pull/2330) +- Corrections for Xlsx Read Comments [Issue #2316](https://github.com/PHPOffice/PhpSpreadsheet/issues/2316) [PR #2329](https://github.com/PHPOffice/PhpSpreadsheet/pull/2329) +- Lowercase Calibri font names [Issue #2273](https://github.com/PHPOffice/PhpSpreadsheet/issues/2273) [PR #2325](https://github.com/PHPOffice/PhpSpreadsheet/pull/2325) +- isFormula Referencing Sheet with Space in Title [Issue #2304](https://github.com/PHPOffice/PhpSpreadsheet/issues/2304) [PR #2306](https://github.com/PHPOffice/PhpSpreadsheet/pull/2306) +- Xls Reader Fatal Error due to Undefined Offset [Issue #1114](https://github.com/PHPOffice/PhpSpreadsheet/issues/1114) [PR #2308](https://github.com/PHPOffice/PhpSpreadsheet/pull/2308) +- Permit Csv Reader delimiter to be set to null [Issue #2287](https://github.com/PHPOffice/PhpSpreadsheet/issues/2287) [PR #2288](https://github.com/PHPOffice/PhpSpreadsheet/pull/2288) +- Csv Reader did not handle booleans correctly [PR #2232](https://github.com/PHPOffice/PhpSpreadsheet/pull/2232) +- Problems when deleting sheet with local defined name [Issue #2266](https://github.com/PHPOffice/PhpSpreadsheet/issues/2266) [PR #2284](https://github.com/PHPOffice/PhpSpreadsheet/pull/2284) +- Worksheet passwords were not always handled correctly [Issue #1897](https://github.com/PHPOffice/PhpSpreadsheet/issues/1897) [PR #2197](https://github.com/PHPOffice/PhpSpreadsheet/pull/2197) +- Gnumeric Reader will now distinguish between Created and Modified timestamp [PR #2133](https://github.com/PHPOffice/PhpSpreadsheet/pull/2133) +- Xls Reader will now handle MACCENTRALEUROPE with or without hyphen [Issue #549](https://github.com/PHPOffice/PhpSpreadsheet/issues/549) [PR #2213](https://github.com/PHPOffice/PhpSpreadsheet/pull/2213) +- Tweaks to input file validation [Issue #1718](https://github.com/PHPOffice/PhpSpreadsheet/issues/1718) [PR #2217](https://github.com/PHPOffice/PhpSpreadsheet/pull/2217) +- Html Reader did not handle comments correctly [Issue #2234](https://github.com/PHPOffice/PhpSpreadsheet/issues/2234) [PR #2235](https://github.com/PHPOffice/PhpSpreadsheet/pull/2235) +- Apache OpenOffice Uses Unexpected Case for General format [Issue #2239](https://github.com/PHPOffice/PhpSpreadsheet/issues/2239) [PR #2242](https://github.com/PHPOffice/PhpSpreadsheet/pull/2242) +- Problems with fraction formatting [Issue #2253](https://github.com/PHPOffice/PhpSpreadsheet/issues/2253) [PR #2254](https://github.com/PHPOffice/PhpSpreadsheet/pull/2254) +- Xlsx Reader had problems reading file with no styles.xml or empty styles.xml [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) [PR #2247](https://github.com/PHPOffice/PhpSpreadsheet/pull/2247) +- Xlsx Reader did not read Data Validation flags correctly [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) +- Better handling of empty arguments in Calculation engine [PR #2143](https://github.com/PHPOffice/PhpSpreadsheet/pull/2143) +- Many fixes for Autofilter [Issue #2216](https://github.com/PHPOffice/PhpSpreadsheet/issues/2216) [PR #2141](https://github.com/PHPOffice/PhpSpreadsheet/pull/2141) [PR #2162](https://github.com/PHPOffice/PhpSpreadsheet/pull/2162) [PR #2218](https://github.com/PHPOffice/PhpSpreadsheet/pull/2218) +- Locale generator will now use Unix line endings even on Windows [Issue #2172](https://github.com/PHPOffice/PhpSpreadsheet/issues/2172) [PR #2174](https://github.com/PHPOffice/PhpSpreadsheet/pull/2174) +- Support differences in implementation of Text functions between Excel/Ods/Gnumeric [PR #2151](https://github.com/PHPOffice/PhpSpreadsheet/pull/2151) +- Fixes to places where PHP8.1 enforces new or previously unenforced restrictions [PR #2137](https://github.com/PHPOffice/PhpSpreadsheet/pull/2137) [PR #2191](https://github.com/PHPOffice/PhpSpreadsheet/pull/2191) [PR #2231](https://github.com/PHPOffice/PhpSpreadsheet/pull/2231) +- Clone for HashTable was incorrect [PR #2130](https://github.com/PHPOffice/PhpSpreadsheet/pull/2130) +- Xlsx Reader was not evaluating Document Security Lock correctly [PR #2128](https://github.com/PHPOffice/PhpSpreadsheet/pull/2128) +- Error in COUPNCD handling end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) +- Xls Writer Parser did not handle concatenation operator correctly [PR #2080](https://github.com/PHPOffice/PhpSpreadsheet/pull/2080) +- Xlsx Writer did not handle boolean false correctly [Issue #2082](https://github.com/PHPOffice/PhpSpreadsheet/issues/2082) [PR #2087](https://github.com/PHPOffice/PhpSpreadsheet/pull/2087) +- SUM needs to treat invalid strings differently depending on whether they come from a cell or are used as literals [Issue #2042](https://github.com/PHPOffice/PhpSpreadsheet/issues/2042) [PR #2045](https://github.com/PHPOffice/PhpSpreadsheet/pull/2045) +- Html reader could have set illegal coordinates when dealing with embedded tables [Issue #2029](https://github.com/PHPOffice/PhpSpreadsheet/issues/2029) [PR #2032](https://github.com/PHPOffice/PhpSpreadsheet/pull/2032) +- Documentation for printing gridlines was wrong [PR #2188](https://github.com/PHPOffice/PhpSpreadsheet/pull/2188) +- Return Value Error - DatabaseAbstruct::buildQuery() return null but must be string [Issue #2158](https://github.com/PHPOffice/PhpSpreadsheet/issues/2158) [PR #2160](https://github.com/PHPOffice/PhpSpreadsheet/pull/2160) +- Xlsx reader not recognize data validations that references another sheet [Issue #1432](https://github.com/PHPOffice/PhpSpreadsheet/issues/1432) [Issue #2149](https://github.com/PHPOffice/PhpSpreadsheet/issues/2149) [PR #2150](https://github.com/PHPOffice/PhpSpreadsheet/pull/2150) [PR #2265](https://github.com/PHPOffice/PhpSpreadsheet/pull/2265) +- Don't calculate cell width for autosize columns if a cell contains a null or empty string value [Issue #2165](https://github.com/PHPOffice/PhpSpreadsheet/issues/2165) [PR #2167](https://github.com/PHPOffice/PhpSpreadsheet/pull/2167) +- Allow negative interest rate values in a number of the Financial functions (`PPMT()`, `PMT()`, `FV()`, `PV()`, `NPER()`, etc) [Issue #2163](https://github.com/PHPOffice/PhpSpreadsheet/issues/2163) [PR #2164](https://github.com/PHPOffice/PhpSpreadsheet/pull/2164) +- Xls Reader changing grey background to black in Excel template [Issue #2147](https://github.com/PHPOffice/PhpSpreadsheet/issues/2147) [PR #2156](https://github.com/PHPOffice/PhpSpreadsheet/pull/2156) +- Column width and Row height styles in the Html Reader when the value includes a unit of measure [Issue #2145](https://github.com/PHPOffice/PhpSpreadsheet/issues/2145). +- Data Validation flags not set correctly when reading XLSX files [Issue #2224](https://github.com/PHPOffice/PhpSpreadsheet/issues/2224) [PR #2225](https://github.com/PHPOffice/PhpSpreadsheet/pull/2225) +- Reading XLSX files without styles.xml throws an exception [Issue #2246](https://github.com/PHPOffice/PhpSpreadsheet/issues/2246) +- Improved performance of `Style::applyFromArray()` when applied to several cells [PR #1785](https://github.com/PHPOffice/PhpSpreadsheet/issues/1785). +- Improve XLSX parsing speed if no readFilter is applied (again) - [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) + +## 1.18.0 - 2021-05-31 + +### Added + +- Enhancements to CSV Reader, allowing options to be set when using `IOFactory::load()` with a callback to set delimiter, enclosure, charset etc [PR #2103](https://github.com/PHPOffice/PhpSpreadsheet/pull/2103) - See [documentation](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md#csv-comma-separated-values) for details. +- Implemented basic AutoFiltering for Ods Reader and Writer [PR #2053](https://github.com/PHPOffice/PhpSpreadsheet/pull/2053) +- Implemented basic AutoFiltering for Gnumeric Reader [PR #2055](https://github.com/PHPOffice/PhpSpreadsheet/pull/2055) +- Improved support for Row and Column ranges in formulae [Issue #1755](https://github.com/PHPOffice/PhpSpreadsheet/issues/1755) [PR #2028](https://github.com/PHPOffice/PhpSpreadsheet/pull/2028) +- Implemented URLENCODE() Web Function +- Implemented the CHITEST(), CHISQ.DIST() and CHISQ.INV() and equivalent Statistical functions, for both left- and right-tailed distributions. +- Support for ActiveSheet and SelectedCells in the ODS Reader and Writer [PR #1908](https://github.com/PHPOffice/PhpSpreadsheet/pull/1908) +- Support for notContainsText Conditional Style in xlsx [Issue #984](https://github.com/PHPOffice/PhpSpreadsheet/issues/984) + +### Changed + +- Use of `nb` rather than `no` as the locale code for Norsk Bokmål. + +### Deprecated + +- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. + +### Removed + +- Use of `nb` rather than `no` as the locale language code for Norsk Bokmål. + +### Fixed + +- Fixed error in COUPNCD() calculation for end of month [Issue #2116](https://github.com/PHPOffice/PhpSpreadsheet/issues/2116) - [PR #2119](https://github.com/PHPOffice/PhpSpreadsheet/pull/2119) +- Resolve default values when a null argument is passed for HLOOKUP(), VLOOKUP() and ADDRESS() functions [Issue #2120](https://github.com/PHPOffice/PhpSpreadsheet/issues/2120) - [PR #2121](https://github.com/PHPOffice/PhpSpreadsheet/pull/2121) +- Fixed incorrect R1C1 to A1 subtraction formula conversion (`R[-2]C-R[2]C`) [Issue #2076](https://github.com/PHPOffice/PhpSpreadsheet/pull/2076) [PR #2086](https://github.com/PHPOffice/PhpSpreadsheet/pull/2086) +- Correctly handle absolute A1 references when converting to R1C1 format [PR #2060](https://github.com/PHPOffice/PhpSpreadsheet/pull/2060) +- Correct default fill style for conditional without a pattern defined [Issue #2035](https://github.com/PHPOffice/PhpSpreadsheet/issues/2035) [PR #2050](https://github.com/PHPOffice/PhpSpreadsheet/pull/2050) +- Fixed issue where array key check for existince before accessing arrays in Xlsx.php [PR #1970](https://github.com/PHPOffice/PhpSpreadsheet/pull/1970) +- Fixed issue with quoted strings in number format mask rendered with toFormattedString() [Issue 1972#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1972) [PR #1978](https://github.com/PHPOffice/PhpSpreadsheet/pull/1978) +- Fixed issue with percentage formats in number format mask rendered with toFormattedString() [Issue 1929#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1929) [PR #1928](https://github.com/PHPOffice/PhpSpreadsheet/pull/1928) +- Fixed issue with _ spacing character in number format mask corrupting output from toFormattedString() [Issue 1924#](https://github.com/PHPOffice/PhpSpreadsheet/issues/1924) [PR #1927](https://github.com/PHPOffice/PhpSpreadsheet/pull/1927) +- Fix for [Issue #1887](https://github.com/PHPOffice/PhpSpreadsheet/issues/1887) - Lose Track of Selected Cells After Save +- Fixed issue with Xlsx@listWorksheetInfo not returning any data +- Fixed invalid arguments triggering mb_substr() error in LEFT(), MID() and RIGHT() text functions [Issue #640](https://github.com/PHPOffice/PhpSpreadsheet/issues/640) +- Fix for [Issue #1916](https://github.com/PHPOffice/PhpSpreadsheet/issues/1916) - Invalid signature check for XML files +- Fix change in `Font::setSize()` behavior for PHP8 [PR #2100](https://github.com/PHPOffice/PhpSpreadsheet/pull/2100) + +## 1.17.1 - 2021-03-01 + +### Added + +- Implementation of the Excel `AVERAGEIFS()` functions as part of a restructuring of Database functions and Conditional Statistical functions. +- Support for date values and percentages in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1875](https://github.com/PHPOffice/PhpSpreadsheet/pull/1875) +- Support for booleans, and for wildcard text search in query parameters for Database functions, and the IF expressions in functions like COUNTIF() and AVERAGEIF(). [#1876](https://github.com/PHPOffice/PhpSpreadsheet/pull/1876) +- Implemented DataBar for conditional formatting in Xlsx, providing read/write and creation of (type, value, direction, fills, border, axis position, color settings) as DataBar options in Excel. [#1754](https://github.com/PHPOffice/PhpSpreadsheet/pull/1754) +- Alignment for ODS Writer [#1796](https://github.com/PHPOffice/PhpSpreadsheet/issues/1796) +- Basic implementation of the PERMUTATIONA() Statistical Function + +### Changed + +- Formula functions that previously called PHP functions directly are now processed through the Excel Functions classes; resolving issues with PHP8 stricter typing. [#1789](https://github.com/PHPOffice/PhpSpreadsheet/issues/1789) + + The following MathTrig functions are affected: + `ABS()`, `ACOS()`, `ACOSH()`, `ASIN()`, `ASINH()`, `ATAN()`, `ATANH()`, + `COS()`, `COSH()`, `DEGREES()` (rad2deg), `EXP()`, `LN()` (log), `LOG10()`, + `RADIANS()` (deg2rad), `SIN()`, `SINH()`, `SQRT()`, `TAN()`, `TANH()`. + + One TextData function is also affected: `REPT()` (str_repeat). +- `formatAsDate` correctly matches language metadata, reverting c55272e +- Formulae that previously crashed on sub function call returning excel error value now return said value. + The following functions are affected `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, + `AMORDEGRC()`. +- Adapt some function error return value to match excel's error. + The following functions are affected `PPMT()`, `IPMT()`. + +### Deprecated + +- Calling many of the Excel formula functions directly rather than through the Calculation Engine. + + The logic for these Functions is now being moved out of the categorised `Database`, `DateTime`, `Engineering`, `Financial`, `Logical`, `LookupRef`, `MathTrig`, `Statistical`, `TextData` and `Web` classes into small, dedicated classes for individual functions or related groups of functions. + + This makes the logic in these classes easier to maintain; and will reduce the memory footprint required to execute formulae when calling these functions. + +### Removed + +- Nothing. + +### Fixed + +- Avoid Duplicate Titles When Reading Multiple HTML Files.[Issue #1823](https://github.com/PHPOffice/PhpSpreadsheet/issues/1823) [PR #1829](https://github.com/PHPOffice/PhpSpreadsheet/pull/1829) +- Fixed issue with Worksheet's `getCell()` method when trying to get a cell by defined name. [#1858](https://github.com/PHPOffice/PhpSpreadsheet/issues/1858) +- Fix possible endless loop in NumberFormat Masks [#1792](https://github.com/PHPOffice/PhpSpreadsheet/issues/1792) +- Fix problem resulting from literal dot inside quotes in number format masks [PR #1830](https://github.com/PHPOffice/PhpSpreadsheet/pull/1830) +- Resolve Google Sheets Xlsx charts issue. Google Sheets uses oneCellAnchor positioning and does not include *Cache values in the exported Xlsx [PR #1761](https://github.com/PHPOffice/PhpSpreadsheet/pull/1761) +- Fix for Xlsx Chart axis titles mapping to correct X or Y axis label when only one is present [PR #1760](https://github.com/PHPOffice/PhpSpreadsheet/pull/1760) +- Fix For Null Exception on ODS Read of Page Settings. [#1772](https://github.com/PHPOffice/PhpSpreadsheet/issues/1772) +- Fix Xlsx reader overriding manually set number format with builtin number format [PR #1805](https://github.com/PHPOffice/PhpSpreadsheet/pull/1805) +- Fix Xlsx reader cell alignment [PR #1710](https://github.com/PHPOffice/PhpSpreadsheet/pull/1710) +- Fix for not yet implemented data-types in Open Document writer [Issue #1674](https://github.com/PHPOffice/PhpSpreadsheet/issues/1674) +- Fix XLSX reader when having a corrupt numeric cell data type [PR #1664](https://github.com/phpoffice/phpspreadsheet/pull/1664) +- Fix on `CUMPRINC()`, `CUMIPMT()`, `AMORLINC()`, `AMORDEGRC()` usage. When those functions called one of `YEARFRAC()`, `PPMT()`, `IPMT()` and they would get back an error value (represented as a string), trying to use numeral operands (`+`, `/`, `-`, `*`) on said return value and a number (`float or `int`) would fail. + +## 1.16.0 - 2020-12-31 + +### Added + +- CSV Reader - Best Guess for Encoding, and Handle Null-string Escape [#1647](https://github.com/PHPOffice/PhpSpreadsheet/issues/1647) + +### Changed + +- Updated the CONVERT() function to support all current MS Excel categories and Units of Measure. + +### Deprecated + +- All Excel Function implementations in `Calculation\Database`, `Calculation\DateTime`, `Calculation\Engineering`, `Calculation\Financial`, `Calculation\Logical`, `Calculation\LookupRef`, `Calculation\MathTrig`, `Calculation\Statistical`, `Calculation\TextData` and `Calculation\Web` have been moved to dedicated classes for individual functions or groups of related functions. See the docblocks against all the deprecated methods for details of the new methods to call instead. At some point, these old classes will be deleted. + +### Removed + +- Nothing. + +### Fixed + +- Fixed issue with absolute path in worksheets' Target [PR #1769](https://github.com/PHPOffice/PhpSpreadsheet/pull/1769) +- Fix for Xls Reader when SST has a bad length [#1592](https://github.com/PHPOffice/PhpSpreadsheet/issues/1592) +- Resolve Xlsx loader issue whe hyperlinks don't have a destination +- Resolve issues when printer settings resources IDs clash with drawing IDs +- Resolve issue with SLK long filenames [#1612](https://github.com/PHPOffice/PhpSpreadsheet/issues/1612) +- ROUNDUP and ROUNDDOWN return incorrect results for values of 0 [#1627](https://github.com/phpoffice/phpspreadsheet/pull/1627) +- Apply Column and Row Styles to Existing Cells [#1712](https://github.com/PHPOffice/PhpSpreadsheet/issues/1712) [PR #1721](https://github.com/PHPOffice/PhpSpreadsheet/pull/1721) +- Resolve issues with defined names where worksheet doesn't exist (#1686)[https://github.com/PHPOffice/PhpSpreadsheet/issues/1686] and [#1723](https://github.com/PHPOffice/PhpSpreadsheet/issues/1723) - [PR #1742](https://github.com/PHPOffice/PhpSpreadsheet/pull/1742) +- Fix for issue [#1735](https://github.com/PHPOffice/PhpSpreadsheet/issues/1735) Incorrect activeSheetIndex after RemoveSheetByIndex - [PR #1743](https://github.com/PHPOffice/PhpSpreadsheet/pull/1743) +- Ensure that the list of shared formulae is maintained when an xlsx file is chunked with readFilter[Issue #169](https://github.com/PHPOffice/PhpSpreadsheet/issues/1669). +- Fix for notice during accessing "cached magnification factor" offset [#1354](https://github.com/PHPOffice/PhpSpreadsheet/pull/1354) +- Fix compatibility with ext-gd on php 8 + +### Security Fix (CVE-2020-7776) + +- Prevent XSS through cell comments in the HTML Writer. + +## 1.15.0 - 2020-10-11 + +### Added + +- Implemented Page Order for Xlsx and Xls Readers, and provided Page Settings (Orientation, Scale, Horizontal/Vertical Centering, Page Order, Margins) support for Ods, Gnumeric and Xls Readers [#1559](https://github.com/PHPOffice/PhpSpreadsheet/pull/1559) +- Implementation of the Excel `LOGNORM.DIST()`, `NORM.S.DIST()`, `GAMMA()` and `GAUSS()` functions. [#1588](https://github.com/PHPOffice/PhpSpreadsheet/pull/1588) +- Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) + - Defined Names are now case-insensitive + - Distinction between named ranges and named formulae + - Correct handling of union and intersection operators in named ranges + - Correct evaluation of named range operators in calculations + - fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. + - Calculation support for named formulae + - Support for nested ranges and formulae (named ranges and formulae that reference other named ranges/formulae) in calculations + - Introduction of a helper to convert address formats between R1C1 and A1 (and the reverse) + - Proper support for both named ranges and named formulae in all appropriate Readers + - **Xlsx** (Previously only simple named ranges were supported) + - **Xls** (Previously only simple named ranges were supported) + - **Gnumeric** (Previously neither named ranges nor formulae were supported) + - **Ods** (Previously neither named ranges nor formulae were supported) + - **Xml** (Previously neither named ranges nor formulae were supported) + - Proper support for named ranges and named formulae in all appropriate Writers + - **Xlsx** (Previously only simple named ranges were supported) + - **Xls** (Previously neither named ranges nor formulae were supported) - Still not supported, but some parser issues resolved that previously failed to differentiate between a defined name and a function name + - **Ods** (Previously neither named ranges nor formulae were supported) +- Support for PHP 8.0 + +### Changed + +- Improve Coverage for ODS Reader [#1545](https://github.com/phpoffice/phpspreadsheet/pull/1545) +- Named formula implementation, and improved handling of Defined Names generally [#1535](https://github.com/PHPOffice/PhpSpreadsheet/pull/1535) +- fix resolution of relative named range values in the calculation engine; previously all named range values had been treated as absolute. +- Drop $this->spreadSheet null check from Xlsx Writer [#1646](https://github.com/phpoffice/phpspreadsheet/pull/1646) +- Improving Coverage for Excel2003 XML Reader [#1557](https://github.com/phpoffice/phpspreadsheet/pull/1557) + +### Deprecated + +- **IMPORTANT NOTE:** This Introduces a **BC break** in the handling of named ranges. Previously, a named range cell reference of `B2` would be treated identically to a named range cell reference of `$B2` or `B$2` or `$B$2` because the calculation engine treated then all as absolute references. These changes "fix" that, so the calculation engine now handles relative references in named ranges correctly. + This change that resolves previously incorrect behaviour in the calculation may affect users who have dynamically defined named ranges using relative references when they should have used absolute references. + +### Removed + +- Nothing. + +### Fixed + +- PrintArea causes exception [#1544](https://github.com/phpoffice/phpspreadsheet/pull/1544) +- Calculation/DateTime Failure With PHP8 [#1661](https://github.com/phpoffice/phpspreadsheet/pull/1661) +- Reader/Gnumeric Failure with PHP8 [#1662](https://github.com/phpoffice/phpspreadsheet/pull/1662) +- ReverseSort bug, exposed but not caused by PHP8 [#1660](https://github.com/phpoffice/phpspreadsheet/pull/1660) +- Bug setting Superscript/Subscript to false [#1567](https://github.com/phpoffice/phpspreadsheet/pull/1567) + +## 1.14.1 - 2020-07-19 + +### Added + +- nothing + +### Fixed + +- WEBSERVICE is HTTP client agnostic and must be configured via `Settings::setHttpClient()` [#1562](https://github.com/PHPOffice/PhpSpreadsheet/issues/1562) +- Borders were not complete on rowspanned columns using HTML reader [#1473](https://github.com/PHPOffice/PhpSpreadsheet/pull/1473) + +### Changed + +## 1.14.0 - 2020-06-29 + +### Added + +- Add support for IFS() logical function [#1442](https://github.com/PHPOffice/PhpSpreadsheet/pull/1442) +- Add Cell Address Helper to provide conversions between the R1C1 and A1 address formats [#1558](https://github.com/PHPOffice/PhpSpreadsheet/pull/1558) +- Add ability to edit Html/Pdf before saving [#1499](https://github.com/PHPOffice/PhpSpreadsheet/pull/1499) +- Add ability to set codepage explicitly for BIFF5 [#1018](https://github.com/PHPOffice/PhpSpreadsheet/issues/1018) +- Added support for the WEBSERVICE function [#1409](https://github.com/PHPOffice/PhpSpreadsheet/pull/1409) + +### Fixed + +- Resolve evaluation of utf-8 named ranges in calculation engine [#1522](https://github.com/PHPOffice/PhpSpreadsheet/pull/1522) +- Fix HLOOKUP on single row [#1512](https://github.com/PHPOffice/PhpSpreadsheet/pull/1512) +- Fix MATCH when comparing different numeric types [#1521](https://github.com/PHPOffice/PhpSpreadsheet/pull/1521) +- Fix exact MATCH on ranges with empty cells [#1520](https://github.com/PHPOffice/PhpSpreadsheet/pull/1520) +- Fix for Issue [#1516](https://github.com/PHPOffice/PhpSpreadsheet/issues/1516) (Cloning worksheet makes corrupted Xlsx) [#1530](https://github.com/PHPOffice/PhpSpreadsheet/pull/1530) +- Fix For Issue [#1509](https://github.com/PHPOffice/PhpSpreadsheet/issues/1509) (Can not set empty enclosure for CSV) [#1518](https://github.com/PHPOffice/PhpSpreadsheet/pull/1518) +- Fix for Issue [#1505](https://github.com/PHPOffice/PhpSpreadsheet/issues/1505) (TypeError : Argument 4 passed to PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeAttributeIf() must be of the type string) [#1525](https://github.com/PHPOffice/PhpSpreadsheet/pull/1525) +- Fix for Issue [#1495](https://github.com/PHPOffice/PhpSpreadsheet/issues/1495) (Sheet index being changed when multiple sheets are used in formula) [#1500]((https://github.com/PHPOffice/PhpSpreadsheet/pull/1500)) +- Fix for Issue [#1533](https://github.com/PHPOffice/PhpSpreadsheet/issues/1533) (A reference to a cell containing a string starting with "#" leads to errors in the generated xlsx.) [#1534](https://github.com/PHPOffice/PhpSpreadsheet/pull/1534) +- Xls Writer - Correct Timestamp Bug [#1493](https://github.com/PHPOffice/PhpSpreadsheet/pull/1493) +- Don't ouput row and columns without any cells in HTML writer [#1235](https://github.com/PHPOffice/PhpSpreadsheet/issues/1235) + +## 1.13.0 - 2020-05-31 + +### Added + +- Support writing to streams in all writers [#1292](https://github.com/PHPOffice/PhpSpreadsheet/issues/1292) +- Support CSV files with data wrapping a lot of lines [#1468](https://github.com/PHPOffice/PhpSpreadsheet/pull/1468) +- Support protection of worksheet by a specific hash algorithm [#1485](https://github.com/PHPOffice/PhpSpreadsheet/pull/1485) + +### Fixed + +- Fix Chart samples by updating chart parameter from 0 to DataSeries::EMPTY_AS_GAP [#1448](https://github.com/PHPOffice/PhpSpreadsheet/pull/1448) +- Fix return type in docblock for the Cells::get() [#1398](https://github.com/PHPOffice/PhpSpreadsheet/pull/1398) +- Fix RATE, PRICE, XIRR, and XNPV Functions [#1456](https://github.com/PHPOffice/PhpSpreadsheet/pull/1456) +- Save Excel 2010+ functions properly in XLSX [#1461](https://github.com/PHPOffice/PhpSpreadsheet/pull/1461) +- Several improvements in HTML writer [#1464](https://github.com/PHPOffice/PhpSpreadsheet/pull/1464) +- Fix incorrect behaviour when saving XLSX file with drawings [#1462](https://github.com/PHPOffice/PhpSpreadsheet/pull/1462), +- Fix Crash while trying setting a cell the value "123456\n" [#1476](https://github.com/PHPOffice/PhpSpreadsheet/pull/1481) +- Improved DATEDIF() function and reduced errors for Y and YM units [#1466](https://github.com/PHPOffice/PhpSpreadsheet/pull/1466) +- Stricter typing for mergeCells [#1494](https://github.com/PHPOffice/PhpSpreadsheet/pull/1494) + +### Changed + +- Drop support for PHP 7.1, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support +- Drop partial migration tool in favor of complete migration via RectorPHP [#1445](https://github.com/PHPOffice/PhpSpreadsheet/issues/1445) +- Limit composer package to `src/` [#1424](https://github.com/PHPOffice/PhpSpreadsheet/pull/1424) + +## 1.12.0 - 2020-04-27 + +### Added + +- Improved the ARABIC function to also handle short-hand roman numerals +- Added support for the FLOOR.MATH and FLOOR.PRECISE functions [#1351](https://github.com/PHPOffice/PhpSpreadsheet/pull/1351) + +### Fixed + +- Fix ROUNDUP and ROUNDDOWN for floating-point rounding error [#1404](https://github.com/PHPOffice/PhpSpreadsheet/pull/1404) +- Fix ROUNDUP and ROUNDDOWN for negative number [#1417](https://github.com/PHPOffice/PhpSpreadsheet/pull/1417) +- Fix loading styles from vmlDrawings when containing whitespace [#1347](https://github.com/PHPOffice/PhpSpreadsheet/issues/1347) +- Fix incorrect behavior when removing last row [#1365](https://github.com/PHPOffice/PhpSpreadsheet/pull/1365) +- MATCH with a static array should return the position of the found value based on the values submitted [#1332](https://github.com/PHPOffice/PhpSpreadsheet/pull/1332) +- Fix Xlsx Reader's handling of undefined fill color [#1353](https://github.com/PHPOffice/PhpSpreadsheet/pull/1353) + +## 1.11.0 - 2020-03-02 + +### Added + +- Added support for the BASE function +- Added support for the ARABIC function +- Conditionals - Extend Support for (NOT)CONTAINSBLANKS [#1278](https://github.com/PHPOffice/PhpSpreadsheet/pull/1278) + +### Fixed + +- Handle Error in Formula Processing Better for Xls [#1267](https://github.com/PHPOffice/PhpSpreadsheet/pull/1267) +- Handle ConditionalStyle NumberFormat When Reading Xlsx File [#1296](https://github.com/PHPOffice/PhpSpreadsheet/pull/1296) +- Fix Xlsx Writer's handling of decimal commas [#1282](https://github.com/PHPOffice/PhpSpreadsheet/pull/1282) +- Fix for issue by removing test code mistakenly left in [#1328](https://github.com/PHPOffice/PhpSpreadsheet/pull/1328) +- Fix for Xls writer wrong selected cells and active sheet [#1256](https://github.com/PHPOffice/PhpSpreadsheet/pull/1256) +- Fix active cell when freeze pane is used [#1323](https://github.com/PHPOffice/PhpSpreadsheet/pull/1323) +- Fix XLSX file loading with autofilter containing '$' [#1326](https://github.com/PHPOffice/PhpSpreadsheet/pull/1326) +- PHPDoc - Use `@return $this` for fluent methods [#1362](https://github.com/PHPOffice/PhpSpreadsheet/pull/1362) + +## 1.10.1 - 2019-12-02 + +### Changed + +- PHP 7.4 compatibility + +### Fixed + +- FLOOR() function accept negative number and negative significance [#1245](https://github.com/PHPOffice/PhpSpreadsheet/pull/1245) +- Correct column style even when using rowspan [#1249](https://github.com/PHPOffice/PhpSpreadsheet/pull/1249) +- Do not confuse defined names and cell refs [#1263](https://github.com/PHPOffice/PhpSpreadsheet/pull/1263) +- XLSX reader/writer keep decimal for floats with a zero decimal part [#1262](https://github.com/PHPOffice/PhpSpreadsheet/pull/1262) +- ODS writer prevent invalid numeric value if locale decimal separator is comma [#1268](https://github.com/PHPOffice/PhpSpreadsheet/pull/1268) +- Xlsx writer actually writes plotVisOnly and dispBlanksAs from chart properties [#1266](https://github.com/PHPOffice/PhpSpreadsheet/pull/1266) + +## 1.10.0 - 2019-11-18 + +### Changed + +- Change license from LGPL 2.1 to MIT [#140](https://github.com/PHPOffice/PhpSpreadsheet/issues/140) + +### Added + +- Implementation of IFNA() logical function +- Support "showZeros" worksheet option to change how Excel shows and handles "null" values returned from a calculation +- Allow HTML Reader to accept HTML as a string into an existing spreadsheet [#1212](https://github.com/PHPOffice/PhpSpreadsheet/pull/1212) + +### Fixed + +- IF implementation properly handles the value `#N/A` [#1165](https://github.com/PHPOffice/PhpSpreadsheet/pull/1165) +- Formula Parser: Wrong line count for stuff like "MyOtherSheet!A:D" [#1215](https://github.com/PHPOffice/PhpSpreadsheet/issues/1215) +- Call garbage collector after removing a column to prevent stale cached values +- Trying to remove a column that doesn't exist deletes the latest column +- Keep big integer as integer instead of lossely casting to float [#874](https://github.com/PHPOffice/PhpSpreadsheet/pull/874) +- Fix branch pruning handling of non boolean conditions [#1167](https://github.com/PHPOffice/PhpSpreadsheet/pull/1167) +- Fix ODS Reader when no DC namespace are defined [#1182](https://github.com/PHPOffice/PhpSpreadsheet/pull/1182) +- Fixed Functions->ifCondition for allowing <> and empty condition [#1206](https://github.com/PHPOffice/PhpSpreadsheet/pull/1206) +- Validate XIRR inputs and return correct error values [#1120](https://github.com/PHPOffice/PhpSpreadsheet/issues/1120) +- Allow to read xlsx files with exotic workbook names like "workbook2.xml" [#1183](https://github.com/PHPOffice/PhpSpreadsheet/pull/1183) + +## 1.9.0 - 2019-08-17 + +### Changed + +- Drop support for PHP 5.6 and 7.0, according to https://phpspreadsheet.readthedocs.io/en/latest/#php-version-support + +### Added + +- When <br> appears in a table cell, set the cell to wrap [#1071](https://github.com/PHPOffice/PhpSpreadsheet/issues/1071) and [#1070](https://github.com/PHPOffice/PhpSpreadsheet/pull/1070) +- Add MAXIFS, MINIFS, COUNTIFS and Remove MINIF, MAXIF [#1056](https://github.com/PHPOffice/PhpSpreadsheet/issues/1056) +- HLookup needs an ordered list even if range_lookup is set to false [#1055](https://github.com/PHPOffice/PhpSpreadsheet/issues/1055) and [#1076](https://github.com/PHPOffice/PhpSpreadsheet/pull/1076) +- Improve performance of IF function calls via ranch pruning to avoid resolution of every branches [#844](https://github.com/PHPOffice/PhpSpreadsheet/pull/844) +- MATCH function supports `*?~` Excel functionality, when match_type=0 [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) +- Allow HTML Reader to accept HTML as a string [#1136](https://github.com/PHPOffice/PhpSpreadsheet/pull/1136) + +### Fixed + +- Fix to AVERAGEIF() function when called with a third argument +- Eliminate duplicate fill none style entries [#1066](https://github.com/PHPOffice/PhpSpreadsheet/issues/1066) +- Fix number format masks containing literal (non-decimal point) dots [#1079](https://github.com/PHPOffice/PhpSpreadsheet/issues/1079) +- Fix number format masks containing named colours that were being misinterpreted as date formats; and add support for masks that fully replace the value with a full text string [#1009](https://github.com/PHPOffice/PhpSpreadsheet/issues/1009) +- Stricter-typed comparison testing in COUNTIF() and COUNTIFS() evaluation [#1046](https://github.com/PHPOffice/PhpSpreadsheet/issues/1046) +- COUPNUM should not return zero when settlement is in the last period [#1020](https://github.com/PHPOffice/PhpSpreadsheet/issues/1020) and [#1021](https://github.com/PHPOffice/PhpSpreadsheet/pull/1021) +- Fix handling of named ranges referencing sheets with spaces or "!" in their title +- Cover `getSheetByName()` with tests for name with quote and spaces [#739](https://github.com/PHPOffice/PhpSpreadsheet/issues/739) +- Best effort to support invalid colspan values in HTML reader - [#878](https://github.com/PHPOffice/PhpSpreadsheet/pull/878) +- Fixes incorrect rows deletion [#868](https://github.com/PHPOffice/PhpSpreadsheet/issues/868) +- MATCH function fix (value search by type, stop search when match_type=-1 and unordered element encountered) [#1116](https://github.com/PHPOffice/PhpSpreadsheet/issues/1116) +- Fix `getCalculatedValue()` error with more than two INDIRECT [#1115](https://github.com/PHPOffice/PhpSpreadsheet/pull/1115) +- Writer\Html did not hide columns [#985](https://github.com/PHPOffice/PhpSpreadsheet/pull/985) + +## 1.8.2 - 2019-07-08 + +### Fixed + +- Uncaught error when opening ods file and properties aren't defined [#1047](https://github.com/PHPOffice/PhpSpreadsheet/issues/1047) +- Xlsx Reader Cell datavalidations bug [#1052](https://github.com/PHPOffice/PhpSpreadsheet/pull/1052) + +## 1.8.1 - 2019-07-02 + +### Fixed + +- Allow nullable theme for Xlsx Style Reader class [#1043](https://github.com/PHPOffice/PhpSpreadsheet/issues/1043) + +## 1.8.0 - 2019-07-01 + +### Security Fix (CVE-2019-12331) + +- Detect double-encoded xml in the Security scanner, and reject as suspicious. +- This change also broadens the scope of the `libxml_disable_entity_loader` setting when reading XML-based formats, so that it is enabled while the xml is being parsed and not simply while it is loaded. + On some versions of PHP, this can cause problems because it is not thread-safe, and can affect other PHP scripts running on the same server. This flag is set to true when instantiating a loader, and back to its original setting when the Reader is no longer in scope, or manually unset. +- Provide a check to identify whether libxml_disable_entity_loader is thread-safe or not. + + `XmlScanner::threadSafeLibxmlDisableEntityLoaderAvailability()` +- Provide an option to disable the libxml_disable_entity_loader call through settings. This is not recommended as it reduces the security of the XML-based readers, and should only be used if you understand the consequences and have no other choice. + +### Added + +- Added support for the SWITCH function [#963](https://github.com/PHPOffice/PhpSpreadsheet/issues/963) and [#983](https://github.com/PHPOffice/PhpSpreadsheet/pull/983) +- Add accounting number format style [#974](https://github.com/PHPOffice/PhpSpreadsheet/pull/974) + +### Fixed + +- Whitelist `tsv` extension when opening CSV files [#429](https://github.com/PHPOffice/PhpSpreadsheet/issues/429) +- Fix a SUMIF warning with some versions of PHP when having different length of arrays provided as input [#873](https://github.com/PHPOffice/PhpSpreadsheet/pull/873) +- Fix incorrectly handled backslash-escaped space characters in number format + +## 1.7.0 - 2019-05-26 + +- Added support for inline styles in Html reader (borders, alignment, width, height) +- QuotedText cells no longer treated as formulae if the content begins with a `=` +- Clean handling for DDE in formulae + +### Fixed + +- Fix handling for escaped enclosures and new lines in CSV Separator Inference +- Fix MATCH an error was appearing when comparing strings against 0 (always true) +- Fix wrong calculation of highest column with specified row [#700](https://github.com/PHPOffice/PhpSpreadsheet/issues/700) +- Fix VLOOKUP +- Fix return type hint + +## 1.6.0 - 2019-01-02 + +### Added + +- Refactored Matrix Functions to use external Matrix library +- Possibility to specify custom colors of values for pie and donut charts [#768](https://github.com/PHPOffice/PhpSpreadsheet/pull/768) + +### Fixed + +- Improve XLSX parsing speed if no readFilter is applied [#772](https://github.com/PHPOffice/PhpSpreadsheet/issues/772) +- Fix column names if read filter calls in XLSX reader skip columns [#777](https://github.com/PHPOffice/PhpSpreadsheet/pull/777) +- XLSX reader can now ignore blank cells, using the setReadEmptyCells(false) method. [#810](https://github.com/PHPOffice/PhpSpreadsheet/issues/810) +- Fix LOOKUP function which was breaking on edge cases [#796](https://github.com/PHPOffice/PhpSpreadsheet/issues/796) +- Fix VLOOKUP with exact matches [#809](https://github.com/PHPOffice/PhpSpreadsheet/pull/809) +- Support COUNTIFS multiple arguments [#830](https://github.com/PHPOffice/PhpSpreadsheet/pull/830) +- Change `libxml_disable_entity_loader()` as shortly as possible [#819](https://github.com/PHPOffice/PhpSpreadsheet/pull/819) +- Improved memory usage and performance when loading large spreadsheets [#822](https://github.com/PHPOffice/PhpSpreadsheet/pull/822) +- Improved performance when loading large spreadsheets [#825](https://github.com/PHPOffice/PhpSpreadsheet/pull/825) +- Improved performance when loading large spreadsheets [#824](https://github.com/PHPOffice/PhpSpreadsheet/pull/824) +- Fix color from CSS when reading from HTML [#831](https://github.com/PHPOffice/PhpSpreadsheet/pull/831) +- Fix infinite loop when reading invalid ODS files [#832](https://github.com/PHPOffice/PhpSpreadsheet/pull/832) +- Fix time format for duration is incorrect [#666](https://github.com/PHPOffice/PhpSpreadsheet/pull/666) +- Fix iconv unsupported `//IGNORE//TRANSLIT` on IBM i [#791](https://github.com/PHPOffice/PhpSpreadsheet/issues/791) + +### Changed + +- `master` is the new default branch, `develop` does not exist anymore + +## 1.5.2 - 2018-11-25 + +### Security + +- Improvements to the design of the XML Security Scanner [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) + +## 1.5.1 - 2018-11-20 + +### Security + +- Fix and improve XXE security scanning for XML-based and HTML Readers [#771](https://github.com/PHPOffice/PhpSpreadsheet/issues/771) + +### Added + +- Support page margin in mPDF [#750](https://github.com/PHPOffice/PhpSpreadsheet/issues/750) + +### Fixed + +- Support numeric condition in SUMIF, SUMIFS, AVERAGEIF, COUNTIF, MAXIF and MINIF [#683](https://github.com/PHPOffice/PhpSpreadsheet/issues/683) +- SUMIFS containing multiple conditions [#704](https://github.com/PHPOffice/PhpSpreadsheet/issues/704) +- Csv reader avoid notice when the file is empty [#743](https://github.com/PHPOffice/PhpSpreadsheet/pull/743) +- Fix print area parser for XLSX reader [#734](https://github.com/PHPOffice/PhpSpreadsheet/pull/734) +- Support overriding `DefaultValueBinder::dataTypeForValue()` without overriding `DefaultValueBinder::bindValue()` [#735](https://github.com/PHPOffice/PhpSpreadsheet/pull/735) +- Mpdf export can exceed pcre.backtrack_limit [#637](https://github.com/PHPOffice/PhpSpreadsheet/issues/637) +- Fix index overflow on data values array [#748](https://github.com/PHPOffice/PhpSpreadsheet/pull/748) + +## 1.5.0 - 2018-10-21 + +### Added + +- PHP 7.3 support +- Add the DAYS() function [#594](https://github.com/PHPOffice/PhpSpreadsheet/pull/594) + +### Fixed + +- Sheet title can contain exclamation mark [#325](https://github.com/PHPOffice/PhpSpreadsheet/issues/325) +- Xls file cause the exception during open by Xls reader [#402](https://github.com/PHPOffice/PhpSpreadsheet/issues/402) +- Skip non numeric value in SUMIF [#618](https://github.com/PHPOffice/PhpSpreadsheet/pull/618) +- OFFSET should allow omitted height and width [#561](https://github.com/PHPOffice/PhpSpreadsheet/issues/561) +- Correctly determine delimiter when CSV contains line breaks inside enclosures [#716](https://github.com/PHPOffice/PhpSpreadsheet/issues/716) + +## 1.4.1 - 2018-09-30 + +### Fixed + +- Remove locale from formatting string [#644](https://github.com/PHPOffice/PhpSpreadsheet/pull/644) +- Allow iterators to go out of bounds with prev [#587](https://github.com/PHPOffice/PhpSpreadsheet/issues/587) +- Fix warning when reading xlsx without styles [#631](https://github.com/PHPOffice/PhpSpreadsheet/pull/631) +- Fix broken sample links on windows due to $baseDir having backslash [#653](https://github.com/PHPOffice/PhpSpreadsheet/pull/653) + +## 1.4.0 - 2018-08-06 + +### Added + +- Add excel function EXACT(value1, value2) support [#595](https://github.com/PHPOffice/PhpSpreadsheet/pull/595) +- Support workbook view attributes for Xlsx format [#523](https://github.com/PHPOffice/PhpSpreadsheet/issues/523) +- Read and write hyperlink for drawing image [#490](https://github.com/PHPOffice/PhpSpreadsheet/pull/490) +- Added calculation engine support for the new bitwise functions that were added in MS Excel 2013 + - BITAND() Returns a Bitwise 'And' of two numbers + - BITOR() Returns a Bitwise 'Or' of two number + - BITXOR() Returns a Bitwise 'Exclusive Or' of two numbers + - BITLSHIFT() Returns a number shifted left by a specified number of bits + - BITRSHIFT() Returns a number shifted right by a specified number of bits +- Added calculation engine support for other new functions that were added in MS Excel 2013 and MS Excel 2016 + - Text Functions + - CONCAT() Synonym for CONCATENATE() + - NUMBERVALUE() Converts text to a number, in a locale-independent way + - UNICHAR() Synonym for CHAR() in PHPSpreadsheet, which has always used UTF-8 internally + - UNIORD() Synonym for ORD() in PHPSpreadsheet, which has always used UTF-8 internally + - TEXTJOIN() Joins together two or more text strings, separated by a delimiter + - Logical Functions + - XOR() Returns a logical Exclusive Or of all arguments + - Date/Time Functions + - ISOWEEKNUM() Returns the ISO 8601 week number of the year for a given date + - Lookup and Reference Functions + - FORMULATEXT() Returns a formula as a string + - Financial Functions + - PDURATION() Calculates the number of periods required for an investment to reach a specified value + - RRI() Calculates the interest rate required for an investment to grow to a specified future value + - Engineering Functions + - ERF.PRECISE() Returns the error function integrated between 0 and a supplied limit + - ERFC.PRECISE() Synonym for ERFC + - Math and Trig Functions + - SEC() Returns the secant of an angle + - SECH() Returns the hyperbolic secant of an angle + - CSC() Returns the cosecant of an angle + - CSCH() Returns the hyperbolic cosecant of an angle + - COT() Returns the cotangent of an angle + - COTH() Returns the hyperbolic cotangent of an angle + - ACOT() Returns the cotangent of an angle + - ACOTH() Returns the hyperbolic cotangent of an angle +- Refactored Complex Engineering Functions to use external complex number library +- Added calculation engine support for the new complex number functions that were added in MS Excel 2013 + - IMCOSH() Returns the hyperbolic cosine of a complex number + - IMCOT() Returns the cotangent of a complex number + - IMCSC() Returns the cosecant of a complex number + - IMCSCH() Returns the hyperbolic cosecant of a complex number + - IMSEC() Returns the secant of a complex number + - IMSECH() Returns the hyperbolic secant of a complex number + - IMSINH() Returns the hyperbolic sine of a complex number + - IMTAN() Returns the tangent of a complex number + +### Fixed + +- Fix ISFORMULA() function to work with a cell reference to another worksheet +- Xlsx reader crashed when reading a file with workbook protection [#553](https://github.com/PHPOffice/PhpSpreadsheet/pull/553) +- Cell formats with escaped spaces were causing incorrect date formatting [#557](https://github.com/PHPOffice/PhpSpreadsheet/issues/557) +- Could not open CSV file containing HTML fragment [#564](https://github.com/PHPOffice/PhpSpreadsheet/issues/564) +- Exclude the vendor folder in migration [#481](https://github.com/PHPOffice/PhpSpreadsheet/issues/481) +- Chained operations on cell ranges involving borders operated on last cell only [#428](https://github.com/PHPOffice/PhpSpreadsheet/issues/428) +- Avoid memory exhaustion when cloning worksheet with a drawing [#437](https://github.com/PHPOffice/PhpSpreadsheet/issues/437) +- Migration tool keep variables containing $PHPExcel untouched [#598](https://github.com/PHPOffice/PhpSpreadsheet/issues/598) +- Rowspans/colspans were incorrect when adding worksheet using loadIntoExisting [#619](https://github.com/PHPOffice/PhpSpreadsheet/issues/619) + +## 1.3.1 - 2018-06-12 + +### Fixed + +- Ranges across Z and AA columns incorrectly threw an exception [#545](https://github.com/PHPOffice/PhpSpreadsheet/issues/545) + +## 1.3.0 - 2018-06-10 + +### Added + +- Support to read Xlsm templates with form elements, macros, printer settings, protected elements and back compatibility drawing, and save result without losing important elements of document [#435](https://github.com/PHPOffice/PhpSpreadsheet/issues/435) +- Expose sheet title maximum length as `Worksheet::SHEET_TITLE_MAXIMUM_LENGTH` [#482](https://github.com/PHPOffice/PhpSpreadsheet/issues/482) +- Allow escape character to be set in CSV reader [#492](https://github.com/PHPOffice/PhpSpreadsheet/issues/492) + +### Fixed + +- Subtotal 9 in a group that has other subtotals 9 exclude the totals of the other subtotals in the range [#332](https://github.com/PHPOffice/PhpSpreadsheet/issues/332) +- `Helper\Html` support UTF-8 HTML input [#444](https://github.com/PHPOffice/PhpSpreadsheet/issues/444) +- Xlsx loaded an extra empty comment for each real comment [#375](https://github.com/PHPOffice/PhpSpreadsheet/issues/375) +- Xlsx reader do not read rows and columns filtered out in readFilter at all [#370](https://github.com/PHPOffice/PhpSpreadsheet/issues/370) +- Make newer Excel versions properly recalculate formulas on document open [#456](https://github.com/PHPOffice/PhpSpreadsheet/issues/456) +- `Coordinate::extractAllCellReferencesInRange()` throws an exception for an invalid range [#519](https://github.com/PHPOffice/PhpSpreadsheet/issues/519) +- Fixed parsing of conditionals in COUNTIF functions [#526](https://github.com/PHPOffice/PhpSpreadsheet/issues/526) +- Corruption errors for saved Xlsx docs with frozen panes [#532](https://github.com/PHPOffice/PhpSpreadsheet/issues/532) + +## 1.2.1 - 2018-04-10 + +### Fixed + +- Plain text and richtext mixed in same cell can be read [#442](https://github.com/PHPOffice/PhpSpreadsheet/issues/442) + +## 1.2.0 - 2018-03-04 + +### Added + +- HTML writer creates a generator meta tag [#312](https://github.com/PHPOffice/PhpSpreadsheet/issues/312) +- Support invalid zoom value in XLSX format [#350](https://github.com/PHPOffice/PhpSpreadsheet/pull/350) +- Support for `_xlfn.` prefixed functions and `ISFORMULA`, `MODE.SNGL`, `STDEV.S`, `STDEV.P` [#390](https://github.com/PHPOffice/PhpSpreadsheet/pull/390) + +### Fixed + +- Avoid potentially unsupported PSR-16 cache keys [#354](https://github.com/PHPOffice/PhpSpreadsheet/issues/354) +- Check for MIME type to know if CSV reader can read a file [#167](https://github.com/PHPOffice/PhpSpreadsheet/issues/167) +- Use proper € symbol for currency format [#379](https://github.com/PHPOffice/PhpSpreadsheet/pull/379) +- Read printing area correctly when skipping some sheets [#371](https://github.com/PHPOffice/PhpSpreadsheet/issues/371) +- Avoid incorrectly overwriting calculated value type [#394](https://github.com/PHPOffice/PhpSpreadsheet/issues/394) +- Select correct cell when calling freezePane [#389](https://github.com/PHPOffice/PhpSpreadsheet/issues/389) +- `setStrikethrough()` did not set the font [#403](https://github.com/PHPOffice/PhpSpreadsheet/issues/403) + +## 1.1.0 - 2018-01-28 + +### Added + +- Support for PHP 7.2 +- Support cell comments in HTML writer and reader [#308](https://github.com/PHPOffice/PhpSpreadsheet/issues/308) +- Option to stop at a conditional styling, if it matches (only XLSX format) [#292](https://github.com/PHPOffice/PhpSpreadsheet/pull/292) +- Support for line width for data series when rendering Xlsx [#329](https://github.com/PHPOffice/PhpSpreadsheet/pull/329) + +### Fixed + +- Better auto-detection of CSV separators [#305](https://github.com/PHPOffice/PhpSpreadsheet/issues/305) +- Support for shape style ending with `;` [#304](https://github.com/PHPOffice/PhpSpreadsheet/issues/304) +- Freeze Panes takes wrong coordinates for XLSX [#322](https://github.com/PHPOffice/PhpSpreadsheet/issues/322) +- `COLUMNS` and `ROWS` functions crashed in some cases [#336](https://github.com/PHPOffice/PhpSpreadsheet/issues/336) +- Support XML file without styles [#331](https://github.com/PHPOffice/PhpSpreadsheet/pull/331) +- Cell coordinates which are already a range cause an exception [#319](https://github.com/PHPOffice/PhpSpreadsheet/issues/319) + +## 1.0.0 - 2017-12-25 + +### Added + +- Support to write merged cells in ODS format [#287](https://github.com/PHPOffice/PhpSpreadsheet/issues/287) +- Able to set the `topLeftCell` in freeze panes [#261](https://github.com/PHPOffice/PhpSpreadsheet/pull/261) +- Support `DateTimeImmutable` as cell value +- Support migration of prefixed classes + +### Fixed + +- Can read very small HTML files [#194](https://github.com/PHPOffice/PhpSpreadsheet/issues/194) +- Written DataValidation was corrupted [#290](https://github.com/PHPOffice/PhpSpreadsheet/issues/290) +- Date format compatible with both LibreOffice and Excel [#298](https://github.com/PHPOffice/PhpSpreadsheet/issues/298) + +### BREAKING CHANGE + +- Constant `TYPE_DOUGHTNUTCHART` is now `TYPE_DOUGHNUTCHART`. + +## 1.0.0-beta2 - 2017-11-26 + +### Added + +- Support for chart fill color - @CrazyBite [#158](https://github.com/PHPOffice/PhpSpreadsheet/pull/158) +- Support for read Hyperlink for xml - @GreatHumorist [#223](https://github.com/PHPOffice/PhpSpreadsheet/pull/223) +- Support for cell value validation according to data validation rules - @SailorMax [#257](https://github.com/PHPOffice/PhpSpreadsheet/pull/257) +- Support for custom implementation, or configuration, of PDF libraries - @SailorMax [#266](https://github.com/PHPOffice/PhpSpreadsheet/pull/266) + +### Changed + +- Merge data-validations to reduce written worksheet size - @billblume [#131](https://github.com/PHPOffice/PhpSpreadSheet/issues/131) +- Throws exception if a XML file is invalid - @GreatHumorist [#222](https://github.com/PHPOffice/PhpSpreadsheet/pull/222) +- Upgrade to mPDF 7.0+ [#144](https://github.com/PHPOffice/PhpSpreadsheet/issues/144) + +### Fixed + +- Control characters in cell values are automatically escaped [#212](https://github.com/PHPOffice/PhpSpreadsheet/issues/212) +- Prevent color changing when copy/pasting xls files written by PhpSpreadsheet to another file - @al-lala [#218](https://github.com/PHPOffice/PhpSpreadsheet/issues/218) +- Add cell reference automatic when there is no cell reference('r' attribute) in Xlsx file. - @GreatHumorist [#225](https://github.com/PHPOffice/PhpSpreadsheet/pull/225) Refer to [#201](https://github.com/PHPOffice/PhpSpreadsheet/issues/201) +- `Reader\Xlsx::getFromZipArchive()` function return false if the zip entry could not be located. - @anton-harvey [#268](https://github.com/PHPOffice/PhpSpreadsheet/pull/268) + +### BREAKING CHANGE + +- Extracted coordinate method to dedicate class [migration guide](./docs/topics/migration-from-PHPExcel.md). +- Column indexes are based on 1, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). +- Standardization of array keys used for style, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). +- Easier usage of PDF writers, and other custom readers and writers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). +- Easier usage of chart renderers, see the [migration guide](./docs/topics/migration-from-PHPExcel.md). +- Rename a few more classes to keep them in their related namespaces: + - `CalcEngine` => `Calculation\Engine` + - `PhpSpreadsheet\Calculation` => `PhpSpreadsheet\Calculation\Calculation` + - `PhpSpreadsheet\Cell` => `PhpSpreadsheet\Cell\Cell` + - `PhpSpreadsheet\Chart` => `PhpSpreadsheet\Chart\Chart` + - `PhpSpreadsheet\RichText` => `PhpSpreadsheet\RichText\RichText` + - `PhpSpreadsheet\Style` => `PhpSpreadsheet\Style\Style` + - `PhpSpreadsheet\Worksheet` => `PhpSpreadsheet\Worksheet\Worksheet` + +## 1.0.0-beta - 2017-08-17 + +### Added + +- Initial implementation of SUMIFS() function +- Additional codepages +- MemoryDrawing not working in HTML writer [#808](https://github.com/PHPOffice/PHPExcel/issues/808) +- CSV Reader can auto-detect the separator used in file [#141](https://github.com/PHPOffice/PhpSpreadsheet/pull/141) +- HTML Reader supports some basic inline styles [#180](https://github.com/PHPOffice/PhpSpreadsheet/pull/180) + +### Changed + +- Start following [SemVer](https://semver.org) properly. + +### Fixed + +- Fix to getCell() method when cell reference includes a worksheet reference - @MarkBaker +- Ignore inlineStr type if formula element exists - @ncrypthic [#570](https://github.com/PHPOffice/PHPExcel/issues/570) +- Excel 2007 Reader freezes because of conditional formatting - @rentalhost [#575](https://github.com/PHPOffice/PHPExcel/issues/575) +- Readers will now parse files containing worksheet titles over 31 characters [#176](https://github.com/PHPOffice/PhpSpreadsheet/pull/176) +- Fixed PHP8 deprecation warning for libxml_disable_entity_loader() [#1625](https://github.com/phpoffice/phpspreadsheet/pull/1625) + +### General + +- Whitespace after toRichTextObject() - @MarkBaker [#554](https://github.com/PHPOffice/PHPExcel/issues/554) +- Optimize vlookup() sort - @umpirsky [#548](https://github.com/PHPOffice/PHPExcel/issues/548) +- c:max and c:min elements shall NOT be inside c:orientation elements - @vitalyrepin [#869](https://github.com/PHPOffice/PHPExcel/pull/869) +- Implement actual timezone adjustment into PHPExcel_Shared_Date::PHPToExcel - @sim642 [#489](https://github.com/PHPOffice/PHPExcel/pull/489) + +### BREAKING CHANGE + +- Introduction of namespaces for all classes, eg: `PHPExcel_Calculation_Functions` becomes `PhpOffice\PhpSpreadsheet\Calculation\Functions` +- Some classes were renamed for clarity and/or consistency: + +For a comprehensive list of all class changes, and a semi-automated migration path, read the [migration guide](./docs/topics/migration-from-PHPExcel.md). + +- Dropped `PHPExcel_Calculation_Functions::VERSION()`. Composer or git should be used to know the version. +- Dropped `PHPExcel_Settings::setPdfRenderer()` and `PHPExcel_Settings::setPdfRenderer()`. Composer should be used to autoload PDF libs. +- Dropped support for HHVM + +## Previous versions of PHPExcel + +The changelog for the project when it was called PHPExcel is [still available](./CHANGELOG.PHPExcel.md). diff --git a/lib/phpoffice/phpspreadsheet/CONTRIBUTING.md b/lib/phpoffice/phpspreadsheet/CONTRIBUTING.md new file mode 100644 index 00000000..f5953533 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/CONTRIBUTING.md @@ -0,0 +1,20 @@ +# Want to contribute? + +If you would like to contribute, here are some notes and guidelines: + + - All new development happens on feature/fix branches, and are then merged to the `master` branch once stable; so the `master` branch is always the most up-to-date, working code + - Tagged releases are made from the `master` branch + - If you are going to be submitting a pull request, please fork from `master`, and submit your pull request back as a fix/feature branch referencing the GitHub issue number + - Code style might be automatically fixed by `composer fix` + - All code changes must be validated by `composer check` + - [Helpful article about forking](https://help.github.com/articles/fork-a-repo/ "Forking a GitHub repository") + - [Helpful article about pull requests](https://help.github.com/articles/using-pull-requests/ "Pull Requests") + +## How to release + +1. Complete CHANGELOG.md and commit +2. Create an annotated tag + 1. `git tag -a 1.2.3` + 2. Tag subject must be the version number, eg: `1.2.3` + 3. Tag body must be a copy-paste of the changelog entries +3. Push tag with `git push --tags`, GitHub Actions will create a GitHub release automatically diff --git a/lib/phpoffice/phpspreadsheet/README.md b/lib/phpoffice/phpspreadsheet/README.md new file mode 100644 index 00000000..2a94e0d3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/README.md @@ -0,0 +1,30 @@ +# PhpSpreadsheet + +[![Build Status](https://github.com/PHPOffice/PhpSpreadsheet/workflows/main/badge.svg)](https://github.com/PHPOffice/PhpSpreadsheet/actions) +[![Code Quality](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) +[![Code Coverage](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/PHPOffice/PhpSpreadsheet/?branch=master) +[![Total Downloads](https://img.shields.io/packagist/dt/PHPOffice/PhpSpreadsheet)](https://packagist.org/packages/phpoffice/phpspreadsheet) +[![Latest Stable Version](https://img.shields.io/github/v/release/PHPOffice/PhpSpreadsheet)](https://packagist.org/packages/phpoffice/phpspreadsheet) +[![License](https://img.shields.io/github/license/PHPOffice/PhpSpreadsheet)](https://packagist.org/packages/phpoffice/phpspreadsheet) +[![Join the chat at https://gitter.im/PHPOffice/PhpSpreadsheet](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/PHPOffice/PhpSpreadsheet) + +PhpSpreadsheet is a library written in pure PHP and offers a set of classes that +allow you to read and write various spreadsheet file formats such as Excel and LibreOffice Calc. + +## Documentation + +Read more about it, including install instructions, in the [official documentation](https://phpspreadsheet.readthedocs.io). Or check out the [API documentation](https://phpoffice.github.io/PhpSpreadsheet). + +Please ask your support questions on [StackOverflow](https://stackoverflow.com/questions/tagged/phpspreadsheet), or have a quick chat on [Gitter](https://gitter.im/PHPOffice/PhpSpreadsheet). + +## PHPExcel vs PhpSpreadsheet ? + +PhpSpreadsheet is the next version of PHPExcel. It breaks compatibility to dramatically improve the code base quality (namespaces, PSR compliance, use of latest PHP language features, etc.). + +Because all efforts have shifted to PhpSpreadsheet, PHPExcel will no longer be maintained. All contributions for PHPExcel, patches and new features, should target PhpSpreadsheet `master` branch. + +Do you need to migrate? There is [an automated tool](/docs/topics/migration-from-PHPExcel.md) for that. + +## License + +PhpSpreadsheet is licensed under [MIT](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/LICENSE). diff --git a/lib/phpoffice/phpspreadsheet/composer.json b/lib/phpoffice/phpspreadsheet/composer.json index cfff1cb1..a0064df2 100644 --- a/lib/phpoffice/phpspreadsheet/composer.json +++ b/lib/phpoffice/phpspreadsheet/composer.json @@ -1,7 +1,22 @@ { "name": "phpoffice/phpspreadsheet", "description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine", - "keywords": ["PHP", "OpenXML", "Excel", "xlsx", "xls", "ods", "gnumeric", "spreadsheet"], + "keywords": [ + "PHP", + "OpenXML", + "Excel", + "xlsx", + "xls", + "ods", + "gnumeric", + "spreadsheet" + ], + "config": { + "sort-packages": true, + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + }, "homepage": "https://github.com/PHPOffice/PhpSpreadsheet", "type": "library", "license": "MIT", @@ -28,49 +43,57 @@ "scripts": { "check": [ "php-cs-fixer fix --ansi --dry-run --diff", - "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PSR2 -n", - "phpunit --color=always" + "phpcs", + "phpunit --color=always", + "phpstan analyse --ansi" ], "fix": [ "php-cs-fixer fix --ansi" ], "versions": [ - "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.1- -n" + "phpcs --report-width=200 samples/ src/ tests/ --ignore=samples/Header.php --standard=PHPCompatibility --runtime-set testVersion 7.3- -n" ] }, "require": { - "php": "^7.1", + "php": "^7.3 || ^8.0", "ext-ctype": "*", "ext-dom": "*", + "ext-fileinfo": "*", "ext-gd": "*", "ext-iconv": "*", - "ext-fileinfo": "*", "ext-libxml": "*", "ext-mbstring": "*", - "ext-SimpleXML": "*", + "ext-simplexml": "*", "ext-xml": "*", "ext-xmlreader": "*", "ext-xmlwriter": "*", "ext-zip": "*", "ext-zlib": "*", - "markbaker/complex": "^1.4", - "markbaker/matrix": "^1.2", - "psr/simple-cache": "^1.0" + "ezyang/htmlpurifier": "^4.13", + "maennchen/zipstream-php": "^2.1", + "markbaker/complex": "^3.0", + "markbaker/matrix": "^3.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0", + "psr/simple-cache": "^1.0 || ^2.0" }, "require-dev": { - "dompdf/dompdf": "^0.8.3", - "friendsofphp/php-cs-fixer": "^2.16", + "dealerdirect/phpcodesniffer-composer-installer": "dev-master", + "dompdf/dompdf": "^1.0", + "friendsofphp/php-cs-fixer": "^3.2", "jpgraph/jpgraph": "^4.0", - "mpdf/mpdf": "^8.0", + "mpdf/mpdf": "8.0.17", "phpcompatibility/php-compatibility": "^9.3", - "phpunit/phpunit": "^7.5", - "squizlabs/php_codesniffer": "^3.5", - "tecnickcom/tcpdf": "^6.3" + "phpstan/phpstan": "^1.1", + "phpstan/phpstan-phpunit": "^1.0", + "phpunit/phpunit": "^8.5 || ^9.0", + "squizlabs/php_codesniffer": "^3.6", + "tecnickcom/tcpdf": "^6.4" }, "suggest": { "mpdf/mpdf": "Option for rendering PDF with PDF Writer", - "dompdf/dompdf": "Option for rendering PDF with PDF Writer", - "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer", + "dompdf/dompdf": "Option for rendering PDF with PDF Writer (doesn't yet support PHP8)", + "tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer (doesn't yet support PHP8)", "jpgraph/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers" }, "autoload": { @@ -80,7 +103,8 @@ }, "autoload-dev": { "psr-4": { - "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests" + "PhpOffice\\PhpSpreadsheetTests\\": "tests/PhpSpreadsheetTests", + "PhpOffice\\PhpSpreadsheetInfra\\": "infra" } } } diff --git a/lib/phpoffice/phpspreadsheet/phpstan-baseline.neon b/lib/phpoffice/phpspreadsheet/phpstan-baseline.neon new file mode 100644 index 00000000..bdbbf4a8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/phpstan-baseline.neon @@ -0,0 +1,5397 @@ +parameters: + ignoreErrors: + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method attach\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method cellExists\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getCell\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 6 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getColumn\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getCoordinate\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getHighestColumn\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getHighestRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method getTitle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Cannot call method has\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToEnglish\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToEnglish\\(\\) has parameter \\$formula with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToLocale\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:_translateFormulaToLocale\\(\\) has parameter \\$formula with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:dataTestReference\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:dataTestReference\\(\\) has parameter \\$operandData with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:getTokensAsString\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:getTokensAsString\\(\\) has parameter \\$tokens with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:localeFunc\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:localeFunc\\(\\) has parameter \\$function with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has parameter \\$operand with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:validateBinaryOperand\\(\\) has parameter \\$stack with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Offset 'type' does not exist on array\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Offset 'value' does not exist on array\\|null\\.$#" + count: 5 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$haystack of function stripos expects string, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$parent of method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:attach\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells, PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#1 \\$str of function preg_quote expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#2 \\$worksheet of static method PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:resolveName\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Parameter \\#3 \\$formula of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:translateSeparator\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$cellStack has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$comparisonOperators has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$controlFunctions has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$cyclicFormulaCell has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceFromExcel has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceFromLocale has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceToExcel has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$functionReplaceToLocale has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$localeFunctions has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$operatorAssociativity has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$operatorPrecedence has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$phpSpreadsheetFunctions has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$returnArrayAsType has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$spreadsheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Static property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\:\\:\\$instance \\(PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Calculation\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Strict comparison using \\=\\=\\= between array and '\\(' will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Strict comparison using \\=\\=\\= between non\\-empty\\-array and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Calculation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DMAX\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DMIN\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DPRODUCT\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSTDEV\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSTDEVP\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DSUM\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DVAR\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\:\\:DVARP\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Parameter \\#2 \\$field of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DCountA\\:\\:evaluate\\(\\) expects int\\|string, int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:buildCondition\\(\\) has parameter \\$criterion with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$criteria with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$database with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:evaluate\\(\\) has parameter \\$field with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Database\\\\DatabaseAbstract\\:\\:processCondition\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Database/DatabaseAbstract.php + + - + message: "#^Variable \\$dateValue on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php + + - + message: "#^Variable \\$timeValue on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BesselJ\\:\\:besselj2a\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\BesselJ\\:\\:besselj2b\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertBase\\:\\:validatePlaces\\(\\) has parameter \\$places with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertBase\\:\\:validateValue\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertUOM\\:\\:getUOMDetails\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ConvertUOM\\:\\:resolveTemperatureSynonyms\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:erfValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:erfValue\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\Erf\\:\\:\\$twoSqrtPi has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/Erf.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:erfcValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:erfcValue\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Engineering\\\\ErfC\\:\\:\\$oneSqrtPi has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Engineering/ErfC.php + + - + message: "#^Parameter \\#1 \\$callback of function set_error_handler expects \\(callable\\(int, string, string, int, array\\)\\: bool\\)\\|null, array\\{'PhpOffice\\\\\\\\PhpSpreadsheet\\\\\\\\Calculation\\\\\\\\Exception', 'errorHandlerCallback'\\} given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/ExceptionHandler.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:ISPMT\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:ISPMT\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\:\\:NPV\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial.php + + - + message: "#^Parameter \\#1 \\$year of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\DateTimeExcel\\\\Helpers\\:\\:isLeapYear\\(\\) expects int\\|string, array\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Amortization.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$futureValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$numberOfPeriods with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$payment with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$presentValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$rate with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:rateNextGuess\\(\\) has parameter \\$type with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\Interest\\:\\:schedulePayment\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php + + - + message: "#^Binary operation \"\\-\" between float\\|string and 0\\|float results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\InterestAndPrincipal\\:\\:\\$interest has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Constant\\\\Periodic\\\\InterestAndPrincipal\\:\\:\\$principal has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Variable\\\\NonPeriodic\\:\\:xnpvOrdered\\(\\) should return float\\|string but returns array\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\CashFlow\\\\Variable\\\\Periodic\\:\\:presentValue\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php + + - + message: "#^Parameter \\#1 \\$year of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Helpers\\:\\:daysPerYear\\(\\) expects int\\|string, array\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Coupons.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateCost\\(\\) has parameter \\$cost with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateFactor\\(\\) has parameter \\$factor with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateLife\\(\\) has parameter \\$life with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateMonth\\(\\) has parameter \\$month with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validatePeriod\\(\\) has parameter \\$period with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Depreciation\\:\\:validateSalvage\\(\\) has parameter \\$salvage with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Depreciation.php + + - + message: "#^Binary operation \"/\" between float\\|string and float\\|string results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Securities\\\\Price\\:\\:received\\(\\) should return float\\|string but returns array\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php + + - + message: "#^Parameter \\#1 \\$year of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Helpers\\:\\:daysPerYear\\(\\) expects int\\|string, array\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php + + - + message: "#^Parameter \\#1 \\$year of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Financial\\\\Helpers\\:\\:daysPerYear\\(\\) expects int\\|string, array\\|int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php + + - + message: "#^Cannot call method getTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method getTokenType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 9 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method setTokenSubType\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 5 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Cannot call method setValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken\\|null\\.$#" + count: 5 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\FormulaToken and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/FormulaParser.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:ifCondition\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:ifCondition\\(\\) has parameter \\$condition with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isCellValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isCellValue\\(\\) has parameter \\$idx with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isMatrixValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isMatrixValue\\(\\) has parameter \\$idx with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:isValue\\(\\) has parameter \\$idx with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:operandSpecialHandling\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Functions\\:\\:operandSpecialHandling\\(\\) has parameter \\$operand with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Functions.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Internal\\\\MakeMatrix\\:\\:make\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php + + - + message: "#^Call to function is_string\\(\\) with null will always evaluate to false\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Logical/Operations.php + + - + message: "#^Result of && is always false\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/Logical/Operations.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\:\\:CHOOSE\\(\\) has parameter \\$chooseArgs with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\:\\:OFFSET\\(\\) should return array\\|string but returns array\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Address\\:\\:sheetName\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Address.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has parameter \\$lookupArray with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchFirstValue\\(\\) has parameter \\$lookupValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$keySet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$lookupArray with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchLargestValue\\(\\) has parameter \\$lookupValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has parameter \\$lookupArray with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:matchSmallestValue\\(\\) has parameter \\$lookupValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has parameter \\$lookupArray with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:prepareLookupArray\\(\\) has parameter \\$matchType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateLookupArray\\(\\) has parameter \\$lookupArray with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateLookupValue\\(\\) has parameter \\$lookupValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\ExcelMatch\\:\\:validateMatchType\\(\\) has parameter \\$matchType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Lookup\\:\\:verifyResultVector\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Lookup\\:\\:verifyResultVector\\(\\) has parameter \\$resultVector with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\LookupBase\\:\\:validateIndexLookup\\(\\) has parameter \\$index_number with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Matrix\\:\\:extractRowValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has parameter \\$columns with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adjustEndCellColumnForWidth\\(\\) has parameter \\$width with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$endCellRow with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$height with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:adustEndCellRowForHeight\\(\\) has parameter \\$rows with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:extractRequiredCells\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\Offset\\:\\:extractWorksheet\\(\\) has parameter \\$cellAddress with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/Offset.php + + - + message: "#^Parameter \\#1 \\$columnAddress of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:columnIndexFromString\\(\\) expects string, string\\|null given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has parameter \\$a with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\LookupRef\\\\VLookup\\:\\:vlookupSort\\(\\) has parameter \\$b with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Parameter \\#2 \\$callback of function uasort expects callable\\(T, T\\)\\: int, array\\{'self', 'vlookupSort'\\} given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php + + - + message: "#^Binary operation \"/\" between array\\|float\\|int\\|string and array\\|float\\|int\\|string results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php + + - + message: "#^Parameter \\#1 \\$factVal of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\MathTrig\\\\Factorial\\:\\:fact\\(\\) expects array\\|float, int\\\\|int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php + + - + message: "#^Binary operation \"/\" between array\\|float\\|int\\|string and float\\|int results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\MathTrig\\\\IntClass\\:\\:evaluate\\(\\) should return array\\|string but returns int\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php + + - + message: "#^PHPDoc tag @var for constant PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\MathTrig\\\\Subtotal\\:\\:CALL_FUNCTIONS with type array\\ is not subtype of value array\\{1\\: array\\{'PhpOffice…', 'average'\\}, 2\\: array\\{'PhpOffice…', 'COUNT'\\}, 3\\: array\\{'PhpOffice…', 'COUNTA'\\}, 4\\: array\\{'PhpOffice…', 'max'\\}, 5\\: array\\{'PhpOffice…', 'min'\\}, 6\\: array\\{'PhpOffice…', 'product'\\}, 7\\: array\\{'PhpOffice…', 'STDEV'\\}, 8\\: array\\{'PhpOffice…', 'STDEVP'\\}, \\.\\.\\.\\}\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\:\\:MAXIFS\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\:\\:MINIFS\\(\\) should return float but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:filterArguments\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:filterArguments\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:modeCalc\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Averages\\:\\:modeCalc\\(\\) has parameter \\$data with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Averages.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:SUMIF\\(\\) should return float\\|string but returns float\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditionSet\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditionSetForValueRange\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildConditions\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDataSet\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDatabase\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Conditional\\:\\:buildDatabaseWithValueRange\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Conditional.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheP has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheQ has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Beta\\:\\:\\$logBetaCacheResult has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php + + - + message: "#^Constant PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:MAX_ITERATIONS is unused\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has parameter \\$n with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gammp\\(\\) has parameter \\$x with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has parameter \\$n with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gcf\\(\\) has parameter \\$x with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has parameter \\$n with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:gser\\(\\) has parameter \\$x with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has parameter \\$chi2 with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:pchisq\\(\\) has parameter \\$degrees with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Parameter \\#2 \\$columns of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\ChiSquared\\:\\:degrees\\(\\) expects int, float\\|int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:calculateDistribution\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:calculateInverse\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma1\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma2\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma3\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:logGamma4\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:\\$logGammaCacheResult has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\GammaBase\\:\\:\\$logGammaCacheX has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\NewtonRaphson\\:\\:execute\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\NewtonRaphson\\:\\:\\$callback has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Normal\\:\\:inverseNcdf\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\Normal\\:\\:inverseNcdf\\(\\) has parameter \\$p with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php + + - + message: "#^Parameter \\#1 \\$factVal of static method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\MathTrig\\\\Factorial\\:\\:fact\\(\\) expects array\\|float, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php + + - + message: "#^Binary operation \"\\-\" between float\\|string and float\\|int\\|numeric\\-string results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php + + - + message: "#^Constant PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Distributions\\\\StudentT\\:\\:MAX_ITERATIONS is unused\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Distributions/StudentT.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\MaxMinBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\MaxMinBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Percentiles\\:\\:percentileFilterValues\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Percentiles\\:\\:rankFilterValues\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php + + - + message: "#^Binary operation \"/\" between array\\|float\\|int\\|string and array\\|float\\|int\\|string results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Permutations.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:GROWTH\\(\\) should return array\\ but returns array\\\\>\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:TREND\\(\\) should return array\\ but returns array\\\\>\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:checkTrendArrays\\(\\) has parameter \\$array1 with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\Trends\\:\\:checkTrendArrays\\(\\) has parameter \\$array2 with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/Trends.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentAllowStrings\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentBooleans\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\Statistical\\\\VarianceBase\\:\\:datatypeAdjustmentBooleans\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Calculation\\\\TextData\\:\\:CONCATENATE\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData.php + + - + message: "#^Variable \\$value on left side of \\?\\? always exists and is not nullable\\.$#" + count: 4 + path: src/PhpSpreadsheet/Calculation/TextData/Extract.php + + - + message: "#^Variable \\$value on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Calculation/TextData/Text.php + + - + message: "#^Elseif branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:getFormulaAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Parameter \\#2 \\$format of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\:\\:toFormattedString\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:\\$formulaAttributes has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\:\\:\\$parent \\(PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\) in isset\\(\\) is not nullable\\.$#" + count: 6 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Cell.php + + - + message: "#^Call to an undefined method object\\:\\:getHashCode\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#4 \\$currentRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:validateRange\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#5 \\$endRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:validateRange\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/Coordinate.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:substring\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Cell/DataType.php + + - + message: "#^Parameter \\#1 \\$angle of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowAngle\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#1 \\$blur of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowBlur\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#1 \\$distance of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowDistance\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Parameter \\#2 \\$alpha of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\:\\:setShadowColor\\(\\) expects int, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Axis.php + + - + message: "#^Call to an undefined method object\\:\\:render\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getBottomRightXOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getBottomRightYOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getTopLeftXOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:getTopLeftYOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightCell\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightCell\\(\\) has parameter \\$cell with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightXOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightXOffset\\(\\) has parameter \\$xOffset with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightYOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setBottomRightYOffset\\(\\) has parameter \\$yOffset with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftXOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftXOffset\\(\\) has parameter \\$xOffset with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftYOffset\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:setTopLeftYOffset\\(\\) has parameter \\$yOffset with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$legend \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$majorGridlines \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$minorGridlines \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$plotArea \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$title \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$xAxis \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$xAxisLabel \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$yAxis \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\:\\:\\$yAxisLabel \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Chart/DataSeries.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:refresh\\(\\) has parameter \\$flatten with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$dataSource \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$dataTypeValues has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\:\\:\\$fillColor \\(array\\\\|string\\) does not accept array\\\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/DataSeriesValues.php + + - + message: "#^Parameter \\#1 \\$angle of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setShadowAngle\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#1 \\$color of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#1 \\$distance of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setShadowDistance\\(\\) expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#2 \\$alpha of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Parameter \\#3 \\$colorType of method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:setGlowColor\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$glowProperties has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$lineProperties has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$objectState has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$shadowProperties has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\:\\:\\$softEdges has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/GridLines.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Legend.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend\\:\\:\\$positionXLref has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Legend.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/PlotArea.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has parameter \\$elements with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getArrayElementsValue\\(\\) has parameter \\$properties with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arrayKaySelector with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getLineStyleArrowSize\\(\\) has parameter \\$arraySelector with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getShadowPresetsMap\\(\\) has parameter \\$presetsOption with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getTrueAlpha\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:getTrueAlpha\\(\\) has parameter \\$alpha with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$alpha with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$color with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Properties\\:\\:setColorProperties\\(\\) has parameter \\$colorType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$datasetLabels with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$labelCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatDataSetLabels\\(\\) has parameter \\$rotation with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has parameter \\$markerID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:formatPointMarker\\(\\) has parameter \\$seriesPlot with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:getCaption\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:getCaption\\(\\) has parameter \\$captionElement with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has parameter \\$dataValues with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageAdjustValues\\(\\) has parameter \\$sumValues with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:percentageSumCalculation\\(\\) has parameter \\$seriesCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderAreaChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderAreaChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBarChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBarChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderBubbleChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCartesianPlotArea\\(\\) has parameter \\$type with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderCombinationChart\\(\\) has parameter \\$outputDestination with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderContourChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderContourChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderLineChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderLineChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$doughnut with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPieChart\\(\\) has parameter \\$multiplePlots with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotBar\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotBar\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotContour\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$combination with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$dimensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$filled with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotLine\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotRadar\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotScatter\\(\\) has parameter \\$bubble with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotScatter\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderPlotStock\\(\\) has parameter \\$groupID with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderRadarChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderScatterChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:renderStockChart\\(\\) has parameter \\$groupCount with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$chart has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$colourSet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$graph has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$height has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$markSet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$plotColour has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$plotMark has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Renderer\\\\JpGraph\\:\\:\\$width has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Renderer/JpGraph.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Title\\:\\:\\$layout \\(PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Layout\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Chart/Title.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Memory\\:\\:\\$cache has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Collection/Memory.php + + - + message: "#^Parameter \\#1 \\$namedRange of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:addNamedRange\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\NamedRange, \\$this\\(PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\) given\\.$#" + count: 1 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:\\$scope \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/DefinedName.php + + - + message: "#^Cannot use array destructuring on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Dimension.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:startFontTag\\(\\) has parameter \\$tag with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\ITextElement\\:\\:setText\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$bold has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$color has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$colourMap has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$endTagCallbacks has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$face has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$italic has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$size has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$stack has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$startTagCallbacks has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$strikethrough has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$stringData has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$subscript has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$superscript has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Html\\:\\:\\$underline has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Sample\\:\\:getSamples\\(\\) should return array\\\\> but returns array\\\\>\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Helper\\\\Sample\\:\\:log\\(\\) has parameter \\$message with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#1 \\$directory of class RecursiveDirectoryIterator constructor expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#1 \\$filename of function unlink expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#1 \\$path of function pathinfo expects string, array\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Helper/Sample.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:createReader\\(\\) should return PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\IReader but returns object\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:createWriter\\(\\) should return PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\IWriter but returns object\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:\\$readers has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\IOFactory\\:\\:\\$writers has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/IOFactory.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\BaseReader\\:\\:getSecurityScanner\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/BaseReader.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\BaseReader\\:\\:\\$fileHandle has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/BaseReader.php + + - + message: "#^Comparison operation \"\\<\" between int and SimpleXMLElement\\|null results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Gnumeric.php + + - + message: "#^Offset 'percentage' does not exist on SimpleXMLElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php + + - + message: "#^Offset 'value' does not exist on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php + + - + message: "#^Variable \\$orientation on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php + + - + message: "#^Comparison operation \"\\<\\=\" between SimpleXMLElement\\|null and int results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Gnumeric/Styles.php + + - + message: "#^Comparison operation \"\\>\" between SimpleXMLElement\\|null and int results in an error\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Gnumeric/Styles.php + + - + message: "#^Variable \\$value on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Html.php + + - + message: "#^Cannot call method children\\(\\) on SimpleXMLElement\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getAttributeNS\\(\\) on DOMElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getElementsByTagNameNS\\(\\) on DOMElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getNamedItem\\(\\) on DOMNamedNodeMap\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getNamespaces\\(\\) on SimpleXMLElement\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method setSelectedCellByColumnAndRow\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:listWorksheetNames\\(\\) should return array\\ but returns array\\\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$element of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:scanElementForText\\(\\) expects DOMNode, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$settings of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:lookForActiveSheet\\(\\) expects DOMElement, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Parameter \\#1 \\$settings of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\:\\:lookForSelectedCells\\(\\) expects DOMElement, DOMElement\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods.php + + - + message: "#^Cannot call method getElementsByTagNameNS\\(\\) on DOMElement\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 6 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$masterPrintStylesCrossReference has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$masterStylesCrossReference has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$officeNs has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$pageLayoutStyles has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$stylesFo has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\PageSettings\\:\\:\\$stylesNs has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/PageSettings.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:load\\(\\) has parameter \\$namespacesMeta with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setMetaProperties\\(\\) has parameter \\$namespacesMeta with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setMetaProperties\\(\\) has parameter \\$propertyName with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setUserDefinedProperty\\(\\) has parameter \\$propertyValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:setUserDefinedProperty\\(\\) has parameter \\$propertyValueAttributes with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Ods\\\\Properties\\:\\:\\$spreadsheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Ods/Properties.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:__construct\\(\\) has parameter \\$pattern with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:getInstance\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:threadSafeLibxmlDisableEntityLoaderAvailability\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:toUtf8\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:toUtf8\\(\\) has parameter \\$xml with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, array\\\\|string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:\\$callback has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Security\\\\XmlScanner\\:\\:\\$libxmlDisableEntityLoaderValue has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Security/XmlScanner.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\\\SpContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:getDgContainer\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\\\SpContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\|PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:getDggContainer\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndCoordinates\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndOffsetX\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getEndOffsetY\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getNestingLevel\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getOPT\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartCoordinates\\(\\)\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartOffsetX\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Call to an undefined method object\\:\\:getStartOffsetY\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^If condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:includeCellRangeFiltered\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:includeCellRangeFiltered\\(\\) has parameter \\$cellRangeAddress with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:parseRichText\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:parseRichText\\(\\) has parameter \\$is with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$block of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:makeKey\\(\\) expects int, float given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$showSummaryBelow of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:setShowSummaryBelow\\(\\) expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#1 \\$showSummaryRight of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:setShowSummaryRight\\(\\) expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\IReadFilter\\:\\:readCell\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$row of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:sizeRow\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#2 \\$startRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:getDistanceY\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Parameter \\#4 \\$endRow of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Xls\\:\\:getDistanceY\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$data \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$documentSummaryInformation \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$documentSummaryInformation \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$md5Ctxt is never written, only read\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$summaryInformation \\(string\\) does not accept string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\:\\:\\$summaryInformation \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 8 + path: src/PhpSpreadsheet/Reader/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BIFF5\\:\\:\\$map has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BIFF5.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BIFF8\\:\\:\\$map has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BIFF8.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\Color\\\\BuiltIn\\:\\:\\$map has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/Color/BuiltIn.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\ErrorCode\\:\\:\\$map has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/ErrorCode.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:f\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:g\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:h\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:i\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:rotate\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\MD5\\:\\:step\\(\\) has parameter \\$func with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/MD5.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$i has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$j has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xls\\\\RC4\\:\\:\\$s has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xls/RC4.php + + - + message: "#^Argument of an invalid type array\\\\|false supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot access offset 0 on array\\\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot access property \\$r on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method addChart\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Comparison operation \"\\>\" between SimpleXMLElement\\|null and 0 results in an error\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:boolean\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:boolean\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToBoolean\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToBoolean\\(\\) has parameter \\$c with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToError\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToError\\(\\) has parameter \\$c with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$c with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$calculatedValue with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$castBaseType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$cellDataType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$r with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$sharedFormulas with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToFormula\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToString\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:castToString\\(\\) has parameter \\$c with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has parameter \\$add with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:dirAdd\\(\\) has parameter \\$base with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has parameter \\$array with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getArrayItem\\(\\) has parameter \\$key with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:getFromZipArchive\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$dir with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$docSheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readFormControlProperties\\(\\) has parameter \\$fileWorksheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$dir with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$docSheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:readPrinterSettings\\(\\) has parameter \\$fileWorksheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:stripWhiteSpaceFromStyleString\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:stripWhiteSpaceFromStyleString\\(\\) has parameter \\$string with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:toCSSArray\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\:\\:toCSSArray\\(\\) has parameter \\$style with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Negated boolean expression is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$fontSizeInPoints of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:fontSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$sizeInCm of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:centimeterSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$sizeInInch of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:inchSizeToPixels\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#1 \\$worksheetName of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getSheetByName\\(\\) expects string, array\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:readAutoFilter\\(\\) has parameter \\$autoFilterRange with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:readAutoFilter\\(\\) has parameter \\$xmlSheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Parameter \\#1 \\$operator of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\AutoFilter\\\\Column\\\\Rule\\:\\:setRule\\(\\) expects string, null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\AutoFilter\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\BaseParserClass\\:\\:boolean\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\BaseParserClass\\:\\:boolean\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php + + - + message: "#^Cannot call method getFont\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\Run\\|null\\.$#" + count: 12 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Cannot call method setUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 3 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$chartDetail with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$namespacesChartMeta with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeries\\(\\) has parameter \\$plotType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$marker with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$namespacesChartMeta with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValueSet\\(\\) has parameter \\$seriesDetail with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has parameter \\$dataType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValues\\(\\) has parameter \\$seriesValueSet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has parameter \\$dataType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartDataSeriesValuesMultiLevel\\(\\) has parameter \\$seriesValueSet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has parameter \\$chartDetail with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartLayoutDetails\\(\\) has parameter \\$namespacesChartMeta with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:chartTitle\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:parseRichText\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readChartAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readChartAttributes\\(\\) has parameter \\$chartDetail with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has parameter \\$background with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Chart\\:\\:readColor\\(\\) has parameter \\$color with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$position of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend constructor expects string, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$overlay of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Legend constructor expects bool, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$plotOrder of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeries constructor expects array\\, array\\ given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$pointCount of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues constructor expects int, null given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#6 \\$displayBlanksAs of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart constructor expects string, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Parameter \\#7 \\$plotDirection of class PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeries constructor expects string\\|null, bool\\|float\\|int\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Chart.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredColumn\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredColumn\\(\\) has parameter \\$columnCoordinate with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredRow\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:isFilteredRow\\(\\) has parameter \\$rowCoordinate with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnAttributes\\(\\) has parameter \\$readDataOnly with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnRangeAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readColumnRangeAttributes\\(\\) has parameter \\$readDataOnly with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readRowAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:readRowAttributes\\(\\) has parameter \\$readDataOnly with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ColumnAndRowAttributes\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readConditionalStyles\\(\\) has parameter \\$xmlSheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarExtLstOfConditionalRule\\(\\) has parameter \\$cfRule with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarExtLstOfConditionalRule\\(\\) has parameter \\$conditionalFormattingRuleExtensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarOfConditionalRule\\(\\) has parameter \\$cfRule with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readDataBarOfConditionalRule\\(\\) has parameter \\$conditionalFormattingRuleExtensions with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has parameter \\$cfRules with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:readStyleRules\\(\\) has parameter \\$extLst with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:setConditionalStyles\\(\\) has parameter \\$xmlExtLst with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$dxfs has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\ConditionalStyles\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\DataValidations\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\DataValidations\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Hyperlinks\\:\\:\\$hyperlinks has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\Hyperlinks\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:load\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:pageSetup\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\PageSetup\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\SheetViewOptions\\:\\:\\$worksheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xlsx\\\\SheetViewOptions\\:\\:\\$worksheetXml has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php + + - + message: "#^Parameter \\#1 \\$haystack of function strpos expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:convertEncoding\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Reader\\\\Xml\\:\\:\\$fileContents has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml.php + + - + message: "#^Argument of an invalid type SimpleXMLElement\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml/Properties.php + + - + message: "#^Argument of an invalid type SimpleXMLElement\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Reader/Xml/Style.php + + - + message: "#^Elseif condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/ReferenceHelper.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\Run\\:\\:\\$font \\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/RichText/Run.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Settings\\:\\:getHttpClient\\(\\) should return Psr\\\\Http\\\\Client\\\\ClientInterface but returns Psr\\\\Http\\\\Client\\\\ClientInterface\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Settings\\:\\:getRequestFactory\\(\\) should return Psr\\\\Http\\\\Message\\\\RequestFactoryInterface but returns Psr\\\\Http\\\\Message\\\\RequestFactoryInterface\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Result of && is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Settings.php + + - + message: "#^Parameter \\#1 \\$excelFormatCode of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:isDateTimeFormatCode\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Parameter \\#1 \\$unixTimestamp of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:timestampToExcel\\(\\) expects int, float\\|int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Date\\:\\:\\$possibleDateFormatCharacters has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Date.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Drawing.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getDgId\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getLastSpId\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:getSpgrContainer\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setDgId\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setLastSpId\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setSpgrContainer\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:setSpgrContainer\\(\\) has parameter \\$spgrContainer with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\:\\:\\$spgrContainer has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DgContainer\\\\SpgrContainer\\:\\:getChildren\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:\\$parent is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php + + - + message: "#^Cannot access offset 0 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 4 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Cannot access offset 6 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Parameter \\#1 \\$size of function imagettfbbox expects float, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Parameter \\#2 \\$defaultFont of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Drawing\\:\\:pixelsToCellDimension\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:\\$autoSizeMethods has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Variable \\$cellText on left side of \\?\\? always exists and is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Font.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\EigenvalueDecomposition\\:\\:\\$cdivi has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\EigenvalueDecomposition\\:\\:\\$e has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php + + - + message: "#^Else branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\LUDecomposition\\:\\:getDoublePivot\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php + + - + message: "#^Call to function is_string\\(\\) with float\\|int will always evaluate to false\\.$#" + count: 5 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:__construct\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayLeftDivide\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayLeftDivideEquals\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayRightDivide\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayRightDivideEquals\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayTimes\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:arrayTimesEquals\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:concat\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:getMatrix\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:minus\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:minusEquals\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:plus\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:plusEquals\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:power\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:times\\(\\) has parameter \\$args with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Parameter \\#3 \\$c of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\JAMA\\\\Matrix\\:\\:set\\(\\) expects float\\|int\\|null, string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Result of && is always false\\.$#" + count: 10 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 19 + path: src/PhpSpreadsheet/Shared/JAMA/Matrix.php + + - + message: "#^If condition is always true\\.$#" + count: 7 + path: src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php + + - + message: "#^Left side of && is always true\\.$#" + count: 4 + path: src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 3 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Cannot access offset 4 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:getData\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:getStream\\(\\) should return resource but returns resource\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$No of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$oleTimestamp of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:OLE2LocalDate\\(\\) expects string, string\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#2 \\$name of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#3 \\$type of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#4 \\$prev of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#5 \\$next of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#6 \\$dir of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#9 \\$data of class PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\:\\:\\$root \\(PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE.php + + - + message: "#^Parameter \\#2 \\$offset of function array_slice expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Parameter \\#3 \\$length of function array_slice expects int\\|null, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:\\$_data \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:\\$startBlock \\(int\\) on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS.php + + - + message: "#^Parameter \\#1 \\$No of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#4 \\$prev of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#5 \\$next of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#6 \\$dir of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/File.php + + - + message: "#^Parameter \\#1 \\$No of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iSBDcnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iSbdSize of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$iStBlk of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBigData\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#2 \\$iBBcnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#2 \\$iBsize of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#3 \\$iPPScnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveHeader\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#3 \\$iPpsCnt of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:saveBbd\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#4 \\$prev of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#5 \\$next of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#6 \\$dir of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#9 \\$data of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\:\\:__construct\\(\\) expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:\\$bigBlockSize \\(int\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLE\\\\PPS\\\\Root\\:\\:\\$smallBlockSize \\(int\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLE/PPS/Root.php + + - + message: "#^Parameter \\#1 \\$data of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:getInt4d\\(\\) expects string, string\\|false given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$data has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$documentSummaryInformation has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$summaryInformation has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\OLERead\\:\\:\\$wrkbook has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Strict comparison using \\=\\=\\= between int and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/OLERead.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:formatNumber\\(\\) should return string but returns array\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbIsUpper\\(\\) has parameter \\$character with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbStrSplit\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:mbStrSplit\\(\\) has parameter \\$string with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:sanitizeUTF8\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Parameter \\#1 \\$string of function strlen expects string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Static property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:\\$decimalSeparator \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Static property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:\\$thousandsSeparator \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Variable \\$textValue on left side of \\?\\? always exists and is not nullable\\.$#" + count: 3 + path: src/PhpSpreadsheet/Shared/StringHelper.php + + - + message: "#^Static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\TimeZone\\:\\:validateTimeZone\\(\\) is unused\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/TimeZone.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$const with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$meanX with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$meanY with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumX with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumX2 with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumXY with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumY with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:calculateGoodnessOfFit\\(\\) has parameter \\$sumY2 with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:getBestFitType\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:getError\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:sumSquares\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$DFResiduals has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$SSRegression has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$SSResiduals has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$correlation has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$covariance has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$f has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$goodnessOfFit has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$intersect has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$intersectSE has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$slope has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$slopeSE has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$stdevOfResiduals has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$xOffset has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\BestFit\\:\\:\\$yOffset has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/BestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\PolynomialBestFit\\:\\:getCoefficients\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\PolynomialBestFit\\:\\:getCoefficients\\(\\) has parameter \\$dp with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php + + - + message: "#^Call to an undefined method object\\:\\:getGoodnessOfFit\\(\\)\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$const with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$trendType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$xValues with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Trend\\\\Trend\\:\\:calculate\\(\\) has parameter \\$yValues with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/Trend/Trend.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:getData\\(\\) should return string but returns string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Parameter \\#1 \\$uri of method XMLWriter\\:\\:openUri\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:\\$debugEnabled has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:\\$tempFileName \\(string\\) does not accept string\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Shared/XMLWriter.php + + - + message: "#^Call to function is_array\\(\\) with string will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Comparison operation \"\\<\\=\" between int\\ and 1000 is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Parameter \\#1 \\$worksheet of method PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:getIndex\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet, PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\:\\:\\$workbookViewVisibilityValues has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Result of \\|\\| is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 1 + path: src/PhpSpreadsheet/Spreadsheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setConditionalFormattingRuleExt\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setMaximumConditionalFormatValueObject\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setMinimumConditionalFormatValueObject\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBar\\:\\:setShowValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:getXmlAttributes\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:getXmlElements\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:setMaximumConditionalFormatValueObject\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalDataBarExtension\\:\\:setMinimumConditionalFormatValueObject\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:__construct\\(\\) has parameter \\$type with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:__construct\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setCellFormula\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setType\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:setValue\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$cellFormula has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$type has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormatValueObject\\:\\:\\$value has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php + + - + message: "#^Cannot access property \\$axisPosition on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$border on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$direction on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$gradient on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$maxLength on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$minLength on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Cannot access property \\$negativeBarBorderColorSameAsPositive on SimpleXMLElement\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:__construct\\(\\) has parameter \\$id with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:generateUuid\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtDataBarElementChildrenFromXml\\(\\) has parameter \\$ns with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtLstXml\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:parseExtLstXml\\(\\) has parameter \\$extLstXml with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'rgb' does not exist on SimpleXMLElement\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'theme' does not exist on SimpleXMLElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Offset 'tint' does not exist on SimpleXMLElement\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\ConditionalFormatting\\\\ConditionalFormattingRuleExtension\\:\\:\\$id has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has parameter \\$sections with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormat\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$cond with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$dfcond with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$dfval with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$val with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:splitFormatCompare\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\Formatter\\:\\:toFormattedString\\(\\) should return string but returns float\\|int\\|string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_split expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/Formatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\\\PercentageFormatter\\:\\:format\\(\\) has parameter \\$value with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php + + - + message: "#^Parameter \\#1 \\$format of function sprintf expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\CellIterator\\:\\:adjustForExistingOnlyRange\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/CellIterator.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Column\\:\\:\\$parent \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Column.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Drawing\\\\Shadow\\:\\:\\$color \\(PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Color\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:getPrintArea\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Parameter \\#1 \\$value of method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:setFirstPageNumber\\(\\) expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\PageSetup\\:\\:\\$pageOrder has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Strict comparison using \\=\\=\\= between int\\ and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/PageSetup.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Row\\:\\:\\$worksheet \\(PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Row.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\SheetView\\:\\:\\$sheetViewTypes has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Strict comparison using \\=\\=\\= between int\\ and null will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/SheetView.php + + - + message: "#^Cannot call method getCalculatedValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getValue\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 4 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getWorksheet\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\DefinedName\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method getXfIndex\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Cell\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Cannot call method rangeToArray\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^If condition is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Left side of && is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:getChartByName\\(\\) should return PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\|false but returns PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Chart\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$index of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\ColumnDimension constructor expects string, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$index of class PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\RowDimension constructor expects int, null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:rangeDimension\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:removeRow\\(\\) expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#1 \\$row of method PhpOffice\\\\PhpSpreadsheet\\\\Collection\\\\Cells\\:\\:removeRow\\(\\) expects string, int\\<1, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#2 \\$format of static method PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\:\\:toFormattedString\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Parameter \\#3 \\$rotation of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:calculateColumnWidth\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Worksheet\\\\Worksheet\\:\\:\\$parent \\(PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\) does not accept PhpOffice\\\\PhpSpreadsheet\\\\Spreadsheet\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Right side of && is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between string and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Worksheet/Worksheet.php + + - + message: "#^Call to function array_key_exists\\(\\) with int and array\\{none\\: 'none', dashDot\\: '1px dashed', dashDotDot\\: '1px dotted', dashed\\: '1px dashed', dotted\\: '1px dotted', double\\: '3px double', hair\\: '1px solid', medium\\: '2px solid', \\.\\.\\.\\} will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 'mime' on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 0 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot call method getSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Cannot call method getSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$candidateSpannedRow with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$sheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:calculateSpansOmitRows\\(\\) has parameter \\$sheetIndex with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateHTMLFooter\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has parameter \\$desc with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateMeta\\(\\) has parameter \\$val with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$cellAddress with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$columnNumber with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellCss\\(\\) has parameter \\$row with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cell with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cellType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellData\\(\\) has parameter \\$cssClass with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValue\\(\\) has parameter \\$cell with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValue\\(\\) has parameter \\$cellData with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cell with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowCellDataValueRich\\(\\) has parameter \\$cellData with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowIncludeCharts\\(\\) has parameter \\$coordinate with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$colSpan with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$html with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowSpans\\(\\) has parameter \\$rowSpan with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cellData with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cellType with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$colNum with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$colSpan with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$coordinate with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$cssClass with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$html with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$row with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$rowSpan with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateRowWriteCell\\(\\) has parameter \\$sheetIndex with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetPrep\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has parameter \\$rowMin with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetStarts\\(\\) has parameter \\$sheet with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$row with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$tbodyStart with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$theadEnd with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateSheetTags\\(\\) has parameter \\$theadStart with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableFooter\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$html with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$id with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTag\\(\\) has parameter \\$sheetIndex with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTagInline\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:generateTableTagInline\\(\\) has parameter \\$id with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$borderStyle of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapBorderStyle\\(\\) expects int, string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$font of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:createCSSStyleFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$hAlign of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapHAlign\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$string of function htmlspecialchars expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#1 \\$vAlign of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Html\\:\\:mapVAlign\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#2 \\$length of function fread expects int\\<0, max\\>, int\\<0, max\\>\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Parameter \\#3 \\$use_include_path of function fopen expects bool, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Ternary operator condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Html.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods.php + + - + message: "#^If condition is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Ods/Cell/Style.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Cell\\\\Style\\:\\:\\$writer has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Cell/Style.php + + - + message: "#^Parameter \\#1 \\$range of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:splitRange\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<2, max\\> given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Content\\:\\:\\$formulaConvertor has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Content.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Ods\\\\Formula\\:\\:\\$definedNames has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Ods/Formula.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Cannot use array destructuring on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endCoordinates' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endOffsetX' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'endOffsetY' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startCoordinates' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startOffsetX' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Offset 'startOffsetY' does not exist on array\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$blipType of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\:\\:setBlipType\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$data of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Escher\\\\DggContainer\\\\BstoreContainer\\\\BSE\\\\Blip\\:\\:setData\\(\\) expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Parameter \\#1 \\$font of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:addFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\:\\:\\$documentSummaryInformation \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\:\\:\\$summaryInformation \\(string\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\BIFFwriter\\:\\:writeEof\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php + + - + message: "#^Static property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\BIFFwriter\\:\\:\\$byteOrder \\(int\\) in isset\\(\\) is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php + + - + message: "#^Elseif condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^If condition is always true\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Escher\\:\\:\\$data has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Escher\\:\\:\\$object has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Escher.php + + - + message: "#^If condition is always false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$bold of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Font\\:\\:mapBold\\(\\) expects bool, bool\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$fontName of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\Font\\:\\:getCharsetFromFontName\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$textValue of static method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:UTF8toBIFF8UnicodeShort\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Parameter \\#1 \\$underline of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Font\\:\\:mapUnderline\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Font.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Parser\\:\\:advance\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'left' does not exist on non\\-empty\\-array\\|string\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'right' does not exist on non\\-empty\\-array\\|string\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Offset 'value' does not exist on non\\-empty\\-array\\|string\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Parameter \\#3 \\$subject of function str_replace expects array\\|string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Parser\\:\\:\\$spreadsheet has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Unreachable statement \\- code above always terminates\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xls/Parser.php + + - + message: "#^Cannot access offset 'encoding' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeAllDefinedNamesBiff8\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeExternalsheetBiff8\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeMsoDrawingGroup\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:writeSupbookInternal\\(\\) has no return type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:\\$biffSize is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Workbook\\:\\:\\$colors has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Workbook.php + + - + message: "#^Cannot access offset 'comp' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 'ident' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 'sa' on array\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 1 on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot access offset 2 on array\\|false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Cannot call method getHashCode\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$coordinates of static method PhpOffice\\\\PhpSpreadsheet\\\\Cell\\\\Coordinate\\:\\:indexesFromString\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$string of function strlen expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, string\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$length of function fread expects int\\<0, max\\>, int\\<0, max\\>\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#2 \\$subject of function preg_match_all expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#3 \\$subject of function preg_replace expects array\\|string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#4 \\$isError of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:writeBoolErr\\(\\) expects bool, int given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#5 \\$width of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:positionImage\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#6 \\$height of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:positionImage\\(\\) expects int, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$activePane \\(int\\) does not accept int\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$colors has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$countCellStyleXfs is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$outlineBelow is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$outlineRight is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$selection is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Worksheet\\:\\:\\$xlsStringMaxLength is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Worksheet.php + + - + message: "#^Parameter \\#1 \\$textRotation of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Xf\\:\\:mapTextRotation\\(\\) expects int, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Xf.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xls\\\\Xf\\:\\:\\$diag is never read, only written\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xls/Xf.php + + - + message: "#^Argument of an invalid type array\\|null supplied for foreach, only iterables are supported\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Parameter \\#1 \\$path of function basename expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Parameter \\#1 \\$path of function dirname expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Possibly invalid array key type array\\|string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\:\\:\\$pathNames has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx.php + + - + message: "#^Cannot call method getDataValues\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Cannot call method getFillColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Else branch is unreachable because previous condition is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$plotSeriesValues of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeBubbles\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|null, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\DataSeriesValues\\|false given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$rawTextData of method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\XMLWriter\\:\\:writeRawData\\(\\) expects array\\\\|string\\|null, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, array\\|int\\|string given\\.$#" + count: 8 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, array\\|int\\|string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float\\|int given\\.$#" + count: 4 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 45 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#3 \\$id1 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$id1 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#4 \\$id2 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects string, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#5 \\$id2 of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects string, int\\|string given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#6 \\$yAxis of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeCategoryAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#7 \\$xAxis of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\Axis\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#8 \\$majorGridlines of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#9 \\$minorGridlines of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:writeValueAxis\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines, PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\GridLines\\|null given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Part \\$xAxis\\-\\>getShadowProperty\\('effect'\\) \\(array\\|int\\|string\\|null\\) of encapsed string cannot be cast to string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Part \\$xAxis\\-\\>getShadowProperty\\(\\['color', 'type'\\]\\) \\(array\\|int\\|string\\|null\\) of encapsed string cannot be cast to string\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Property PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Chart\\:\\:\\$calculateCellValues has no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Strict comparison using \\=\\=\\= between PhpOffice\\\\PhpSpreadsheet\\\\Chart\\\\PlotArea and null will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Chart.php + + - + message: "#^Parameter \\#1 \\$string of function substr expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Comments.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Comments.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/DocProps.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/DocProps.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeUnparsedRelationship\\(\\) has parameter \\$relationship with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeUnparsedRelationship\\(\\) has parameter \\$type with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Parameter \\#2 \\$id of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeRelationship\\(\\) expects int, string given\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Parameter \\#4 \\$target of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Rels\\:\\:writeRelationship\\(\\) expects string, array\\|string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Rels.php + + - + message: "#^Cannot call method getBold\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getColor\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getItalic\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getName\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSize\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getStrikethrough\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSubscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getSuperscript\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getUnderline\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Instanceof between \\*NEVER\\* and PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Instanceof between string and PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText will always evaluate to false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#1 \\$text of method PhpOffice\\\\PhpSpreadsheet\\\\RichText\\\\RichText\\:\\:createTextRun\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 5 + path: src/PhpSpreadsheet/Writer/Xlsx/StringTable.php + + - + message: "#^Cannot call method getStyle\\(\\) on PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Conditional\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Comparison operation \"\\<\" between int\\ and 0 is always true\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$borders of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeBorder\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Borders\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$fill of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeFill\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Fill\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$font of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeFont\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\Font\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$numberFormat of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Style\\:\\:writeNumFmt\\(\\) expects PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat, PhpOffice\\\\PhpSpreadsheet\\\\Style\\\\NumberFormat\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, float given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 22 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<1, max\\> given\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Result of \\|\\| is always true\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Style.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 7 + path: src/PhpSpreadsheet/Writer/Xlsx/Workbook.php + + - + message: "#^Expression on left side of \\?\\? is not nullable\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^If condition is always true\\.$#" + count: 6 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) has parameter \\$condition with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeDataBarElements\\(\\) has parameter \\$dataBar with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeElementIf\\(\\) has parameter \\$condition with no type specified\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Negated boolean expression is always false\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Offset int\\<1, max\\> on array\\\\> in isset\\(\\) does not exist\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$content of method XMLWriter\\:\\:writeElement\\(\\) expects string\\|null, int\\|string given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int given\\.$#" + count: 15 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<0, max\\> given\\.$#" + count: 3 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\<1, max\\> given\\.$#" + count: 9 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, int\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#2 \\$value of method XMLWriter\\:\\:writeAttribute\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#3 \\$stringTable of method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeSheetData\\(\\) expects array\\, array\\\\|null given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Parameter \\#4 \\$val of static method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Worksheet\\:\\:writeAttributeIf\\(\\) expects string, int given\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Strict comparison using \\=\\=\\= between false and true will always evaluate to false\\.$#" + count: 2 + path: src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php + + - + message: "#^Method PhpOffice\\\\PhpSpreadsheet\\\\Writer\\\\Xlsx\\\\Xlfn\\:\\:addXlfn\\(\\) should return string but returns string\\|null\\.$#" + count: 1 + path: src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php + diff --git a/lib/phpoffice/phpspreadsheet/phpstan-conditional.php b/lib/phpoffice/phpspreadsheet/phpstan-conditional.php new file mode 100644 index 00000000..c5d28dd6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/phpstan-conditional.php @@ -0,0 +1,51 @@ + '~^Method .* has invalid return type GdImage\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Shared/Drawing.php', + 'count' => 1, + ]; + $config['parameters']['ignoreErrors'][] = [ + 'message' => '~^Property .* has unknown class GdImage as its type\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', + 'count' => 1, + ]; + $config['parameters']['ignoreErrors'][] = [ + 'message' => '~^Method .* has invalid return type GdImage\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', + 'count' => 1, + ]; + $config['parameters']['ignoreErrors'][] = [ + 'message' => '~^Parameter .* of method .* has invalid type GdImage\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php', + 'count' => 1, + ]; + $config['parameters']['ignoreErrors'][] = [ + 'message' => '~^Class GdImage not found\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xls/Worksheet.php', + 'count' => 1, + ]; + $config['parameters']['ignoreErrors'][] = [ + 'message' => '~^Parameter .* of method .* has invalid type GdImage\.$~', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xls/Worksheet.php', + 'count' => 1, + ]; + // Erroneous analysis by Phpstan before PHP8 - 3rd parameter is nullable + $config['parameters']['ignoreErrors'][] = [ + 'message' => '#^Parameter \\#3 \\$namespace of method XMLWriter\\:\\:startElementNs\\(\\) expects string, null given\\.$#', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php', + 'count' => 8, + ]; + // Erroneous analysis by Phpstan before PHP8 - mb_strlen does not return false + $config['parameters']['ignoreErrors'][] = [ + 'message' => '#^Method PhpOffice\\\\PhpSpreadsheet\\\\Shared\\\\StringHelper\\:\\:countCharacters\\(\\) should return int but returns int(<0, max>)?\\|false\\.$#', + 'path' => __DIR__ . '/src/PhpSpreadsheet/Shared/StringHelper.php', + 'count' => 1, + ]; +} + +return $config; diff --git a/lib/phpoffice/phpspreadsheet/phpstan.neon.dist b/lib/phpoffice/phpspreadsheet/phpstan.neon.dist new file mode 100644 index 00000000..e97e1ce8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/phpstan.neon.dist @@ -0,0 +1,26 @@ +includes: + - phpstan-baseline.neon + - phpstan-conditional.php + - vendor/phpstan/phpstan-phpunit/extension.neon + - vendor/phpstan/phpstan-phpunit/rules.neon + +parameters: + level: 8 + paths: + - src/ + - tests/ + parallel: + processTimeout: 300.0 + checkMissingIterableValueType: false + ignoreErrors: + - '~^Parameter \#1 \$im(age)? of function (imagedestroy|imageistruecolor|imagealphablending|imagesavealpha|imagecolortransparent|imagecolorsforindex|imagesavealpha|imagesx|imagesy) expects (GdImage|resource), GdImage\|resource given\.$~' + - '~^Parameter \#2 \$src_im(age)? of function imagecopy expects (GdImage|resource), GdImage\|resource given\.$~' + # Accept a bit anything for assert methods + - '~^Parameter \#2 .* of static method PHPUnit\\Framework\\Assert\:\:assert\w+\(\) expects .*, .* given\.$~' + - '~^Method PhpOffice\\PhpSpreadsheetTests\\.*\:\:test.*\(\) has parameter \$args with no type specified\.$~' + + # Ignore all JpGraph issues + - '~^Constant (MARK_CIRCLE|MARK_CROSS|MARK_DIAMOND|MARK_DTRIANGLE|MARK_FILLEDCIRCLE|MARK_SQUARE|MARK_STAR|MARK_UTRIANGLE|MARK_X|SIDE_RIGHT) not found\.$~' + - '~^Instantiated class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot) not found\.$~' + - '~^Call to method .*\(\) on an unknown class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot)\.$~' + - '~^Access to property .* on an unknown class (AccBarPlot|AccLinePlot|BarPlot|ContourPlot|Graph|GroupBarPlot|GroupBarPlot|LinePlot|LinePlot|PieGraph|PiePlot|PiePlot3D|PiePlotC|RadarGraph|RadarPlot|ScatterPlot|Spline|StockPlot)\.$~' diff --git a/lib/phpoffice/phpspreadsheet/src/Bootstrap.php b/lib/phpoffice/phpspreadsheet/src/Bootstrap.php deleted file mode 100644 index f15de26a..00000000 --- a/lib/phpoffice/phpspreadsheet/src/Bootstrap.php +++ /dev/null @@ -1,22 +0,0 @@ -initialise($arguments ?: []); + } + + /** + * Handles array argument processing when the function accepts a single argument that can be an array argument. + * Example use for: + * DAYOFMONTH() or FACT(). + */ + protected static function evaluateSingleArgumentArray(callable $method, array $values): array + { + $result = []; + foreach ($values as $value) { + $result[] = $method($value); + } + + return $result; + } + + /** + * Handles array argument processing when the function accepts multiple arguments, + * and any of them can be an array argument. + * Example use for: + * ROUND() or DATE(). + * + * @param mixed ...$arguments + */ + protected static function evaluateArrayArguments(callable $method, ...$arguments): array + { + self::initialiseHelper($arguments); + $arguments = self::$arrayArgumentHelper->arguments(); + + return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); + } + + /** + * Handles array argument processing when the function accepts multiple arguments, + * but only the first few (up to limit) can be an array arguments. + * Example use for: + * NETWORKDAYS() or CONCATENATE(), where the last argument is a matrix (or a series of values) that need + * to be treated as a such rather than as an array arguments. + * + * @param mixed ...$arguments + */ + protected static function evaluateArrayArgumentsSubset(callable $method, int $limit, ...$arguments): array + { + self::initialiseHelper(array_slice($arguments, 0, $limit)); + $trailingArguments = array_slice($arguments, $limit); + $arguments = self::$arrayArgumentHelper->arguments(); + $arguments = array_merge($arguments, $trailingArguments); + + return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); + } + + /** + * @param mixed $value + */ + private static function testFalse($value): bool + { + return $value === false; + } + + /** + * Handles array argument processing when the function accepts multiple arguments, + * but only the last few (from start) can be an array arguments. + * Example use for: + * Z.TEST() or INDEX(), where the first argument 1 is a matrix that needs to be treated as a dataset + * rather than as an array argument. + * + * @param mixed ...$arguments + */ + protected static function evaluateArrayArgumentsSubsetFrom(callable $method, int $start, ...$arguments): array + { + $arrayArgumentsSubset = array_combine( + range($start, count($arguments) - $start), + array_slice($arguments, $start) + ); + if (self::testFalse($arrayArgumentsSubset)) { + return ['#VALUE!']; + } + + self::initialiseHelper($arrayArgumentsSubset); + $leadingArguments = array_slice($arguments, 0, $start); + $arguments = self::$arrayArgumentHelper->arguments(); + $arguments = array_merge($leadingArguments, $arguments); + + return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); + } + + /** + * Handles array argument processing when the function accepts multiple arguments, + * and any of them can be an array argument except for the one specified by ignore. + * Example use for: + * HLOOKUP() and VLOOKUP(), where argument 1 is a matrix that needs to be treated as a database + * rather than as an array argument. + * + * @param mixed ...$arguments + */ + protected static function evaluateArrayArgumentsIgnore(callable $method, int $ignore, ...$arguments): array + { + $leadingArguments = array_slice($arguments, 0, $ignore); + $ignoreArgument = array_slice($arguments, $ignore, 1); + $trailingArguments = array_slice($arguments, $ignore + 1); + + self::initialiseHelper(array_merge($leadingArguments, [[null]], $trailingArguments)); + $arguments = self::$arrayArgumentHelper->arguments(); + + array_splice($arguments, $ignore, 1, $ignoreArgument); + + return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php new file mode 100644 index 00000000..5d4f261f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/BinaryComparison.php @@ -0,0 +1,181 @@ + '' && $operand1[0] == Calculation::FORMULA_STRING_QUOTE) { + $operand1 = Calculation::unwrapResult($operand1); + } + if (is_string($operand2) && $operand2 > '' && $operand2[0] == Calculation::FORMULA_STRING_QUOTE) { + $operand2 = Calculation::unwrapResult($operand2); + } + + // Use case insensitive comparaison if not OpenOffice mode + if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { + if (is_string($operand1)) { + $operand1 = StringHelper::strToUpper($operand1); + } + if (is_string($operand2)) { + $operand2 = StringHelper::strToUpper($operand2); + } + } + + $useLowercaseFirstComparison = is_string($operand1) && + is_string($operand2) && + Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE; + + return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function evaluateComparison($operand1, $operand2, string $operator, bool $useLowercaseFirstComparison): bool + { + switch ($operator) { + // Equality + case '=': + return self::equal($operand1, $operand2); + // Greater than + case '>': + return self::greaterThan($operand1, $operand2, $useLowercaseFirstComparison); + // Less than + case '<': + return self::lessThan($operand1, $operand2, $useLowercaseFirstComparison); + // Greater than or equal + case '>=': + return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison); + // Less than or equal + case '<=': + return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison); + // Inequality + case '<>': + return self::notEqual($operand1, $operand2); + default: + throw new Exception('Unsupported binary comparison operator'); + } + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function equal($operand1, $operand2): bool + { + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = (abs($operand1 - $operand2) < self::DELTA); + } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { + $result = $operand1 == $operand2; + } else { + $result = self::strcmpAllowNull($operand1, $operand2) == 0; + } + + return $result; + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function greaterThanOrEqual($operand1, $operand2, bool $useLowercaseFirstComparison): bool + { + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 > $operand2)); + } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { + $result = $operand1 >= $operand2; + } elseif ($useLowercaseFirstComparison) { + $result = self::strcmpLowercaseFirst($operand1, $operand2) >= 0; + } else { + $result = self::strcmpAllowNull($operand1, $operand2) >= 0; + } + + return $result; + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function lessThanOrEqual($operand1, $operand2, bool $useLowercaseFirstComparison): bool + { + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 < $operand2)); + } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { + $result = $operand1 <= $operand2; + } elseif ($useLowercaseFirstComparison) { + $result = self::strcmpLowercaseFirst($operand1, $operand2) <= 0; + } else { + $result = self::strcmpAllowNull($operand1, $operand2) <= 0; + } + + return $result; + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function greaterThan($operand1, $operand2, bool $useLowercaseFirstComparison): bool + { + return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function lessThan($operand1, $operand2, bool $useLowercaseFirstComparison): bool + { + return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; + } + + /** + * @param mixed $operand1 + * @param mixed $operand2 + */ + private static function notEqual($operand1, $operand2): bool + { + return self::equal($operand1, $operand2) !== true; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php index 69f72033..26ef7946 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php @@ -2,15 +2,23 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner; use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; +use PhpOffice\PhpSpreadsheet\Calculation\Information\Value; use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; -use PhpOffice\PhpSpreadsheet\NamedRange; +use PhpOffice\PhpSpreadsheet\DefinedName; +use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use ReflectionClassConstant; +use ReflectionMethod; +use ReflectionParameter; class Calculation { @@ -23,11 +31,19 @@ class Calculation // Opening bracket const CALCULATION_REGEXP_OPENBRACE = '\('; // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) - const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?([A-Z][A-Z0-9\.]*)[\s]*\('; + const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?([\p{L}][\p{L}\p{N}\.]*)[\s]*\('; // Cell reference (cell or range of cells, with or without a sheet reference) - const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; - // Named Range of cells - const CALCULATION_REGEXP_NAMEDRANGE = '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)'; + const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'.*?\')|(\".*?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; + // Cell reference (with or without a sheet reference) ensuring absolute/relative + const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'.*?\')|(\".*?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; + const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'.*?\')|(\".*?\"))!)?(\$?[a-z]{1,3})):(?![.*])'; + const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'.*?\')|(\".*?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; + // Cell reference (with or without a sheet reference) ensuring absolute/relative + // Cell ranges ensuring absolute/relative + const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; + const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; + // Defined Names: Named Range of cells, or Named Formulae + const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'.*?\')|(\".*?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)'; // Error const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; @@ -36,6 +52,12 @@ class Calculation const RETURN_ARRAY_AS_VALUE = 'value'; const RETURN_ARRAY_AS_ARRAY = 'array'; + const FORMULA_OPEN_FUNCTION_BRACE = '('; + const FORMULA_CLOSE_FUNCTION_BRACE = ')'; + const FORMULA_OPEN_MATRIX_BRACE = '{'; + const FORMULA_CLOSE_MATRIX_BRACE = '}'; + const FORMULA_STRING_QUOTE = '"'; + private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; /** @@ -67,12 +89,13 @@ class Calculation private $calculationCacheEnabled = true; /** - * Used to generate unique store keys. - * - * @var int + * @var BranchPruner */ - private $branchStoreKeyCounter = 0; + private $branchPruner; + /** + * @var bool + */ private $branchPruningEnabled = true; /** @@ -85,7 +108,8 @@ class Calculation '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, - '<=' => true, '<>' => true, '|' => true, ':' => true, + '<=' => true, '<>' => true, '∩' => true, '∪' => true, + ':' => true, ]; /** @@ -97,7 +121,7 @@ class Calculation '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, - '|' => true, ':' => true, + '∩' => true, '∪' => true, ':' => true, ]; /** @@ -119,10 +143,17 @@ class Calculation /** * Error message for any error that was raised/thrown by the calculation engine. * - * @var string + * @var null|string */ public $formulaError; + /** + * Reference Helper. + * + * @var ReferenceHelper + */ + private static $referenceHelper; + /** * An array of the nested cell references accessed by the calculation engine, used for the debug log. * @@ -150,13 +181,6 @@ class Calculation */ public $cyclicFormulaCount = 1; - /** - * Epsilon Precision used for comparisons in calculations. - * - * @var float - */ - private $delta = 0.1e-12; - /** * The current locale setting. * @@ -186,7 +210,7 @@ class Calculation /** * Locale-specific translations for Excel constants (True, False and Null). * - * @var string[] + * @var array */ public static $localeBoolean = [ 'TRUE' => 'TRUE', @@ -198,9 +222,9 @@ class Calculation * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. * - * @var string[] + * @var array */ - private static $excelConstants = [ + public static $excelConstants = [ 'TRUE' => true, 'FALSE' => false, 'NULL' => null, @@ -210,62 +234,67 @@ class Calculation private static $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'abs', + 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ACCRINT'], - 'argumentCount' => '4-7', + 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], + 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ACCRINTM'], + 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'acos', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'acosh', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ACOT'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ACOTH'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'cellAddress'], + 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], + 'AGGREGATE' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3+', + ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'AMORDEGRC'], + 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'AMORLINC'], + 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalAnd'], + 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ARABIC'], + 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ @@ -273,6 +302,11 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], + 'ARRAYTOTEXT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], @@ -280,52 +314,52 @@ class Calculation ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'asin', + 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'asinh', + 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'atan', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ATAN2'], + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'atanh', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVEDEV'], + 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGE'], + 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGEA'], + 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'AVERAGEIF'], + 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ @@ -335,88 +369,123 @@ class Calculation ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'BASE'], + 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELI'], + 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELJ'], + 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELK'], + 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BESSELY'], + 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BETADIST'], + 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], + 'BETA.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '4-6', + ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BETAINV'], + 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], + 'argumentCount' => '3-5', + ], + 'BETA.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTODEC'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTOHEX'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BINTOOCT'], + 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'BINOMDIST'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], + 'argumentCount' => '4', + ], + 'BINOM.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], + 'BINOM.DIST.RANGE' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], + 'argumentCount' => '3,4', + ], + 'BINOM.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], + 'argumentCount' => '3', + ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITAND'], + 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITOR'], + 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITOR'], + 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITLSHIFT'], + 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'BITRSHIFT'], + 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CEILING'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], + 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric + ], + 'CEILING.MATH' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\Ceiling::class, 'math'], + 'argumentCount' => '1-3', + ], + 'CEILING.PRECISE' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\Ceiling::class, 'precise'], + 'argumentCount' => '1,2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, @@ -425,178 +494,229 @@ class Calculation ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CHARACTER'], + 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIDIST'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], + 'argumentCount' => '2', + ], + 'CHISQ.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], + 'argumentCount' => '3', + ], + 'CHISQ.DIST.RT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CHIINV'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], + 'argumentCount' => '2', + ], + 'CHISQ.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], + 'argumentCount' => '2', + ], + 'CHISQ.INV.RT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], + 'argumentCount' => '2', + ], + 'CHISQ.TEST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'CHOOSE'], + 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TRIMNONPRINTABLE'], + 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'ASCIICODE'], + 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'COLUMN'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', + 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'COLUMNS'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COMBIN'], + 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], + 'argumentCount' => '2', + ], + 'COMBINA' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'COMPLEX'], + 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CONCATENATE'], + 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CONCATENATE'], + 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CONFIDENCE'], + 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], + 'argumentCount' => '3', + ], + 'CONFIDENCE.NORM' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], + 'argumentCount' => '3', + ], + 'CONFIDENCE.T' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'CONVERTUOM'], + 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CORREL'], + 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'cos', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'cosh', + 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COT'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'COTH'], + 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNT'], + 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTA'], + 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTBLANK'], + 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTIF'], + 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COUNTIFS'], + 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYBS'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYS'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPDAYSNC'], + 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPNCD'], + 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPNUM'], + 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'COUPPCD'], + 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'COVAR'], + 'functionCall' => [Statistical\Trends::class, 'COVAR'], + 'argumentCount' => '2', + ], + 'COVARIANCE.P' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Trends::class, 'COVAR'], + 'argumentCount' => '2', + ], + 'COVARIANCE.S' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CRITBINOM'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CSC'], + 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'CSCH'], + 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ @@ -636,152 +756,167 @@ class Calculation ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'CUMIPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'CUMPRINC'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATE'], + 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATEDIF'], + 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], + 'DATESTRING' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATEVALUE'], + 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DAVERAGE'], + 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYOFMONTH'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYS'], + 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DAYS360'], + 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DB'], + 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], + 'DBCS' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '1', + ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DCOUNT'], + 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DCOUNTA'], + 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DDB'], + 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOBIN'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOHEX'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DECTOOCT'], + 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], + 'DECIMAL' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'rad2deg', + 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'DELTA'], + 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'DEVSQ'], + 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DGET'], + 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DISC'], + 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DMAX'], + 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DMIN'], + 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'DOLLAR'], + 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DOLLARDE'], + 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'DOLLARFR'], + 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DPRODUCT'], + 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSTDEV'], + 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSTDEVP'], + 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DSUM'], + 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ @@ -791,87 +926,102 @@ class Calculation ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DVAR'], + 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, - 'functionCall' => [Database::class, 'DVARP'], + 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], + 'ECMA.CEILING' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '1,2', + ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'EDATE'], + 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'EFFECT'], + 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], + 'ENCODEURL' => [ + 'category' => Category::CATEGORY_WEB, + 'functionCall' => [Web\Service::class, 'urlEncode'], + 'argumentCount' => '1', + ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'EOMONTH'], + 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERF'], + 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFPRECISE'], + 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFC'], + 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'ERFC'], + 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'errorType'], + 'functionCall' => [Information\ExcelError::class, 'type'], 'argumentCount' => '1', ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'EVEN'], + 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'EXACT'], + 'functionCall' => [TextData\Text::class, 'exact'], 'argumentCount' => '2', ], 'EXP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'exp', + 'functionCall' => [MathTrig\Exp::class, 'evaluate'], 'argumentCount' => '1', ], 'EXPONDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'EXPONDIST'], + 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], + 'argumentCount' => '3', + ], + 'EXPON.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'], 'argumentCount' => '3', ], 'FACT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FACT'], + 'functionCall' => [MathTrig\Factorial::class, 'fact'], 'argumentCount' => '1', ], 'FACTDOUBLE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FACTDOUBLE'], + 'functionCall' => [MathTrig\Factorial::class, 'factDouble'], 'argumentCount' => '1', ], 'FALSE' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'FALSE'], + 'functionCall' => [Logical\Boolean::class, 'FALSE'], 'argumentCount' => '0', ], 'FDIST' => [ @@ -879,14 +1029,34 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], + 'F.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\F::class, 'distribution'], + 'argumentCount' => '4', + ], + 'F.DIST.RT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3', + ], + 'FILTER' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [LookupRef\Filter::class, 'filter'], + 'argumentCount' => '2-3', + ], + 'FILTERXML' => [ + 'category' => Category::CATEGORY_WEB, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], 'FIND' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'sensitive'], 'argumentCount' => '2,3', ], 'FINV' => [ @@ -894,44 +1064,79 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], + 'F.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3', + ], + 'F.INV.RT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3', + ], 'FISHER' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FISHER'], + 'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'], 'argumentCount' => '1', ], 'FISHERINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FISHERINV'], + 'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'], 'argumentCount' => '1', ], 'FIXED' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'FIXEDFORMAT'], + 'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'], 'argumentCount' => '1-3', ], 'FLOOR' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOOR'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Floor::class, 'floor'], + 'argumentCount' => '1-2', // Excel requries 2, Ods/Gnumeric 1-2 ], 'FLOOR.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOORMATH'], - 'argumentCount' => '3', + 'functionCall' => [MathTrig\Floor::class, 'math'], + 'argumentCount' => '1-3', ], 'FLOOR.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'FLOORPRECISE'], - 'argumentCount' => '2', + 'functionCall' => [MathTrig\Floor::class, 'precise'], + 'argumentCount' => '1-2', ], 'FORECAST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'FORECAST'], + 'functionCall' => [Statistical\Trends::class, 'FORECAST'], + 'argumentCount' => '3', + ], + 'FORECAST.ETS' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3-6', + ], + 'FORECAST.ETS.CONFINT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3-6', + ], + 'FORECAST.ETS.SEASONALITY' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2-4', + ], + 'FORECAST.ETS.STAT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3-6', + ], + 'FORECAST.LINEAR' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Trends::class, 'FORECAST'], 'argumentCount' => '3', ], 'FORMULATEXT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'FORMULATEXT'], + 'functionCall' => [LookupRef\Formula::class, 'text'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], @@ -946,44 +1151,74 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], + 'F.TEST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], 'FV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'FV'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'], 'argumentCount' => '3-5', ], 'FVSCHEDULE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'FVSCHEDULE'], + 'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'], 'argumentCount' => '2', ], + 'GAMMA' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'], + 'argumentCount' => '1', + ], 'GAMMADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMADIST'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], + 'argumentCount' => '4', + ], + 'GAMMA.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'], 'argumentCount' => '4', ], 'GAMMAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMAINV'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], + 'argumentCount' => '3', + ], + 'GAMMA.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'], 'argumentCount' => '3', ], 'GAMMALN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GAMMALN'], + 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], + 'argumentCount' => '1', + ], + 'GAMMALN.PRECISE' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'], + 'argumentCount' => '1', + ], + 'GAUSS' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'], 'argumentCount' => '1', ], 'GCD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'GCD'], + 'functionCall' => [MathTrig\Gcd::class, 'evaluate'], 'argumentCount' => '1+', ], 'GEOMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GEOMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'geometric'], 'argumentCount' => '1+', ], 'GESTEP' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'GESTEP'], + 'functionCall' => [Engineering\Compare::class, 'GESTEP'], 'argumentCount' => '1,2', ], 'GETPIVOTDATA' => [ @@ -993,203 +1228,208 @@ class Calculation ], 'GROWTH' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'GROWTH'], + 'functionCall' => [Statistical\Trends::class, 'GROWTH'], 'argumentCount' => '1-4', ], 'HARMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'HARMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'], 'argumentCount' => '1+', ], 'HEX2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTOBIN'], + 'functionCall' => [Engineering\ConvertHex::class, 'toBinary'], 'argumentCount' => '1,2', ], 'HEX2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTODEC'], + 'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'], 'argumentCount' => '1', ], 'HEX2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'HEXTOOCT'], + 'functionCall' => [Engineering\ConvertHex::class, 'toOctal'], 'argumentCount' => '1,2', ], 'HLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'HLOOKUP'], + 'functionCall' => [LookupRef\HLookup::class, 'lookup'], 'argumentCount' => '3,4', ], 'HOUR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'HOUROFDAY'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'], 'argumentCount' => '1', ], 'HYPERLINK' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'HYPERLINK'], + 'functionCall' => [LookupRef\Hyperlink::class, 'set'], 'argumentCount' => '1,2', 'passCellReference' => true, ], 'HYPGEOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'HYPGEOMDIST'], + 'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'], 'argumentCount' => '4', ], + 'HYPGEOM.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '5', + ], 'IF' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'statementIf'], + 'functionCall' => [Logical\Conditional::class, 'statementIf'], 'argumentCount' => '1-3', ], 'IFERROR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'IFERROR'], + 'functionCall' => [Logical\Conditional::class, 'IFERROR'], 'argumentCount' => '2', ], 'IFNA' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'IFNA'], + 'functionCall' => [Logical\Conditional::class, 'IFNA'], 'argumentCount' => '2', ], 'IFS' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Logical\Conditional::class, 'IFS'], 'argumentCount' => '2+', ], 'IMABS' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMABS'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'], 'argumentCount' => '1', ], 'IMAGINARY' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMAGINARY'], + 'functionCall' => [Engineering\Complex::class, 'IMAGINARY'], 'argumentCount' => '1', ], 'IMARGUMENT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMARGUMENT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'], 'argumentCount' => '1', ], 'IMCONJUGATE' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCONJUGATE'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'], 'argumentCount' => '1', ], 'IMCOS' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOS'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'], 'argumentCount' => '1', ], 'IMCOSH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOSH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'], 'argumentCount' => '1', ], 'IMCOT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCOT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'], 'argumentCount' => '1', ], 'IMCSC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCSC'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'], 'argumentCount' => '1', ], 'IMCSCH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMCSCH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'], 'argumentCount' => '1', ], 'IMDIV' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMDIV'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'], 'argumentCount' => '2', ], 'IMEXP' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMEXP'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'], 'argumentCount' => '1', ], 'IMLN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'], 'argumentCount' => '1', ], 'IMLOG10' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLOG10'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'], 'argumentCount' => '1', ], 'IMLOG2' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMLOG2'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'], 'argumentCount' => '1', ], 'IMPOWER' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMPOWER'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'], 'argumentCount' => '2', ], 'IMPRODUCT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMPRODUCT'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'], 'argumentCount' => '1+', ], 'IMREAL' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMREAL'], + 'functionCall' => [Engineering\Complex::class, 'IMREAL'], 'argumentCount' => '1', ], 'IMSEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSEC'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'], 'argumentCount' => '1', ], 'IMSECH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSECH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'], 'argumentCount' => '1', ], 'IMSIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSIN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'], 'argumentCount' => '1', ], 'IMSINH' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSINH'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'], 'argumentCount' => '1', ], 'IMSQRT' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSQRT'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'], 'argumentCount' => '1', ], 'IMSUB' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSUB'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'], 'argumentCount' => '2', ], 'IMSUM' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMSUM'], + 'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'], 'argumentCount' => '1+', ], 'IMTAN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'IMTAN'], + 'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'], 'argumentCount' => '1', ], 'INDEX' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'INDEX'], + 'functionCall' => [LookupRef\Matrix::class, 'index'], 'argumentCount' => '1-4', ], 'INDIRECT' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'INDIRECT'], + 'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'], 'argumentCount' => '1,2', 'passCellReference' => true, ], @@ -1200,101 +1440,113 @@ class Calculation ], 'INT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'INT'], + 'functionCall' => [MathTrig\IntClass::class, 'evaluate'], 'argumentCount' => '1', ], 'INTERCEPT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'INTERCEPT'], + 'functionCall' => [Statistical\Trends::class, 'INTERCEPT'], 'argumentCount' => '2', ], 'INTRATE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'INTRATE'], + 'functionCall' => [Financial\Securities\Rates::class, 'interest'], 'argumentCount' => '4,5', ], 'IPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'IPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'], 'argumentCount' => '4-6', ], 'IRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'IRR'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'], 'argumentCount' => '1,2', ], 'ISBLANK' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isBlank'], + 'functionCall' => [Information\Value::class, 'isBlank'], 'argumentCount' => '1', ], 'ISERR' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isErr'], + 'functionCall' => [Information\ErrorValue::class, 'isErr'], 'argumentCount' => '1', ], 'ISERROR' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isError'], + 'functionCall' => [Information\ErrorValue::class, 'isError'], 'argumentCount' => '1', ], 'ISEVEN' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isEven'], + 'functionCall' => [Information\Value::class, 'isEven'], 'argumentCount' => '1', ], 'ISFORMULA' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isFormula'], + 'functionCall' => [Information\Value::class, 'isFormula'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'ISLOGICAL' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isLogical'], + 'functionCall' => [Information\Value::class, 'isLogical'], 'argumentCount' => '1', ], 'ISNA' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isNa'], + 'functionCall' => [Information\ErrorValue::class, 'isNa'], 'argumentCount' => '1', ], 'ISNONTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isNonText'], + 'functionCall' => [Information\Value::class, 'isNonText'], 'argumentCount' => '1', ], 'ISNUMBER' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isNumber'], + 'functionCall' => [Information\Value::class, 'isNumber'], 'argumentCount' => '1', ], + 'ISO.CEILING' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '1,2', + ], 'ISODD' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isOdd'], + 'functionCall' => [Information\Value::class, 'isOdd'], 'argumentCount' => '1', ], 'ISOWEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'ISOWEEKNUM'], + 'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'], 'argumentCount' => '1', ], 'ISPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'ISPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'], 'argumentCount' => '4', ], 'ISREF' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Information\Value::class, 'isRef'], 'argumentCount' => '1', + 'passCellReference' => true, + 'passByReference' => [true], ], 'ISTEXT' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'isText'], + 'functionCall' => [Information\Value::class, 'isText'], 'argumentCount' => '1', ], + 'ISTHAIDIGIT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'JIS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], @@ -1302,107 +1554,117 @@ class Calculation ], 'KURT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'KURT'], + 'functionCall' => [Statistical\Deviations::class, 'kurtosis'], 'argumentCount' => '1+', ], 'LARGE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LARGE'], + 'functionCall' => [Statistical\Size::class, 'large'], 'argumentCount' => '2', ], 'LCM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'LCM'], + 'functionCall' => [MathTrig\Lcm::class, 'evaluate'], 'argumentCount' => '1+', ], 'LEFT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LEFT'], + 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEFTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LEFT'], + 'functionCall' => [TextData\Extract::class, 'left'], 'argumentCount' => '1,2', ], 'LEN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'STRINGLENGTH'], + 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LENB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'STRINGLENGTH'], + 'functionCall' => [TextData\Text::class, 'length'], 'argumentCount' => '1', ], 'LINEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LINEST'], + 'functionCall' => [Statistical\Trends::class, 'LINEST'], 'argumentCount' => '1-4', ], 'LN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'log', + 'functionCall' => [MathTrig\Logarithms::class, 'natural'], 'argumentCount' => '1', ], 'LOG' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'logBase'], + 'functionCall' => [MathTrig\Logarithms::class, 'withBase'], 'argumentCount' => '1,2', ], 'LOG10' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'log10', + 'functionCall' => [MathTrig\Logarithms::class, 'base10'], 'argumentCount' => '1', ], 'LOGEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGEST'], + 'functionCall' => [Statistical\Trends::class, 'LOGEST'], 'argumentCount' => '1-4', ], 'LOGINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGINV'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOGNORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'LOGNORMDIST'], + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'], + 'argumentCount' => '3', + ], + 'LOGNORM.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'], + 'argumentCount' => '4', + ], + 'LOGNORM.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'], 'argumentCount' => '3', ], 'LOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'LOOKUP'], + 'functionCall' => [LookupRef\Lookup::class, 'lookup'], 'argumentCount' => '2,3', ], 'LOWER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'LOWERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'lower'], 'argumentCount' => '1', ], 'MATCH' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'MATCH'], + 'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'], 'argumentCount' => '2,3', ], 'MAX' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAX'], + 'functionCall' => [Statistical\Maximum::class, 'max'], 'argumentCount' => '1+', ], 'MAXA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAXA'], + 'functionCall' => [Statistical\Maximum::class, 'maxA'], 'argumentCount' => '1+', ], 'MAXIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MAXIFS'], + 'functionCall' => [Statistical\Conditional::class, 'MAXIFS'], 'argumentCount' => '3+', ], 'MDETERM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MDETERM'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'], 'argumentCount' => '1', ], 'MDURATION' => [ @@ -1412,7 +1674,7 @@ class Calculation ], 'MEDIAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MEDIAN'], + 'functionCall' => [Statistical\Averages::class, 'median'], 'argumentCount' => '1+', ], 'MEDIANIF' => [ @@ -1422,97 +1684,112 @@ class Calculation ], 'MID' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'MID'], + 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIDB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'MID'], + 'functionCall' => [TextData\Extract::class, 'mid'], 'argumentCount' => '3', ], 'MIN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MIN'], + 'functionCall' => [Statistical\Minimum::class, 'min'], 'argumentCount' => '1+', ], 'MINA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MINA'], + 'functionCall' => [Statistical\Minimum::class, 'minA'], 'argumentCount' => '1+', ], 'MINIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MINIFS'], + 'functionCall' => [Statistical\Conditional::class, 'MINIFS'], 'argumentCount' => '3+', ], 'MINUTE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'MINUTE'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'], 'argumentCount' => '1', ], 'MINVERSE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MINVERSE'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'], 'argumentCount' => '1', ], 'MIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'MIRR'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'], 'argumentCount' => '3', ], 'MMULT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MMULT'], + 'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'], 'argumentCount' => '2', ], 'MOD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MOD'], + 'functionCall' => [MathTrig\Operations::class, 'mod'], 'argumentCount' => '2', ], 'MODE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MODE'], + 'functionCall' => [Statistical\Averages::class, 'mode'], + 'argumentCount' => '1+', + ], + 'MODE.MULT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'MODE.SNGL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'MODE'], + 'functionCall' => [Statistical\Averages::class, 'mode'], 'argumentCount' => '1+', ], 'MONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'MONTHOFYEAR'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'month'], 'argumentCount' => '1', ], 'MROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MROUND'], + 'functionCall' => [MathTrig\Round::class, 'multiple'], 'argumentCount' => '2', ], 'MULTINOMIAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'MULTINOMIAL'], + 'functionCall' => [MathTrig\Factorial::class, 'multinomial'], 'argumentCount' => '1+', ], + 'MUNIT' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'], + 'argumentCount' => '1', + ], 'N' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'n'], + 'functionCall' => [Information\Value::class, 'asNumber'], 'argumentCount' => '1', ], 'NA' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'NA'], + 'functionCall' => [Information\ExcelError::class, 'NA'], 'argumentCount' => '0', ], 'NEGBINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NEGBINOMDIST'], + 'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'], 'argumentCount' => '3', ], + 'NEGBINOM.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '4', + ], 'NETWORKDAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'NETWORKDAYS'], + 'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'], 'argumentCount' => '2-3', ], 'NETWORKDAYS.INTL' => [ @@ -1522,72 +1799,97 @@ class Calculation ], 'NOMINAL' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NOMINAL'], + 'functionCall' => [Financial\InterestRate::class, 'nominal'], 'argumentCount' => '2', ], 'NORMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMDIST'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], + 'argumentCount' => '4', + ], + 'NORM.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'], 'argumentCount' => '4', ], 'NORMINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMINV'], + 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], + 'argumentCount' => '3', + ], + 'NORM.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'], 'argumentCount' => '3', ], 'NORMSDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSDIST'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'], 'argumentCount' => '1', ], + 'NORM.S.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'], + 'argumentCount' => '1,2', + ], 'NORMSINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'NORMSINV'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], + 'argumentCount' => '1', + ], + 'NORM.S.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'], 'argumentCount' => '1', ], 'NOT' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'NOT'], + 'functionCall' => [Logical\Operations::class, 'NOT'], 'argumentCount' => '1', ], 'NOW' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATETIMENOW'], + 'functionCall' => [DateTimeExcel\Current::class, 'now'], 'argumentCount' => '0', ], 'NPER' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NPER'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'], 'argumentCount' => '3-5', ], 'NPV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'NPV'], + 'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'], 'argumentCount' => '2+', ], + 'NUMBERSTRING' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'NUMBERVALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'NUMBERVALUE'], + 'functionCall' => [TextData\Format::class, 'NUMBERVALUE'], 'argumentCount' => '1+', ], 'OCT2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTOBIN'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'OCT2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTODEC'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'], 'argumentCount' => '1', ], 'OCT2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, - 'functionCall' => [Engineering::class, 'OCTTOHEX'], + 'functionCall' => [Engineering\ConvertOctal::class, 'toHex'], 'argumentCount' => '1,2', ], 'ODD' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ODD'], + 'functionCall' => [MathTrig\Round::class, 'odd'], 'argumentCount' => '1', ], 'ODDFPRICE' => [ @@ -1612,39 +1914,64 @@ class Calculation ], 'OFFSET' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'OFFSET'], + 'functionCall' => [LookupRef\Offset::class, 'OFFSET'], 'argumentCount' => '3-5', 'passCellReference' => true, 'passByReference' => [true], ], 'OR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalOr'], + 'functionCall' => [Logical\Operations::class, 'logicalOr'], 'argumentCount' => '1+', ], 'PDURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PDURATION'], + 'functionCall' => [Financial\CashFlow\Single::class, 'periods'], 'argumentCount' => '3', ], 'PEARSON' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'CORREL'], + 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'PERCENTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], + 'argumentCount' => '2', + ], + 'PERCENTILE.EXC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], + 'PERCENTILE.INC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'], 'argumentCount' => '2', ], 'PERCENTRANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERCENTRANK'], + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], + 'argumentCount' => '2,3', + ], + 'PERCENTRANK.EXC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2,3', + ], + 'PERCENTRANK.INC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'], 'argumentCount' => '2,3', ], 'PERMUT' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'PERMUT'], + 'functionCall' => [Statistical\Permutations::class, 'PERMUT'], + 'argumentCount' => '2', + ], + 'PERMUTATIONA' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'], 'argumentCount' => '2', ], 'PHONETIC' => [ @@ -1652,6 +1979,11 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], + 'PHI' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '1', + ], 'PI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'pi', @@ -1659,37 +1991,42 @@ class Calculation ], 'PMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'], 'argumentCount' => '3-5', ], 'POISSON' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'POISSON'], + 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], + 'argumentCount' => '3', + ], + 'POISSON.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'], 'argumentCount' => '3', ], 'POWER' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'POWER'], + 'functionCall' => [MathTrig\Operations::class, 'power'], 'argumentCount' => '2', ], 'PPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PPMT'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'], 'argumentCount' => '4-6', ], 'PRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICE'], + 'functionCall' => [Financial\Securities\Price::class, 'price'], 'argumentCount' => '6,7', ], 'PRICEDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICEDISC'], + 'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'], 'argumentCount' => '4,5', ], 'PRICEMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PRICEMAT'], + 'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'], 'argumentCount' => '5,6', ], 'PROB' => [ @@ -1699,123 +2036,159 @@ class Calculation ], 'PRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'PRODUCT'], + 'functionCall' => [MathTrig\Operations::class, 'product'], 'argumentCount' => '1+', ], 'PROPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'PROPERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'proper'], 'argumentCount' => '1', ], 'PV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'PV'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'], 'argumentCount' => '3-5', ], 'QUARTILE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'QUARTILE'], + 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], + 'argumentCount' => '2', + ], + 'QUARTILE.EXC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], + 'QUARTILE.INC' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'], 'argumentCount' => '2', ], 'QUOTIENT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'QUOTIENT'], + 'functionCall' => [MathTrig\Operations::class, 'quotient'], 'argumentCount' => '2', ], 'RADIANS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'deg2rad', + 'functionCall' => [MathTrig\Angle::class, 'toRadians'], 'argumentCount' => '1', ], 'RAND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'RAND'], + 'functionCall' => [MathTrig\Random::class, 'rand'], 'argumentCount' => '0', ], + 'RANDARRAY' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\Random::class, 'randArray'], + 'argumentCount' => '0-5', + ], 'RANDBETWEEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'RAND'], + 'functionCall' => [MathTrig\Random::class, 'randBetween'], 'argumentCount' => '2', ], 'RANK' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'RANK'], + 'functionCall' => [Statistical\Percentiles::class, 'RANK'], + 'argumentCount' => '2,3', + ], + 'RANK.AVG' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2,3', + ], + 'RANK.EQ' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Percentiles::class, 'RANK'], 'argumentCount' => '2,3', ], 'RATE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RATE'], + 'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'], 'argumentCount' => '3-6', ], 'RECEIVED' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RECEIVED'], + 'functionCall' => [Financial\Securities\Price::class, 'received'], 'argumentCount' => '4-5', ], 'REPLACE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'REPLACE'], + 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPLACEB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'REPLACE'], + 'functionCall' => [TextData\Replace::class, 'replace'], 'argumentCount' => '4', ], 'REPT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => 'str_repeat', + 'functionCall' => [TextData\Concatenate::class, 'builtinREPT'], 'argumentCount' => '2', ], 'RIGHT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RIGHT'], + 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'RIGHTB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RIGHT'], + 'functionCall' => [TextData\Extract::class, 'right'], 'argumentCount' => '1,2', ], 'ROMAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROMAN'], + 'functionCall' => [MathTrig\Roman::class, 'evaluate'], 'argumentCount' => '1,2', ], 'ROUND' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'round', + 'functionCall' => [MathTrig\Round::class, 'round'], 'argumentCount' => '2', ], + 'ROUNDBAHTDOWN' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'ROUNDBAHTUP' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'ROUNDDOWN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROUNDDOWN'], + 'functionCall' => [MathTrig\Round::class, 'down'], 'argumentCount' => '2', ], 'ROUNDUP' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'ROUNDUP'], + 'functionCall' => [MathTrig\Round::class, 'up'], 'argumentCount' => '2', ], 'ROW' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'ROW'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'], 'argumentCount' => '-1', + 'passCellReference' => true, 'passByReference' => [true], ], 'ROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'ROWS'], + 'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'], 'argumentCount' => '1', ], 'RRI' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'RRI'], + 'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'], 'argumentCount' => '3', ], 'RSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'RSQ'], + 'functionCall' => [Statistical\Trends::class, 'RSQ'], 'argumentCount' => '2', ], 'RTD' => [ @@ -1825,273 +2198,363 @@ class Calculation ], 'SEARCH' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEARCHB' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SEARCHINSENSITIVE'], + 'functionCall' => [TextData\Search::class, 'insensitive'], 'argumentCount' => '2,3', ], 'SEC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SEC'], + 'functionCall' => [MathTrig\Trig\Secant::class, 'sec'], 'argumentCount' => '1', ], 'SECH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SECH'], + 'functionCall' => [MathTrig\Trig\Secant::class, 'sech'], 'argumentCount' => '1', ], 'SECOND' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'SECOND'], + 'functionCall' => [DateTimeExcel\TimeParts::class, 'second'], 'argumentCount' => '1', ], + 'SEQUENCE' => [ + 'category' => Category::CATEGORY_MATH_AND_TRIG, + 'functionCall' => [MathTrig\MatrixFunctions::class, 'sequence'], + 'argumentCount' => '1-4', + ], 'SERIESSUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SERIESSUM'], + 'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'], 'argumentCount' => '4', ], + 'SHEET' => [ + 'category' => Category::CATEGORY_INFORMATION, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '0,1', + ], + 'SHEETS' => [ + 'category' => Category::CATEGORY_INFORMATION, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '0,1', + ], 'SIGN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SIGN'], + 'functionCall' => [MathTrig\Sign::class, 'evaluate'], 'argumentCount' => '1', ], 'SIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sin', + 'functionCall' => [MathTrig\Trig\Sine::class, 'sin'], 'argumentCount' => '1', ], 'SINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sinh', + 'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'], 'argumentCount' => '1', ], 'SKEW' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SKEW'], + 'functionCall' => [Statistical\Deviations::class, 'skew'], + 'argumentCount' => '1+', + ], + 'SKEW.P' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1+', ], 'SLN' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'SLN'], + 'functionCall' => [Financial\Depreciation::class, 'SLN'], 'argumentCount' => '3', ], 'SLOPE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SLOPE'], + 'functionCall' => [Statistical\Trends::class, 'SLOPE'], 'argumentCount' => '2', ], 'SMALL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'SMALL'], + 'functionCall' => [Statistical\Size::class, 'small'], 'argumentCount' => '2', ], + 'SORT' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [LookupRef\Sort::class, 'sort'], + 'argumentCount' => '1-4', + ], + 'SORTBY' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [LookupRef\Sort::class, 'sortBy'], + 'argumentCount' => '2+', + ], 'SQRT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'sqrt', + 'functionCall' => [MathTrig\Sqrt::class, 'sqrt'], 'argumentCount' => '1', ], 'SQRTPI' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SQRTPI'], + 'functionCall' => [MathTrig\Sqrt::class, 'pi'], 'argumentCount' => '1', ], 'STANDARDIZE' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STANDARDIZE'], + 'functionCall' => [Statistical\Standardize::class, 'execute'], 'argumentCount' => '3', ], 'STDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEV'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.S' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEV'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'], 'argumentCount' => '1+', ], 'STDEV.P' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVP'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVA'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'], 'argumentCount' => '1+', ], 'STDEVP' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVP'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'], 'argumentCount' => '1+', ], 'STDEVPA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STDEVPA'], + 'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'], 'argumentCount' => '1+', ], 'STEYX' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'STEYX'], + 'functionCall' => [Statistical\Trends::class, 'STEYX'], 'argumentCount' => '2', ], 'SUBSTITUTE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'SUBSTITUTE'], + 'functionCall' => [TextData\Replace::class, 'substitute'], 'argumentCount' => '3,4', ], 'SUBTOTAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUBTOTAL'], + 'functionCall' => [MathTrig\Subtotal::class, 'evaluate'], 'argumentCount' => '2+', 'passCellReference' => true, ], 'SUM' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUM'], + 'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'], 'argumentCount' => '1+', ], 'SUMIF' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMIF'], + 'functionCall' => [Statistical\Conditional::class, 'SUMIF'], 'argumentCount' => '2,3', ], 'SUMIFS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMIFS'], + 'functionCall' => [Statistical\Conditional::class, 'SUMIFS'], 'argumentCount' => '3+', ], 'SUMPRODUCT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMPRODUCT'], + 'functionCall' => [MathTrig\Sum::class, 'product'], 'argumentCount' => '1+', ], 'SUMSQ' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMSQ'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'], 'argumentCount' => '1+', ], 'SUMX2MY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMX2MY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'], 'argumentCount' => '2', ], 'SUMX2PY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMX2PY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'], 'argumentCount' => '2', ], 'SUMXMY2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'SUMXMY2'], + 'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'], 'argumentCount' => '2', ], 'SWITCH' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'statementSwitch'], + 'functionCall' => [Logical\Conditional::class, 'statementSwitch'], 'argumentCount' => '3+', ], 'SYD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'SYD'], + 'functionCall' => [Financial\Depreciation::class, 'SYD'], 'argumentCount' => '4', ], 'T' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'RETURNSTRING'], + 'functionCall' => [TextData\Text::class, 'test'], 'argumentCount' => '1', ], 'TAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'tan', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'], 'argumentCount' => '1', ], 'TANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => 'tanh', + 'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'], 'argumentCount' => '1', ], 'TBILLEQ' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLEQ'], + 'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'], 'argumentCount' => '3', ], 'TBILLPRICE' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLPRICE'], + 'functionCall' => [Financial\TreasuryBill::class, 'price'], 'argumentCount' => '3', ], 'TBILLYIELD' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'TBILLYIELD'], + 'functionCall' => [Financial\TreasuryBill::class, 'yield'], 'argumentCount' => '3', ], 'TDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TDIST'], + 'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'], + 'argumentCount' => '3', + ], + 'T.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], + 'T.DIST.2T' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], + 'T.DIST.RT' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2', + ], 'TEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TEXTFORMAT'], + 'functionCall' => [TextData\Format::class, 'TEXTFORMAT'], 'argumentCount' => '2', ], 'TEXTJOIN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TEXTJOIN'], + 'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'], 'argumentCount' => '3+', ], + 'THAIDAYOFWEEK' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIDIGIT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIMONTHOFYEAR' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAINUMSOUND' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAINUMSTRING' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAISTRINGLENGTH' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], + 'THAIYEAR' => [ + 'category' => Category::CATEGORY_DATE_AND_TIME, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'TIME' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'TIME'], + 'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'], 'argumentCount' => '3', ], 'TIMEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'TIMEVALUE'], + 'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'], 'argumentCount' => '1', ], 'TINV' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TINV'], + 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], + 'argumentCount' => '2', + ], + 'T.INV' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'], + 'argumentCount' => '2', + ], + 'T.INV.2T' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'TODAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'DATENOW'], + 'functionCall' => [DateTimeExcel\Current::class, 'today'], 'argumentCount' => '0', ], 'TRANSPOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'TRANSPOSE'], + 'functionCall' => [LookupRef\Matrix::class, 'transpose'], 'argumentCount' => '1', ], 'TREND' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TREND'], + 'functionCall' => [Statistical\Trends::class, 'TREND'], 'argumentCount' => '1-4', ], 'TRIM' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'TRIMSPACES'], + 'functionCall' => [TextData\Trim::class, 'spaces'], 'argumentCount' => '1', ], 'TRIMMEAN' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'TRIMMEAN'], + 'functionCall' => [Statistical\Averages\Mean::class, 'trim'], 'argumentCount' => '2', ], 'TRUE' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'TRUE'], + 'functionCall' => [Logical\Boolean::class, 'TRUE'], 'argumentCount' => '0', ], 'TRUNC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, - 'functionCall' => [MathTrig::class, 'TRUNC'], + 'functionCall' => [MathTrig\Trunc::class, 'evaluate'], 'argumentCount' => '1,2', ], 'TTEST' => [ @@ -2099,64 +2562,79 @@ class Calculation 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4', ], + 'T.TEST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '4', + ], 'TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, - 'functionCall' => [Functions::class, 'TYPE'], + 'functionCall' => [Information\Value::class, 'type'], 'argumentCount' => '1', ], 'UNICHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'CHARACTER'], + 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'UNICODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'ASCIICODE'], + 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], + 'UNIQUE' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [LookupRef\Unique::class, 'unique'], + 'argumentCount' => '1+', + ], 'UPPER' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'UPPERCASE'], + 'functionCall' => [TextData\CaseConvert::class, 'upper'], 'argumentCount' => '1', ], 'USDOLLAR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Functions::class, 'DUMMY'], + 'functionCall' => [Financial\Dollar::class, 'format'], 'argumentCount' => '2', ], 'VALUE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, - 'functionCall' => [TextData::class, 'VALUE'], + 'functionCall' => [TextData\Format::class, 'VALUE'], 'argumentCount' => '1', ], + 'VALUETOTEXT' => [ + 'category' => Category::CATEGORY_TEXT_AND_DATA, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '?', + ], 'VAR' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARFunc'], + 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VAR.P' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARP'], + 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VAR.S' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARFunc'], + 'functionCall' => [Statistical\Variances::class, 'VAR'], 'argumentCount' => '1+', ], 'VARA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARA'], + 'functionCall' => [Statistical\Variances::class, 'VARA'], 'argumentCount' => '1+', ], 'VARP' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARP'], + 'functionCall' => [Statistical\Variances::class, 'VARP'], 'argumentCount' => '1+', ], 'VARPA' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'VARPA'], + 'functionCall' => [Statistical\Variances::class, 'VARPA'], 'argumentCount' => '1+', ], 'VDB' => [ @@ -2166,27 +2644,37 @@ class Calculation ], 'VLOOKUP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, - 'functionCall' => [LookupRef::class, 'VLOOKUP'], + 'functionCall' => [LookupRef\VLookup::class, 'lookup'], 'argumentCount' => '3,4', ], + 'WEBSERVICE' => [ + 'category' => Category::CATEGORY_WEB, + 'functionCall' => [Web\Service::class, 'webService'], + 'argumentCount' => '1', + ], 'WEEKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WEEKDAY'], + 'functionCall' => [DateTimeExcel\Week::class, 'day'], 'argumentCount' => '1,2', ], 'WEEKNUM' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WEEKNUM'], + 'functionCall' => [DateTimeExcel\Week::class, 'number'], 'argumentCount' => '1,2', ], 'WEIBULL' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'WEIBULL'], + 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], + 'argumentCount' => '4', + ], + 'WEIBULL.DIST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'], 'argumentCount' => '4', ], 'WORKDAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'WORKDAY'], + 'functionCall' => [DateTimeExcel\WorkDay::class, 'date'], 'argumentCount' => '2-3', ], 'WORKDAY.INTL' => [ @@ -2196,27 +2684,37 @@ class Calculation ], 'XIRR' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'XIRR'], + 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'], 'argumentCount' => '2,3', ], + 'XLOOKUP' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '3-6', + ], 'XNPV' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'XNPV'], + 'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'], 'argumentCount' => '3', ], + 'XMATCH' => [ + 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => [Functions::class, 'DUMMY'], + 'argumentCount' => '2,3', + ], 'XOR' => [ 'category' => Category::CATEGORY_LOGICAL, - 'functionCall' => [Logical::class, 'logicalXor'], + 'functionCall' => [Logical\Operations::class, 'logicalXor'], 'argumentCount' => '1+', ], 'YEAR' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'YEAR'], + 'functionCall' => [DateTimeExcel\DateParts::class, 'year'], 'argumentCount' => '1', ], 'YEARFRAC' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, - 'functionCall' => [DateTime::class, 'YEARFRAC'], + 'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'], 'argumentCount' => '2,3', ], 'YIELD' => [ @@ -2226,17 +2724,22 @@ class Calculation ], 'YIELDDISC' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'YIELDDISC'], + 'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'], 'argumentCount' => '4,5', ], 'YIELDMAT' => [ 'category' => Category::CATEGORY_FINANCIAL, - 'functionCall' => [Financial::class, 'YIELDMAT'], + 'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'], 'argumentCount' => '5,6', ], 'ZTEST' => [ 'category' => Category::CATEGORY_STATISTICAL, - 'functionCall' => [Statistical::class, 'ZTEST'], + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], + 'argumentCount' => '2-3', + ], + 'Z.TEST' => [ + 'category' => Category::CATEGORY_STATISTICAL, + 'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'], 'argumentCount' => '2-3', ], ]; @@ -2245,20 +2748,28 @@ class Calculation private static $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', - 'functionCall' => [__CLASS__, 'mkMatrix'], + 'functionCall' => [Internal\MakeMatrix::class, 'make'], + ], + 'NAME.ERROR' => [ + 'argumentCount' => '*', + 'functionCall' => [Functions::class, 'NAME'], + ], + 'WILDCARDMATCH' => [ + 'argumentCount' => '2', + 'functionCall' => [Internal\WildcardMatch::class, 'compare'], ], ]; - public function __construct(Spreadsheet $spreadsheet = null) + public function __construct(?Spreadsheet $spreadsheet = null) { - $this->delta = 1 * pow(10, 0 - ini_get('precision')); - $this->spreadsheet = $spreadsheet; $this->cyclicReferenceStack = new CyclicReferenceStack(); $this->debugLog = new Logger($this->cyclicReferenceStack); + $this->branchPruner = new BranchPruner($this->branchPruningEnabled); + self::$referenceHelper = ReferenceHelper::getInstance(); } - private static function loadLocales() + private static function loadLocales(): void { $localeFileDirectory = __DIR__ . '/locale/'; foreach (glob($localeFileDirectory . '*', GLOB_ONLYDIR) as $filename) { @@ -2272,12 +2783,10 @@ private static function loadLocales() /** * Get an instance of this class. * - * @param Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, - * or NULL to create a standalone claculation engine - * - * @return Calculation + * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, + * or NULL to create a standalone calculation engine */ - public static function getInstance(Spreadsheet $spreadsheet = null) + public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { $instance = $spreadsheet->getCalculationEngine(); @@ -2297,10 +2806,10 @@ public static function getInstance(Spreadsheet $spreadsheet = null) * Flush the calculation cache for any existing instance of this class * but only if a Calculation instance exists. */ - public function flushInstance() + public function flushInstance(): void { $this->clearCalculationCache(); - $this->clearBranchStore(); + $this->branchPruner->clearBranchStore(); } /** @@ -2315,8 +2824,6 @@ public function getDebugLog() /** * __clone implementation. Cloning should not be allowed in a Singleton! - * - * @throws Exception */ final public function __clone() { @@ -2328,7 +2835,7 @@ final public function __clone() * * @return string locale-specific translation of TRUE */ - public static function getTRUE() + public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } @@ -2338,7 +2845,7 @@ public static function getTRUE() * * @return string locale-specific translation of FALSE */ - public static function getFALSE() + public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } @@ -2352,9 +2859,11 @@ public static function getFALSE() */ public static function setArrayReturnType($returnType) { - if (($returnType == self::RETURN_ARRAY_AS_VALUE) || + if ( + ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || - ($returnType == self::RETURN_ARRAY_AS_ARRAY)) { + ($returnType == self::RETURN_ARRAY_AS_ARRAY) + ) { self::$returnArrayAsType = $returnType; return true; @@ -2386,18 +2895,18 @@ public function getCalculationCacheEnabled() /** * Enable/disable calculation cache. * - * @param bool $pValue + * @param bool $calculationCacheEnabled */ - public function setCalculationCacheEnabled($pValue) + public function setCalculationCacheEnabled($calculationCacheEnabled): void { - $this->calculationCacheEnabled = $pValue; + $this->calculationCacheEnabled = $calculationCacheEnabled; $this->clearCalculationCache(); } /** * Enable calculation cache. */ - public function enableCalculationCache() + public function enableCalculationCache(): void { $this->setCalculationCacheEnabled(true); } @@ -2405,7 +2914,7 @@ public function enableCalculationCache() /** * Disable calculation cache. */ - public function disableCalculationCache() + public function disableCalculationCache(): void { $this->setCalculationCacheEnabled(false); } @@ -2413,7 +2922,7 @@ public function disableCalculationCache() /** * Clear calculation cache. */ - public function clearCalculationCache() + public function clearCalculationCache(): void { $this->calculationCache = []; } @@ -2423,7 +2932,7 @@ public function clearCalculationCache() * * @param string $worksheetName */ - public function clearCalculationCacheForWorksheet($worksheetName) + public function clearCalculationCacheForWorksheet($worksheetName): void { if (isset($this->calculationCache[$worksheetName])) { unset($this->calculationCache[$worksheetName]); @@ -2436,7 +2945,7 @@ public function clearCalculationCacheForWorksheet($worksheetName) * @param string $fromWorksheetName * @param string $toWorksheetName */ - public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) + public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName): void { if (isset($this->calculationCache[$fromWorksheetName])) { $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; @@ -2447,29 +2956,24 @@ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksh /** * Enable/disable calculation cache. * - * @param bool $pValue * @param mixed $enabled */ - public function setBranchPruningEnabled($enabled) + public function setBranchPruningEnabled($enabled): void { $this->branchPruningEnabled = $enabled; + $this->branchPruner = new BranchPruner($this->branchPruningEnabled); } - public function enableBranchPruning() + public function enableBranchPruning(): void { $this->setBranchPruningEnabled(true); } - public function disableBranchPruning() + public function disableBranchPruning(): void { $this->setBranchPruningEnabled(false); } - public function clearBranchStore() - { - $this->branchStoreKeyCounter = 0; - } - /** * Get the currently defined locale code. * @@ -2480,6 +2984,21 @@ public function getLocale() return self::$localeLanguage; } + private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string + { + $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . + DIRECTORY_SEPARATOR . $file; + if (!file_exists($localeFileName)) { + // If there isn't a locale specific file, look for a language specific file + $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; + if (!file_exists($localeFileName)) { + throw new Exception('Locale file not found'); + } + } + + return $localeFileName; + } + /** * Set the locale code. * @@ -2487,7 +3006,7 @@ public function getLocale() * * @return bool */ - public function setLocale($locale) + public function setLocale(string $locale) { // Identify our locale and language $language = $locale = strtolower($locale); @@ -2497,31 +3016,30 @@ public function setLocale($locale) if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } + // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; - // Default is English, if user isn't requesting english, then read the necessary data from the locale files - if ($locale != 'en_us') { + + // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files + if ($locale !== 'en_us') { + $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale - $functionNamesFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'functions'; - if (!file_exists($functionNamesFile)) { - // If there isn't a locale specific function file, look for a language specific function file - $functionNamesFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'functions'; - if (!file_exists($functionNamesFile)) { - return false; - } + try { + $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); + } catch (Exception $e) { + return false; } + // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (strpos($localeFunction, '=') !== false) { - [$fName, $lfName] = explode('=', $localeFunction); - $fName = trim($fName); - $lfName = trim($lfName); + [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } @@ -2535,20 +3053,22 @@ public function setLocale($locale) self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } - $configFile = __DIR__ . '/locale/' . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . 'config'; - if (!file_exists($configFile)) { - $configFile = __DIR__ . '/locale/' . $language . DIRECTORY_SEPARATOR . 'config'; + try { + $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); + } catch (Exception $e) { + return false; } - if (file_exists($configFile)) { - $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); - foreach ($localeSettings as $localeSetting) { - [$localeSetting] = explode('##', $localeSetting); // Strip out comments - if (strpos($localeSetting, '=') !== false) { - [$settingName, $settingValue] = explode('=', $localeSetting); - $settingName = strtoupper(trim($settingName)); + + $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeSettings as $localeSetting) { + [$localeSetting] = explode('##', $localeSetting); // Strip out comments + if (strpos($localeSetting, '=') !== false) { + [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); + $settingName = strtoupper($settingName); + if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': - self::$localeArgumentSeparator = trim($settingValue); + self::$localeArgumentSeparator = $settingValue; break; } @@ -2567,30 +3087,28 @@ public function setLocale($locale) return false; } - /** - * @param string $fromSeparator - * @param string $toSeparator - * @param string $formula - * @param bool $inBraces - * - * @return string - */ - public static function translateSeparator($fromSeparator, $toSeparator, $formula, &$inBraces) - { + public static function translateSeparator( + string $fromSeparator, + string $toSeparator, + string $formula, + int &$inBracesLevel, + string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE, + string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE + ): string { $strlen = mb_strlen($formula); for ($i = 0; $i < $strlen; ++$i) { $chr = mb_substr($formula, $i, 1); switch ($chr) { - case '{': - $inBraces = true; + case $openBrace: + ++$inBracesLevel; break; - case '}': - $inBraces = false; + case $closeBrace: + --$inBracesLevel; break; case $fromSeparator: - if (!$inBraces) { + if ($inBracesLevel > 0) { $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } @@ -2599,59 +3117,75 @@ public static function translateSeparator($fromSeparator, $toSeparator, $formula return $formula; } - /** - * @param string[] $from - * @param string[] $to - * @param string $formula - * @param string $fromSeparator - * @param string $toSeparator - * - * @return string - */ - private static function translateFormula(array $from, array $to, $formula, $fromSeparator, $toSeparator) + private static function translateFormulaBlock( + array $from, + array $to, + string $formula, + int &$inFunctionBracesLevel, + int &$inMatrixBracesLevel, + string $fromSeparator, + string $toSeparator + ): string { + // Function Names + $formula = preg_replace($from, $to, $formula); + + // Temporarily adjust matrix separators so that they won't be confused with function arguments + $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); + $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); + // Function Argument Separators + $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel); + // Restore matrix separators + $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); + $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); + + return $formula; + } + + private static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string { - // Convert any Excel function names to the required language + // Convert any Excel function names and constant names to the required language; + // and adjust function argument separators if (self::$localeLanguage !== 'en_us') { - $inBraces = false; - // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators - if (strpos($formula, '"') !== false) { - // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded - // the formula - $temp = explode('"', $formula); + $inFunctionBracesLevel = 0; + $inMatrixBracesLevel = 0; + // If there is the possibility of separators within a quoted string, then we treat them as literals + if (strpos($formula, self::FORMULA_STRING_QUOTE) !== false) { + // So instead we skip replacing in any quoted strings by only replacing in every other array element + // after we've exploded the formula + $temp = explode(self::FORMULA_STRING_QUOTE, $formula); $i = false; foreach ($temp as &$value) { - // Only count/replace in alternating array entries + // Only adjust in alternating array entries if ($i = !$i) { - $value = preg_replace($from, $to, $value); - $value = self::translateSeparator($fromSeparator, $toSeparator, $value, $inBraces); + $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } unset($value); // Then rebuild the formula string - $formula = implode('"', $temp); + $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace - $formula = preg_replace($from, $to, $formula); - $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inBraces); + $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } return $formula; } - private static $functionReplaceFromExcel = null; + private static $functionReplaceFromExcel; - private static $functionReplaceToLocale = null; + private static $functionReplaceToLocale; public function _translateFormulaToLocale($formula) { + // Build list of function names and constants for translation if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { - self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/Ui'; + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { - self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/Ui'; + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } @@ -2665,28 +3199,35 @@ public function _translateFormulaToLocale($formula) } } - return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator); + return self::translateFormula( + self::$functionReplaceFromExcel, + self::$functionReplaceToLocale, + $formula, + ',', + self::$localeArgumentSeparator + ); } - private static $functionReplaceFromLocale = null; + private static $functionReplaceFromLocale; - private static $functionReplaceToExcel = null; + private static $functionReplaceToExcel; public function _translateFormulaToEnglish($formula) { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { - self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/Ui'; + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui'; } foreach (self::$localeBoolean as $excelBoolean) { - self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/Ui'; + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { + // @phpstan-ignore-next-line self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { @@ -2728,11 +3269,12 @@ public static function wrapResult($value) // Return Excel errors "as is" return $value; } + // Return strings wrapped in quotes - return '"' . $value . '"'; - // Convert numeric errors to NaN error + return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { - return Functions::NAN(); + // Convert numeric errors to NaN error + return Information\ExcelError::NAN(); } return $value; @@ -2748,12 +3290,12 @@ public static function wrapResult($value) public static function unwrapResult($value) { if (is_string($value)) { - if ((isset($value[0])) && ($value[0] == '"') && (substr($value, -1) == '"')) { + if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) { return substr($value, 1, -1); } // Convert numeric errors to NAN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { - return Functions::NAN(); + return Information\ExcelError::NAN(); } return $value; @@ -2763,16 +3305,14 @@ public static function unwrapResult($value) * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility. * - * @param Cell $pCell Cell to calculate - * - * @throws Exception + * @param Cell $cell Cell to calculate * * @return mixed */ - public function calculate(Cell $pCell = null) + public function calculate(?Cell $cell = null) { try { - return $this->calculateCellValue($pCell); + return $this->calculateCellValue($cell); } catch (\Exception $e) { throw new Exception($e->getMessage()); } @@ -2781,16 +3321,14 @@ public function calculate(Cell $pCell = null) /** * Calculate the value of a cell formula. * - * @param Cell $pCell Cell to calculate + * @param Cell $cell Cell to calculate * @param bool $resetLog Flag indicating whether the debug log should be reset or not * - * @throws \PhpOffice\PhpSpreadsheet\Exception - * * @return mixed */ - public function calculateCellValue(Cell $pCell = null, $resetLog = true) + public function calculateCellValue(?Cell $cell = null, $resetLog = true) { - if ($pCell === null) { + if ($cell === null) { return null; } @@ -2807,12 +3345,12 @@ public function calculateCellValue(Cell $pCell = null, $resetLog = true) // Execute the calculation for the cell formula $this->cellStack[] = [ - 'sheet' => $pCell->getWorksheet()->getTitle(), - 'cell' => $pCell->getCoordinate(), + 'sheet' => $cell->getWorksheet()->getTitle(), + 'cell' => $cell->getCoordinate(), ]; try { - $result = self::unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell)); + $result = self::unwrapResult($this->_calculateFormulaValue($cell->getValue(), $cell->getCoordinate(), $cell)); $cellAddress = array_pop($this->cellStack); $this->spreadsheet->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); } catch (\Exception $e) { @@ -2826,7 +3364,7 @@ public function calculateCellValue(Cell $pCell = null, $resetLog = true) self::$returnArrayAsType = $returnArrayAsType; $testResult = Functions::flattenArray($result); if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) { - return Functions::VALUE(); + return Information\ExcelError::VALUE(); } // If there's only a single cell in the array, then we allow it if (count($testResult) != 1) { @@ -2834,13 +3372,13 @@ public function calculateCellValue(Cell $pCell = null, $resetLog = true) $r = array_keys($result); $r = array_shift($r); if (!is_numeric($r)) { - return Functions::VALUE(); + return Information\ExcelError::VALUE(); } if (is_array($result[$r])) { $c = array_keys($result[$r]); $c = array_shift($c); if (!is_numeric($c)) { - return Functions::VALUE(); + return Information\ExcelError::VALUE(); } } } @@ -2848,10 +3386,10 @@ public function calculateCellValue(Cell $pCell = null, $resetLog = true) } self::$returnArrayAsType = $returnArrayAsType; - if ($result === null && $pCell->getWorksheet()->getSheetView()->getShowZeros()) { + if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { - return Functions::NAN(); + return Information\ExcelError::NAN(); } return $result; @@ -2878,7 +3416,7 @@ public function parseFormula($formula) } // Parse the formula and return the token stack - return $this->_parseFormula($formula); + return $this->internalParseFormula($formula); } /** @@ -2886,13 +3424,11 @@ public function parseFormula($formula) * * @param string $formula Formula to parse * @param string $cellID Address of the cell to calculate - * @param Cell $pCell Cell to calculate - * - * @throws \PhpOffice\PhpSpreadsheet\Exception + * @param Cell $cell Cell to calculate * * @return mixed */ - public function calculateFormula($formula, $cellID = null, Cell $pCell = null) + public function calculateFormula($formula, $cellID = null, ?Cell $cell = null) { // Initialise the logging settings $this->formulaError = null; @@ -2900,9 +3436,9 @@ public function calculateFormula($formula, $cellID = null, Cell $pCell = null) $this->cyclicReferenceStack->clear(); $resetCache = $this->getCalculationCacheEnabled(); - if ($this->spreadsheet !== null && $cellID === null && $pCell === null) { + if ($this->spreadsheet !== null && $cellID === null && $cell === null) { $cellID = 'A1'; - $pCell = $this->spreadsheet->getActiveSheet()->getCell($cellID); + $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID); } else { // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache @@ -2911,7 +3447,7 @@ public function calculateFormula($formula, $cellID = null, Cell $pCell = null) // Execute the calculation try { - $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell)); + $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } @@ -2925,18 +3461,15 @@ public function calculateFormula($formula, $cellID = null, Cell $pCell = null) } /** - * @param string $cellReference * @param mixed $cellValue - * - * @return bool */ - public function getValueFromCache($cellReference, &$cellValue) + public function getValueFromCache(string $cellReference, &$cellValue): bool { + $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference); // Is calculation cacheing enabled? - // Is the value present in calculation cache? - $this->debugLog->writeDebugLog('Testing cache value for cell ', $cellReference); + // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { - $this->debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache'); + $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; @@ -2951,7 +3484,7 @@ public function getValueFromCache($cellReference, &$cellValue) * @param string $cellReference * @param mixed $cellValue */ - public function saveValueToCache($cellReference, $cellValue) + public function saveValueToCache($cellReference, $cellValue): void { if ($this->calculationCacheEnabled) { $this->calculationCache[$cellReference] = $cellValue; @@ -2963,18 +3496,16 @@ public function saveValueToCache($cellReference, $cellValue) * * @param string $formula The formula to parse and calculate * @param string $cellID The ID (e.g. A3) of the cell that we are calculating - * @param Cell $pCell Cell to calculate - * - * @throws Exception + * @param Cell $cell Cell to calculate * * @return mixed */ - public function _calculateFormulaValue($formula, $cellID = null, Cell $pCell = null) + public function _calculateFormulaValue($formula, $cellID = null, ?Cell $cell = null) { $cellValue = null; // Quote-Prefixed cell values cannot be formulae, but are treated as strings - if ($pCell !== null && $pCell->getStyle()->getQuotePrefix() === true) { + if ($cell !== null && $cell->getStyle()->getQuotePrefix() === true) { return self::wrapResult((string) $formula); } @@ -2993,13 +3524,14 @@ public function _calculateFormulaValue($formula, $cellID = null, Cell $pCell = n return self::wrapResult($formula); } - $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; + $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; $wsCellReference = $wsTitle . '!' . $cellID; if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } + $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { @@ -3021,9 +3553,11 @@ public function _calculateFormulaValue($formula, $cellID = null, Cell $pCell = n } } + $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); - $cellValue = $this->processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell); + + $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell); $this->cyclicReferenceStack->pop(); // Save to calculation cache @@ -3038,8 +3572,8 @@ public function _calculateFormulaValue($formula, $cellID = null, Cell $pCell = n /** * Ensure that paired matrix operands are both matrices and of the same size. * - * @param mixed &$operand1 First matrix operand - * @param mixed &$operand2 Second matrix operand + * @param mixed $operand1 First matrix operand + * @param mixed $operand2 Second matrix operand * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. @@ -3083,7 +3617,7 @@ private static function checkMatrixOperands(&$operand1, &$operand2, $resize = 1) /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * - * @param array &$matrix matrix operand + * @param array $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ @@ -3108,14 +3642,14 @@ public static function getMatrixDimensions(array &$matrix) /** * Ensure that paired matrix operands are both matrices of the same size. * - * @param mixed &$matrix1 First matrix operand - * @param mixed &$matrix2 Second matrix operand + * @param mixed $matrix1 First matrix operand + * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ - private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) + private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Rows < $matrix1Rows) { @@ -3151,14 +3685,14 @@ private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, /** * Ensure that paired matrix operands are both matrices of the same size. * - * @param mixed &$matrix1 First matrix operand - * @param mixed &$matrix2 Second matrix operand + * @param mixed $matrix1 First matrix operand + * @param mixed $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ - private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) + private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { @@ -3223,10 +3757,12 @@ private function showValue($value) } return '{ ' . implode($rpad, $returnMatrix) . ' }'; - } elseif (is_string($value) && (trim($value, '"') == $value)) { - return '"' . $value . '"'; + } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) { + return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif (is_bool($value)) { return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; + } elseif ($value === null) { + return self::$localeBoolean['NULL']; } } @@ -3269,6 +3805,8 @@ private function showTypeDetails($value) return $typeString . ' with a value of ' . $this->showValue($value); } + + return null; } /** @@ -3278,34 +3816,34 @@ private function showTypeDetails($value) */ private function convertMatrixReferences($formula) { - static $matrixReplaceFrom = ['{', ';', '}']; + static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE]; static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))']; // Convert any Excel matrix references to the MKMATRIX() function - if (strpos($formula, '{') !== false) { + if (strpos($formula, self::FORMULA_OPEN_MATRIX_BRACE) !== false) { // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators - if (strpos($formula, '"') !== false) { + if (strpos($formula, self::FORMULA_STRING_QUOTE) !== false) { // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded // the formula - $temp = explode('"', $formula); + $temp = explode(self::FORMULA_STRING_QUOTE, $formula); // Open and Closed counts used for trapping mismatched braces in the formula $openCount = $closeCount = 0; $i = false; foreach ($temp as &$value) { // Only count/replace in alternating array entries if ($i = !$i) { - $openCount += substr_count($value, '{'); - $closeCount += substr_count($value, '}'); + $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE); + $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE); $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value); } } unset($value); // Then rebuild the formula string - $formula = implode('"', $temp); + $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace - $openCount = substr_count($formula, '{'); - $closeCount = substr_count($formula, '}'); + $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE); + $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula); } // Trap for mismatched braces and trigger an appropriate error @@ -3327,11 +3865,6 @@ private function convertMatrixReferences($formula) return $formula; } - private static function mkMatrix(...$args) - { - return $args; - } - // Binary Operators // These operators always work on two values // Array key is the operator, the value indicates whether this is a left or right associative operator @@ -3340,7 +3873,7 @@ private static function mkMatrix(...$args) '*' => 0, '/' => 0, // Multiplication and Division '+' => 0, '-' => 0, // Addition and Subtraction '&' => 0, // Concatenation - '|' => 0, ':' => 0, // Intersect and Range + '∪' => 0, '∩' => 0, ':' => 0, // Union, Intersect and Range '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, // Comparison ]; @@ -3352,8 +3885,9 @@ private static function mkMatrix(...$args) // This list includes all valid operators, whether binary (including boolean) or unary (such as %) // Array key is the operator, the value is its precedence private static $operatorPrecedence = [ - ':' => 8, // Range - '|' => 7, // Intersect + ':' => 9, // Range + '∩' => 8, // Intersect + '∪' => 7, // Union '~' => 6, // Negation '%' => 5, // Percentage '^' => 4, // Exponentiation @@ -3367,11 +3901,10 @@ private static function mkMatrix(...$args) /** * @param string $formula - * @param null|\PhpOffice\PhpSpreadsheet\Cell\Cell $pCell * - * @return bool + * @return array|false */ - private function _parseFormula($formula, Cell $pCell = null) + private function internalParseFormula($formula, ?Cell $cell = null) { if (($formula = $this->convertMatrixReferences(trim($formula))) === false) { return false; @@ -3379,108 +3912,73 @@ private function _parseFormula($formula, Cell $pCell = null) // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), // so we store the parent worksheet so that we can re-attach it when necessary - $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; + $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; - $regexpMatchString = '/^(' . self::CALCULATION_REGEXP_FUNCTION . + $regexpMatchString = '/^(' . self::CALCULATION_REGEXP_STRING . + '|' . self::CALCULATION_REGEXP_FUNCTION . '|' . self::CALCULATION_REGEXP_CELLREF . + '|' . self::CALCULATION_REGEXP_COLUMN_RANGE . + '|' . self::CALCULATION_REGEXP_ROW_RANGE . '|' . self::CALCULATION_REGEXP_NUMBER . - '|' . self::CALCULATION_REGEXP_STRING . '|' . self::CALCULATION_REGEXP_OPENBRACE . - '|' . self::CALCULATION_REGEXP_NAMEDRANGE . + '|' . self::CALCULATION_REGEXP_DEFINEDNAME . '|' . self::CALCULATION_REGEXP_ERROR . - ')/si'; + ')/sui'; // Start with initialisation $index = 0; - $stack = new Stack(); + $stack = new Stack($this->branchPruner); $output = []; $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a - // - is a negation or + is a positive operator rather than an operation + // - is a negation or + is a positive operator rather than an operation $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand - // should be null in a function call - - // IF branch pruning - // currently pending storeKey (last item of the storeKeysStack - $pendingStoreKey = null; - // stores a list of storeKeys (string[]) - $pendingStoreKeysStack = []; - $expectingConditionMap = []; // ['storeKey' => true, ...] - $expectingThenMap = []; // ['storeKey' => true, ...] - $expectingElseMap = []; // ['storeKey' => true, ...] - $parenthesisDepthMap = []; // ['storeKey' => 4, ...] + // should be null in a function call // The guts of the lexical parser // Loop through the formula extracting each operator and operand in turn while (true) { // Branch pruning: we adapt the output item to the context (it will // be used to limit its computation) - $currentCondition = null; - $currentOnlyIf = null; - $currentOnlyIfNot = null; - $previousStoreKey = null; - $pendingStoreKey = end($pendingStoreKeysStack); - - if ($this->branchPruningEnabled) { - // this is a condition ? - if (isset($expectingConditionMap[$pendingStoreKey]) && $expectingConditionMap[$pendingStoreKey]) { - $currentCondition = $pendingStoreKey; - $stackDepth = count($pendingStoreKeysStack); - if ($stackDepth > 1) { // nested if - $previousStoreKey = $pendingStoreKeysStack[$stackDepth - 2]; - } - } - if (isset($expectingThenMap[$pendingStoreKey]) && $expectingThenMap[$pendingStoreKey]) { - $currentOnlyIf = $pendingStoreKey; - } elseif (isset($previousStoreKey)) { - if (isset($expectingThenMap[$previousStoreKey]) && $expectingThenMap[$previousStoreKey]) { - $currentOnlyIf = $previousStoreKey; - } - } - if (isset($expectingElseMap[$pendingStoreKey]) && $expectingElseMap[$pendingStoreKey]) { - $currentOnlyIfNot = $pendingStoreKey; - } elseif (isset($previousStoreKey)) { - if (isset($expectingElseMap[$previousStoreKey]) && $expectingElseMap[$previousStoreKey]) { - $currentOnlyIfNot = $previousStoreKey; - } - } - } + $this->branchPruner->initialiseForLoop(); $opCharacter = $formula[$index]; // Get the first character of the value at the current index position + if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula[$index + 1]]))) { $opCharacter .= $formula[++$index]; } - // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand - $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match); + $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match); if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus? // Put a negation on the stack - $stack->push('Unary Operator', '~', null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); + $stack->push('Unary Operator', '~'); ++$index; // and drop the negation symbol } elseif ($opCharacter == '%' && $expectingOperator) { // Put a percentage on the stack - $stack->push('Unary Operator', '%', null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); + $stack->push('Unary Operator', '%'); ++$index; } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? ++$index; // Drop the redundant plus symbol - } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal + } elseif ((($opCharacter == '~') || ($opCharacter == '∩') || ($opCharacter == '∪')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde, union or intersect because they are legal return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression - } elseif ((isset(self::$operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? - while ($stack->count() > 0 && + } elseif ((isset(self::$operators[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? + while ( + $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::$operators[$o2['value']]) && - @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) { + @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) + ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } // Finally put our current operator onto the stack - $stack->push('Binary Operator', $opCharacter, null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); + $stack->push('Binary Operator', $opCharacter); ++$index; $expectingOperator = false; - } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis? + } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis? $expectingOperand = false; - while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( if ($o2 === null) { return $this->raiseFormulaError('Formula Error: Unexpected closing brace ")"'); } @@ -3490,29 +3988,19 @@ private function _parseFormula($formula, Cell $pCell = null) // Branch pruning we decrease the depth whether is it a function // call or a parenthesis - if (!empty($pendingStoreKey)) { - $parenthesisDepthMap[$pendingStoreKey] -= 1; - } + $this->branchPruner->decrementDepth(); - if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $d['value'], $matches)) { // Did this parenthesis just close a function? - if (!empty($pendingStoreKey) && $parenthesisDepthMap[$pendingStoreKey] == -1) { - // we are closing an IF( - if ($d['value'] != 'IF(') { - return $this->raiseFormulaError('Parser bug we should be in an "IF("'); - } - if ($expectingConditionMap[$pendingStoreKey]) { - return $this->raiseFormulaError('We should not be expecting a condition'); - } - $expectingThenMap[$pendingStoreKey] = false; - $expectingElseMap[$pendingStoreKey] = false; - $parenthesisDepthMap[$pendingStoreKey] -= 1; - array_pop($pendingStoreKeysStack); - unset($pendingStoreKey); + if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) { + // Did this parenthesis just close a function? + try { + $this->branchPruner->closingBrace($d['value']); + } catch (Exception $e) { + return $this->raiseFormulaError($e->getMessage()); } $functionName = $matches[1]; // Get the function name $d = $stack->pop(); - $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack) + $argumentCount = $d['value'] ?? 0; // See how many arguments there were (argument count is the next value stored on the stack) $output[] = $d; // Dump the argument count on the output $output[] = $stack->pop(); // Pop the function and push onto the output if (isset(self::$controlFunctions[$functionName])) { @@ -3526,6 +4014,7 @@ private function _parseFormula($formula, Cell $pCell = null) } // Check the argument count $argumentCountError = false; + $expectedArgumentCountString = null; if (is_numeric($expectedArgumentCount)) { if ($expectedArgumentCount < 0) { if ($argumentCount > abs($expectedArgumentCount)) { @@ -3569,22 +4058,14 @@ private function _parseFormula($formula, Cell $pCell = null) } } ++$index; - } elseif ($opCharacter == ',') { // Is this the separator for function arguments? - if (!empty($pendingStoreKey) && - $parenthesisDepthMap[$pendingStoreKey] == 0 - ) { - // We must go to the IF next argument - if ($expectingConditionMap[$pendingStoreKey]) { - $expectingConditionMap[$pendingStoreKey] = false; - $expectingThenMap[$pendingStoreKey] = true; - } elseif ($expectingThenMap[$pendingStoreKey]) { - $expectingThenMap[$pendingStoreKey] = false; - $expectingElseMap[$pendingStoreKey] = true; - } elseif ($expectingElseMap[$pendingStoreKey]) { - return $this->raiseFormulaError('Reaching fourth argument of an IF'); - } + } elseif ($opCharacter == ',') { // Is this the separator for function arguments? + try { + $this->branchPruner->argumentSeparator(); + } catch (Exception $e) { + return $this->raiseFormulaError($e->getMessage()); } - while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + + while (($o2 = $stack->pop()) && $o2['value'] !== '(') { // Pop off the stack back to the last ( if ($o2 === null) { return $this->raiseFormulaError('Formula Error: Unexpected ,'); } @@ -3593,27 +4074,32 @@ private function _parseFormula($formula, Cell $pCell = null) // If we've a comma when we're expecting an operand, then what we actually have is a null operand; // so push a null onto the stack if (($expectingOperand) || (!$expectingOperator)) { - $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; + $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => 'NULL']; } // make sure there was a function $d = $stack->last(2); - if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $d['value'], $matches)) { + if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) { + // Can we inject a dummy function at this point so that the braces at least have some context + // because at least the braces are paired up (at this stage in the formula) + // MS Excel allows this if the content is cell references; but doesn't allow actual values, + // but at this point, we can't differentiate (so allow both) return $this->raiseFormulaError('Formula Error: Unexpected ,'); } + + /** @var array $d */ $d = $stack->pop(); - $itemStoreKey = $d['storeKey'] ?? null; - $itemOnlyIf = $d['onlyIf'] ?? null; - $itemOnlyIfNot = $d['onlyIfNot'] ?? null; - $stack->push($d['type'], ++$d['value'], $d['reference'], $itemStoreKey, $itemOnlyIf, $itemOnlyIfNot); // increment the argument count - $stack->push('Brace', '(', null, $itemStoreKey, $itemOnlyIf, $itemOnlyIfNot); // put the ( back on, we'll need to pop back to it again + ++$d['value']; // increment the argument count + + $stack->pushStackItem($d); + $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again + $expectingOperator = false; $expectingOperand = true; ++$index; } elseif ($opCharacter == '(' && !$expectingOperator) { - if (!empty($pendingStoreKey)) { // Branch pruning: we go deeper - $parenthesisDepthMap[$pendingStoreKey] += 1; - } - $stack->push('Brace', '(', null, $currentCondition, $currentOnlyIf, $currentOnlyIf); + // Branch pruning: we go deeper + $this->branchPruner->incrementDepth(); + $stack->push('Brace', '(', null); ++$index; } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number? $expectingOperator = true; @@ -3621,124 +4107,193 @@ private function _parseFormula($formula, Cell $pCell = null) $val = $match[1]; $length = strlen($val); - if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $val, $matches)) { + if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) { $val = preg_replace('/\s/u', '', $val); if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function $valToUpper = strtoupper($val); - // here $matches[1] will contain values like "IF" - // and $val "IF(" - if ($this->branchPruningEnabled && ($valToUpper == 'IF(')) { // we handle a new if - $pendingStoreKey = $this->getUnusedBranchStoreKey(); - $pendingStoreKeysStack[] = $pendingStoreKey; - $expectingConditionMap[$pendingStoreKey] = true; - $parenthesisDepthMap[$pendingStoreKey] = 0; - } else { // this is not a if but we good deeper - if (!empty($pendingStoreKey) && array_key_exists($pendingStoreKey, $parenthesisDepthMap)) { - $parenthesisDepthMap[$pendingStoreKey] += 1; - } - } + } else { + $valToUpper = 'NAME.ERROR('; + } + // here $matches[1] will contain values like "IF" + // and $val "IF(" - $stack->push('Function', $valToUpper, null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); - // tests if the function is closed right after opening - $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index + $length), $amatch); - if ($ax) { - $stack->push('Operand Count for Function ' . $valToUpper . ')', 0, null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); - $expectingOperator = true; - } else { - $stack->push('Operand Count for Function ' . $valToUpper . ')', 1, null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); - $expectingOperator = false; - } - $stack->push('Brace', '('); - } else { // it's a var w/ implicit multiplication - $output[] = ['type' => 'Value', 'value' => $matches[1], 'reference' => null]; + $this->branchPruner->functionCall($valToUpper); + + $stack->push('Function', $valToUpper); + // tests if the function is closed right after opening + $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length)); + if ($ax) { + $stack->push('Operand Count for Function ' . $valToUpper . ')', 0); + $expectingOperator = true; + } else { + $stack->push('Operand Count for Function ' . $valToUpper . ')', 1); + $expectingOperator = false; } + $stack->push('Brace', '('); } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $val, $matches)) { // Watch for this case-change when modifying to allow cell references in different worksheets... // Should only be applied to the actual cell column, not the worksheet name - // If the last entry on the stack was a : operator, then we have a cell range reference $testPrevOp = $stack->last(1); - if ($testPrevOp !== null && $testPrevOp['value'] == ':') { + if ($testPrevOp !== null && $testPrevOp['value'] === ':') { // If we have a worksheet reference, then we're playing with a 3D reference - if ($matches[2] == '') { + if ($matches[2] === '') { // Otherwise, we 'inherit' the worksheet reference from the start cell reference // The start of the cell range reference should be the last entry in $output - $startCellRef = $output[count($output) - 1]['value']; - preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $startCellRef, $startMatches); - if ($startMatches[2] > '') { - $val = $startMatches[2] . '!' . $val; + $rangeStartCellRef = $output[count($output) - 1]['value']; + if ($rangeStartCellRef === ':') { + // Do we have chained range operators? + $rangeStartCellRef = $output[count($output) - 2]['value']; + } + preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); + if ($rangeStartMatches[2] > '') { + $val = $rangeStartMatches[2] . '!' . $val; } } else { - return $this->raiseFormulaError('3D Range references are not yet supported'); + $rangeStartCellRef = $output[count($output) - 1]['value']; + if ($rangeStartCellRef === ':') { + // Do we have chained range operators? + $rangeStartCellRef = $output[count($output) - 2]['value']; + } + preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches); + if ($rangeStartMatches[2] !== $matches[2]) { + return $this->raiseFormulaError('3D Range references are not yet supported'); + } } + } elseif (strpos($val, '!') === false && $pCellParent !== null) { + $worksheet = $pCellParent->getTitle(); + $val = "'{$worksheet}'!{$val}"; } - - $outputItem = $stack->getStackItem('Cell Reference', $val, $val, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); + // unescape any apostrophes or double quotes in worksheet name + $val = str_replace(["''", '""'], ["'", '"'], $val); + $outputItem = $stack->getStackItem('Cell Reference', $val, $val); $output[] = $outputItem; - } else { // it's a variable, constant, string, number or boolean + } else { // it's a variable, constant, string, number or boolean + $localeConstant = false; + $stackItemType = 'Value'; + $stackItemReference = null; + // If the last entry on the stack was a : operator, then we may have a row or column range reference $testPrevOp = $stack->last(1); if ($testPrevOp !== null && $testPrevOp['value'] === ':') { - $startRowColRef = $output[count($output) - 1]['value']; - [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); - $rangeSheetRef = $rangeWS1; - if ($rangeWS1 != '') { - $rangeWS1 .= '!'; - } - [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); - if ($rangeWS2 != '') { - $rangeWS2 .= '!'; + $stackItemType = 'Cell Reference'; + + if ( + !is_numeric($val) && + ((ctype_alpha($val) === false || strlen($val) > 3)) && + (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false) && + ($this->spreadsheet->getNamedRange($val) !== null) + ) { + $namedRange = $this->spreadsheet->getNamedRange($val); + if ($namedRange !== null) { + $stackItemType = 'Defined Name'; + $address = str_replace('$', '', $namedRange->getValue()); + $stackItemReference = $val; + if (strpos($address, ':') !== false) { + // We'll need to manipulate the stack for an actual named range rather than a named cell + $fromTo = explode(':', $address); + $to = array_pop($fromTo); + foreach ($fromTo as $from) { + $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference); + $output[] = $stack->getStackItem('Binary Operator', ':'); + } + $address = $to; + } + $val = $address; + } } else { - $rangeWS2 = $rangeWS1; + $startRowColRef = $output[count($output) - 1]['value']; + [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true); + $rangeSheetRef = $rangeWS1; + if ($rangeWS1 !== '') { + $rangeWS1 .= '!'; + } + $rangeSheetRef = trim($rangeSheetRef, "'"); + [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true); + if ($rangeWS2 !== '') { + $rangeWS2 .= '!'; + } else { + $rangeWS2 = $rangeWS1; + } + + $refSheet = $pCellParent; + if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) { + $refSheet = $pCellParent->getParent()->getSheetByName($rangeSheetRef); + } + + if (ctype_digit($val) && $val <= 1048576) { + // Row range + $stackItemType = 'Row Reference'; + /** @var int $valx */ + $valx = $val; + $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : 'XFD'; // Max 16,384 columns for Excel2007 + $val = "{$rangeWS2}{$endRowColRef}{$val}"; + } elseif (ctype_alpha($val) && strlen($val) <= 3) { + // Column range + $stackItemType = 'Column Reference'; + $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : 1048576; // Max 1,048,576 rows for Excel2007 + $val = "{$rangeWS2}{$val}{$endRowColRef}"; + } + $stackItemReference = $val; } - $refSheet = $pCellParent; - if ($pCellParent !== null && $rangeSheetRef !== $pCellParent->getTitle()) { - $refSheet = $pCellParent->getParent()->getSheetByName($rangeSheetRef); + } elseif ($opCharacter == self::FORMULA_STRING_QUOTE) { + // UnEscape any quotes within the string + $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val))); + } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { + $stackItemType = 'Constant'; + $excelConstant = trim(strtoupper($val)); + $val = self::$excelConstants[$excelConstant]; + } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { + $stackItemType = 'Constant'; + $val = self::$excelConstants[$localeConstant]; + } elseif ( + preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference) + ) { + $val = $rowRangeReference[1]; + $length = strlen($rowRangeReference[1]); + $stackItemType = 'Row Reference'; + $column = 'A'; + if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { + $column = $pCellParent->getHighestDataColumn($val); } - if ((is_int($startRowColRef)) && (ctype_digit($val)) && - ($startRowColRef <= 1048576) && ($val <= 1048576)) { - // Row range - $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007 - $output[count($output) - 1]['value'] = $rangeWS1 . 'A' . $startRowColRef; - $val = $rangeWS2 . $endRowColRef . $val; - } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) && - (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) { - // Column range - $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007 - $output[count($output) - 1]['value'] = $rangeWS1 . strtoupper($startRowColRef) . '1'; - $val = $rangeWS2 . $val . $endRowColRef; + $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}"; + $stackItemReference = $val; + } elseif ( + preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference) + ) { + $val = $columnRangeReference[1]; + $length = strlen($val); + $stackItemType = 'Column Reference'; + $row = '1'; + if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) { + $row = $pCellParent->getHighestDataRow($val); } - } - - $localeConstant = false; - if ($opCharacter == '"') { - // UnEscape any quotes within the string - $val = self::wrapResult(str_replace('""', '"', self::unwrapResult($val))); + $val = "{$val}{$row}"; + $stackItemReference = $val; + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) { + $stackItemType = 'Defined Name'; + $stackItemReference = $val; } elseif (is_numeric($val)) { if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { $val = (float) $val; } else { $val = (int) $val; } - } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { - $excelConstant = trim(strtoupper($val)); - $val = self::$excelConstants[$excelConstant]; - } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { - $val = self::$excelConstants[$localeConstant]; } - $details = $stack->getStackItem('Value', $val, null, $currentCondition, $currentOnlyIf, $currentOnlyIfNot); + + $details = $stack->getStackItem($stackItemType, $val, $stackItemReference); if ($localeConstant) { $details['localeValue'] = $localeConstant; } $output[] = $details; } $index += $length; - } elseif ($opCharacter == '$') { // absolute row or column range + } elseif ($opCharacter == '$') { // absolute row or column range ++$index; - } elseif ($opCharacter == ')') { // miscellaneous error checking + } elseif ($opCharacter == ')') { // miscellaneous error checking if ($expectingOperand) { - $output[] = ['type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null]; + $output[] = ['type' => 'Empty Argument', 'value' => self::$excelConstants['NULL'], 'reference' => 'NULL']; $expectingOperand = false; $expectingOperator = true; } else { @@ -3763,27 +4318,39 @@ private function _parseFormula($formula, Cell $pCell = null) while (($formula[$index] == "\n") || ($formula[$index] == "\r")) { ++$index; } + if ($formula[$index] == ' ') { - while ($formula[$index] == ' ') { + while ($formula[$index] === ' ') { ++$index; } + // If we're expecting an operator, but only have a space between the previous and next operands (and both are // Cell References) then we have an INTERSECTION operator - if (($expectingOperator) && (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) && - ($output[count($output) - 1]['type'] == 'Cell Reference')) { - while ($stack->count() > 0 && + if ( + ($expectingOperator) && + ( + (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/Ui', substr($formula, $index), $match)) && + ($output[count($output) - 1]['type'] === 'Cell Reference') || + (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match)) && + ($output[count($output) - 1]['type'] === 'Defined Name' || $output[count($output) - 1]['type'] === 'Value') + ) + ) { + while ( + $stack->count() > 0 && ($o2 = $stack->last()) && isset(self::$operators[$o2['value']]) && - @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) { + @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']]) + ) { $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output } - $stack->push('Binary Operator', '|'); // Put an Intersect Operator on the stack + $stack->push('Binary Operator', '∩'); // Put an Intersect Operator on the stack $expectingOperator = false; } } } - while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output + while (($op = $stack->pop()) !== null) { + // pop everything off the stack and push onto output if ((is_array($op) && $op['value'] == '(') || ($op === '(')) { return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced } @@ -3799,9 +4366,15 @@ private static function dataTestReference(&$operandData) if (($operandData['reference'] === null) && (is_array($operand))) { $rKeys = array_keys($operand); $rowKey = array_shift($rKeys); + if (is_array($operand[$rowKey]) === false) { + $operandData['value'] = $operand[$rowKey]; + + return $operand[$rowKey]; + } + $cKeys = array_keys(array_keys($operand[$rowKey])); $colKey = array_shift($cKeys); - if (ctype_upper($colKey)) { + if (ctype_upper("$colKey")) { $operandData['reference'] = $colKey . $rowKey; } } @@ -3814,31 +4387,28 @@ private static function dataTestReference(&$operandData) /** * @param mixed $tokens * @param null|string $cellID - * @param null|Cell $pCell * - * @return bool + * @return array|false */ - private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) + private function processTokenStack($tokens, $cellID = null, ?Cell $cell = null) { - if ($tokens == false) { + if ($tokens === false) { return false; } // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), // so we store the parent cell collection so that we can re-attach it when necessary - $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null; - $pCellParent = ($pCell !== null) ? $pCell->getParent() : null; - $stack = new Stack(); + $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null; + $pCellParent = ($cell !== null) ? $cell->getParent() : null; + $stack = new Stack($this->branchPruner); // Stores branches that have been pruned $fakedForBranchPruning = []; // help us to know when pruning ['branchTestId' => true/false] $branchStore = []; - // Loop through each token in turn foreach ($tokens as $tokenData) { $token = $tokenData['value']; - // Branch pruning: skip useless resolutions $storeKey = $tokenData['storeKey'] ?? null; if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) { @@ -3848,15 +4418,12 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); - $storeValue = end($wrappedItem); + $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } - if (isset($storeValue) - && ( - !$storeValueAsBool - || Functions::isError($storeValue) - || ($storeValue === 'Pruned branch') - ) + if ( + (isset($storeValue) || $tokenData['reference'] === 'NULL') + && (!$storeValueAsBool || ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is not true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) { @@ -3883,13 +4450,12 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) true : (bool) Functions::flattenSingleValue($storeValue); if (is_array($storeValue)) { $wrappedItem = end($storeValue); - $storeValue = end($wrappedItem); + $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem; } - if (isset($storeValue) - && ( - $storeValueAsBool - || Functions::isError($storeValue) - || ($storeValue === 'Pruned branch')) + + if ( + (isset($storeValue) || $tokenData['reference'] === 'NULL') + && ($storeValueAsBool || ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch')) ) { // If branching value is true, we don't need to compute if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) { @@ -3910,7 +4476,7 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } // 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 - if (isset(self::$binaryOperators[$token])) { + if (!is_numeric($token) && isset(self::$binaryOperators[$token])) { // We must have two operands, error if we don't if (($operand2Data = $stack->pop()) === null) { return $this->raiseFormulaError('Internal error - Operand value missing from stack'); @@ -3924,28 +4490,36 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) // Log what we're doing if ($token == ':') { - $this->debugLog->writeDebugLog('Evaluating Range ', $this->showValue($operand1Data['reference']), ' ', $token, ' ', $this->showValue($operand2Data['reference'])); + $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference'])); } else { - $this->debugLog->writeDebugLog('Evaluating ', $this->showValue($operand1), ' ', $token, ' ', $this->showValue($operand2)); + $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2)); } // Process the operation in the appropriate manner switch ($token) { - // Comparison (Boolean) Operators - case '>': // Greater than - case '<': // Less than - case '>=': // Greater than or Equal to - case '<=': // Less than or Equal to - case '=': // Equality - case '<>': // Inequality - $result = $this->executeBinaryComparisonOperation($cellID, $operand1, $operand2, $token, $stack); + // Comparison (Boolean) Operators + case '>': // Greater than + case '<': // Less than + case '>=': // Greater than or Equal to + case '<=': // Less than or Equal to + case '=': // Equality + case '<>': // Inequality + $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack); if (isset($storeKey)) { $branchStore[$storeKey] = $result; } break; - // Binary Operators - case ':': // Range + // Binary Operators + case ':': // Range + if ($operand1Data['type'] === 'Defined Name') { + if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false) { + $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']); + if ($definedName !== null) { + $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue()); + } + } + } if (strpos($operand1Data['reference'], '!') !== false) { [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true); } else { @@ -3957,23 +4531,25 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $sheet2 = $sheet1; } - if ($sheet1 == $sheet2) { + if (trim($sheet1, "'") === trim($sheet2, "'")) { if ($operand1Data['reference'] === null) { if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { - $operand1Data['reference'] = $pCell->getColumn() . $operand1Data['value']; + $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value']; + // @phpstan-ignore-next-line } elseif (trim($operand1Data['reference']) == '') { - $operand1Data['reference'] = $pCell->getCoordinate(); + $operand1Data['reference'] = $cell->getCoordinate(); } else { - $operand1Data['reference'] = $operand1Data['value'] . $pCell->getRow(); + $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow(); } } if ($operand2Data['reference'] === null) { if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { - $operand2Data['reference'] = $pCell->getColumn() . $operand2Data['value']; + $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value']; + // @phpstan-ignore-next-line } elseif (trim($operand2Data['reference']) == '') { - $operand2Data['reference'] = $pCell->getCoordinate(); + $operand2Data['reference'] = $cell->getCoordinate(); } else { - $operand2Data['reference'] = $operand2Data['value'] . $pCell->getRow(); + $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow(); } } @@ -3990,9 +4566,10 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } + $stack->push('Cell Reference', $cellValue, $cellRef); } else { - $stack->push('Error', Functions::REF(), null); + $stack->push('Error', Information\ExcelError::REF(), null); } break; @@ -4052,13 +4629,13 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $matrixResult = $matrix->concat($operand2); $result = $matrixResult->getArray(); } catch (\Exception $ex) { - $this->debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $this->debugLog->writeDebugLog('JAMA Matrix Exception: %s', $ex->getMessage()); $result = '#VALUE!'; } } else { - $result = '"' . str_replace('""', '"', self::unwrapResult($operand1) . self::unwrapResult($operand2)) . '"'; + $result = self::FORMULA_STRING_QUOTE . str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)) . self::FORMULA_STRING_QUOTE; } - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { @@ -4066,7 +4643,7 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } break; - case '|': // Intersect + case '∩': // Intersect $rowIntersect = array_intersect_key($operand1, $operand2); $cellIntersect = $oCol = $oRow = []; foreach (array_keys($rowIntersect) as $row) { @@ -4076,9 +4653,15 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); } } - $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($cellIntersect)); - $stack->push('Value', $cellIntersect, $cellRef); + if (count(Functions::flattenArray($cellIntersect)) === 0) { + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); + $stack->push('Error', Functions::null(), null); + } else { + $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . + Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect)); + $stack->push('Value', $cellIntersect, $cellRef); + } break; } @@ -4090,10 +4673,10 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } $arg = $arg['value']; if ($token === '~') { - $this->debugLog->writeDebugLog('Evaluating Negation of ', $this->showValue($arg)); + $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg)); $multiplier = -1; } else { - $this->debugLog->writeDebugLog('Evaluating Percentile of ', $this->showValue($arg)); + $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg)); $multiplier = 0.01; } if (is_array($arg)) { @@ -4104,10 +4687,10 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $matrixResult = $matrix1->arrayTimesEquals($multiplier); $result = $matrixResult->getArray(); } catch (\Exception $ex) { - $this->debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $this->debugLog->writeDebugLog('JAMA Matrix Exception: %s', $ex->getMessage()); $result = '#VALUE!'; } - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); $stack->push('Value', $result); if (isset($storeKey)) { $branchStore[$storeKey] = $result; @@ -4115,12 +4698,13 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } else { $this->executeNumericBinaryOperation($multiplier, $arg, '*', 'arrayTimesEquals', $stack); } - } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token, $matches)) { + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) { $cellRef = null; + if (isset($matches[8])) { - if ($pCell === null) { + if ($cell === null) { // We can't access the range, so return a REF error - $cellValue = Functions::REF(); + $cellValue = Information\ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7] . ':' . $matches[9] . $matches[10]; if ($matches[2] > '') { @@ -4130,27 +4714,27 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) return $this->raiseFormulaError('Unable to access External Workbook'); } $matches[2] = trim($matches[2], "\"'"); - $this->debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]); + $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } - $this->debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); + $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { - $this->debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet'); + $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef); if ($pCellParent !== null) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } - $this->debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->showTypeDetails($cellValue)); + $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } else { - if ($pCell === null) { - // We can't access the cell, so return a REF error - $cellValue = Functions::REF(); + if ($cell === null) { + // We can't access the cell, so return a REF error + $cellValue = Information\ExcelError::REF(); } else { $cellRef = $matches[6] . $matches[7]; if ($matches[2] > '') { @@ -4159,49 +4743,54 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) // It's a Reference to an external spreadsheet (not currently supported) return $this->raiseFormulaError('Unable to access External Workbook'); } - $this->debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]); + $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]); if ($pCellParent !== null) { $cellSheet = $this->spreadsheet->getSheetByName($matches[2]); if ($cellSheet && $cellSheet->cellExists($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false); - $pCell->attach($pCellParent); + $cell->attach($pCellParent); } else { + $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef; $cellValue = null; } } else { return $this->raiseFormulaError('Unable to access Cell Reference'); } - $this->debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); + $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue)); } else { - $this->debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet'); + $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef); if ($pCellParent->has($cellRef)) { $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); - $pCell->attach($pCellParent); + $cell->attach($pCellParent); } else { $cellValue = null; } - $this->debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->showTypeDetails($cellValue)); + $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue)); } } } - $stack->push('Value', $cellValue, $cellRef); + + $stack->push('Cell Value', $cellValue, $cellRef); if (isset($storeKey)) { $branchStore[$storeKey] = $cellValue; } // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on - } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/i', $token, $matches)) { + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) { if ($pCellParent) { - $pCell->attach($pCellParent); + $cell->attach($pCellParent); } $functionName = $matches[1]; $argCount = $stack->pop(); $argCount = $argCount['value']; - if ($functionName != 'MKMATRIX') { - $this->debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); + if ($functionName !== 'MKMATRIX') { + $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's')); } if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function + $passByReference = false; + $passCellReference = false; + $functionCall = null; if (isset(self::$phpSpreadsheetFunctions[$functionName])) { $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall']; $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']); @@ -4211,28 +4800,33 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); } + // get the arguments for this function $args = $argArrayVals = []; + $emptyArguments = []; for ($i = 0; $i < $argCount; ++$i) { $arg = $stack->pop(); $a = $argCount - $i - 1; - if (($passByReference) && + if ( + ($passByReference) && (isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) && - (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) { + (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a]) + ) { if ($arg['reference'] === null) { $args[] = $cellID; - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($cellID); } } else { $args[] = $arg['reference']; - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['reference']); } } } else { + $emptyArguments[] = ($arg['type'] === 'Empty Argument'); $args[] = self::unwrapResult($arg['value']); - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { $argArrayVals[] = $this->showValue($arg['value']); } } @@ -4240,21 +4834,26 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) // Reverse the order of the arguments krsort($args); + krsort($emptyArguments); + + if ($argCount > 0) { + $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments); + } if (($passByReference) && ($argCount == 0)) { $args[] = $cellID; $argArrayVals[] = $this->showValue($cellID); } - if ($functionName != 'MKMATRIX') { + if ($functionName !== 'MKMATRIX') { if ($this->debugLog->getWriteDebugLog()) { krsort($argArrayVals); - $this->debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)), ' )'); + $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals))); } } // Process the argument with the appropriate function call - $args = $this->addCellReference($args, $passCellReference, $functionCall, $pCell); + $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell); if (!is_array($functionCall)) { foreach ($args as &$arg) { @@ -4265,8 +4864,8 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) $result = call_user_func_array($functionCall, $args); - if ($functionName != 'MKMATRIX') { - $this->debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result)); + if ($functionName !== 'MKMATRIX') { + $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result)); } $stack->push('Value', self::wrapResult($result)); if (isset($storeKey)) { @@ -4275,32 +4874,37 @@ private function processTokenStack($tokens, $cellID = null, Cell $pCell = null) } } else { // if the token is a number, boolean, string or an Excel error, push it onto the stack - if (isset(self::$excelConstants[strtoupper($token)])) { + if (isset(self::$excelConstants[strtoupper($token ?? '')])) { $excelConstant = strtoupper($token); $stack->push('Constant Value', self::$excelConstants[$excelConstant]); if (isset($storeKey)) { $branchStore[$storeKey] = self::$excelConstants[$excelConstant]; } - $this->debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant])); - } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == '"') || ($token[0] == '#')) { - $stack->push('Value', $token); + $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::$excelConstants[$excelConstant])); + } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { + $stack->push($tokenData['type'], $token, $tokenData['reference']); if (isset($storeKey)) { $branchStore[$storeKey] = $token; } - // if the token is a named range, push the named range name onto the stack - } elseif (preg_match('/^' . self::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $token, $matches)) { - $namedRange = $matches[6]; - $this->debugLog->writeDebugLog('Evaluating Named Range ', $namedRange); - - $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellWorksheet : null), false); - $pCell->attach($pCellParent); - $this->debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->showTypeDetails($cellValue)); - $stack->push('Named Range', $cellValue, $namedRange); + // if the token is a named range or formula, evaluate it and push the result onto the stack + } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) { + $definedName = $matches[6]; + if ($cell === null || $pCellWorksheet === null) { + return $this->raiseFormulaError("undefined name '$token'"); + } + + $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName); + $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet); + if ($namedRange === null) { + return $this->raiseFormulaError("undefined name '$definedName'"); + } + + $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack); if (isset($storeKey)) { - $branchStore[$storeKey] = $cellValue; + $branchStore[$storeKey] = $result; } } else { - return $this->raiseFormulaError("undefined variable '$token'"); + return $this->raiseFormulaError("undefined name '$token'"); } } } @@ -4327,7 +4931,7 @@ private function validateBinaryOperand(&$operand, &$stack) if (is_string($operand)) { // We only need special validations for the operand if it is a string // Start by stripping off the quotation marks we use to identify true excel string values internally - if ($operand > '' && $operand[0] == '"') { + if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) { $operand = self::unwrapResult($operand); } // If the string is a numeric value, we treat it as a numeric, so no further testing @@ -4335,13 +4939,13 @@ private function validateBinaryOperand(&$operand, &$stack) // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations if ($operand > '' && $operand[0] == '#') { $stack->push('Value', $operand); - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand)); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand)); return false; } elseif (!Shared\StringHelper::convertToNumberIfFraction($operand)) { // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations - $stack->push('Value', '#VALUE!'); - $this->debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!')); + $stack->push('Error', '#VALUE!'); + $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!')); return false; } @@ -4353,157 +4957,74 @@ private function validateBinaryOperand(&$operand, &$stack) } /** - * @param null|string $cellID * @param mixed $operand1 * @param mixed $operand2 * @param string $operation - * @param Stack $stack - * @param bool $recursingArrays * - * @return mixed + * @return array */ - private function executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, Stack &$stack, $recursingArrays = false) + private function executeArrayComparison($operand1, $operand2, $operation, Stack &$stack, bool $recursingArrays) { - // If we're dealing with matrix operations, we want a matrix result - if ((is_array($operand1)) || (is_array($operand2))) { - $result = []; - if ((is_array($operand1)) && (!is_array($operand2))) { - foreach ($operand1 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2)); - $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack); - $r = $stack->pop(); - $result[$x] = $r['value']; - } - } elseif ((!is_array($operand1)) && (is_array($operand2))) { - foreach ($operand2 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData)); - $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack); - $r = $stack->pop(); - $result[$x] = $r['value']; - } - } else { - if (!$recursingArrays) { - self::checkMatrixOperands($operand1, $operand2, 2); - } - foreach ($operand1 as $x => $operandData) { - $this->debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x])); - $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true); - $r = $stack->pop(); - $result[$x] = $r['value']; - } + $result = []; + if (!is_array($operand2)) { + // Operand 1 is an array, Operand 2 is a scalar + foreach ($operand1 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2)); + $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; } - // Log the result details - $this->debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result)); - // And push the result onto the stack - $stack->push('Array', $result); - - return $result; - } - - // Simple validate the two operands if they are string values - if (is_string($operand1) && $operand1 > '' && $operand1[0] == '"') { - $operand1 = self::unwrapResult($operand1); - } - if (is_string($operand2) && $operand2 > '' && $operand2[0] == '"') { - $operand2 = self::unwrapResult($operand2); - } - - // Use case insensitive comparaison if not OpenOffice mode - if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { - if (is_string($operand1)) { - $operand1 = strtoupper($operand1); + } elseif (!is_array($operand1)) { + // Operand 1 is a scalar, Operand 2 is an array + foreach ($operand2 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData)); + $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; } - if (is_string($operand2)) { - $operand2 = strtoupper($operand2); + } else { + // Operand 1 and Operand 2 are both arrays + if (!$recursingArrays) { + self::checkMatrixOperands($operand1, $operand2, 2); + } + foreach ($operand1 as $x => $operandData) { + $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x])); + $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true); + $r = $stack->pop(); + $result[$x] = $r['value']; } } - - $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE; - - // execute the necessary operation - switch ($operation) { - // Greater than - case '>': - if ($useLowercaseFirstComparison) { - $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0; - } else { - $result = ($operand1 > $operand2); - } - - break; - // Less than - case '<': - if ($useLowercaseFirstComparison) { - $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0; - } else { - $result = ($operand1 < $operand2); - } - - break; - // Equality - case '=': - if (is_numeric($operand1) && is_numeric($operand2)) { - $result = (abs($operand1 - $operand2) < $this->delta); - } else { - $result = strcmp($operand1, $operand2) == 0; - } - - break; - // Greater than or equal - case '>=': - if (is_numeric($operand1) && is_numeric($operand2)) { - $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 > $operand2)); - } elseif ($useLowercaseFirstComparison) { - $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0; - } else { - $result = strcmp($operand1, $operand2) >= 0; - } - - break; - // Less than or equal - case '<=': - if (is_numeric($operand1) && is_numeric($operand2)) { - $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 < $operand2)); - } elseif ($useLowercaseFirstComparison) { - $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0; - } else { - $result = strcmp($operand1, $operand2) <= 0; - } - - break; - // Inequality - case '<>': - if (is_numeric($operand1) && is_numeric($operand2)) { - $result = (abs($operand1 - $operand2) > 1E-14); - } else { - $result = strcmp($operand1, $operand2) != 0; - } - - break; - } - // Log the result details - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack - $stack->push('Value', $result); + $stack->push('Array', $result); return $result; } /** - * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters. - * - * @param string $str1 First string value for the comparison - * @param string $str2 Second string value for the comparison + * @param mixed $operand1 + * @param mixed $operand2 + * @param string $operation + * @param bool $recursingArrays * - * @return int + * @return mixed */ - private function strcmpLowercaseFirst($str1, $str2) + private function executeBinaryComparisonOperation($operand1, $operand2, $operation, Stack &$stack, $recursingArrays = false) { - $inversedStr1 = Shared\StringHelper::strCaseReverse($str1); - $inversedStr2 = Shared\StringHelper::strCaseReverse($str2); + // If we're dealing with matrix operations, we want a matrix result + if ((is_array($operand1)) || (is_array($operand2))) { + return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays); + } - return strcmp($inversedStr1, $inversedStr2); + $result = BinaryComparison::compare($operand1, $operand2, $operation); + + // Log the result details + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Value', $result); + + return $result; } /** @@ -4539,14 +5060,16 @@ private function executeNumericBinaryOperation($operand1, $operand2, $operation, $matrixResult = $matrix->$matrixFunction($operand2); $result = $matrixResult->getArray(); } catch (\Exception $ex) { - $this->debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $this->debugLog->writeDebugLog('JAMA Matrix Exception: %s', $ex->getMessage()); $result = '#VALUE!'; } } else { - if ((Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) && + if ( + (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) && ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1) > 0) || - (is_string($operand2) && !is_numeric($operand2) && strlen($operand2) > 0))) { - $result = Functions::VALUE(); + (is_string($operand2) && !is_numeric($operand2) && strlen($operand2) > 0)) + ) { + $result = Information\ExcelError::VALUE(); } else { // If we're dealing with non-matrix operations, execute the necessary operation switch ($operation) { @@ -4569,40 +5092,50 @@ private function executeNumericBinaryOperation($operand1, $operand2, $operation, case '/': if ($operand2 == 0) { // Trap for Divide by Zero error - $stack->push('Value', '#DIV/0!'); - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails('#DIV/0!')); + $stack->push('Error', ExcelError::DIV0()); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0())); return false; } - $result = $operand1 / $operand2; + $result = $operand1 / $operand2; break; // Power case '^': - $result = pow($operand1, $operand2); + $result = $operand1 ** $operand2; break; + + default: + throw new Exception('Unsupported numeric binary operation'); } } } // Log the result details - $this->debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result)); // And push the result onto the stack $stack->push('Value', $result); return $result; } - // trigger an error, but nicely, if need be - protected function raiseFormulaError($errorMessage) + /** + * Trigger an error, but nicely, if need be. + * + * @return false + */ + protected function raiseFormulaError(string $errorMessage) { $this->formulaError = $errorMessage; $this->cyclicReferenceStack->clear(); if (!$this->suppressFormulaErrors) { throw new Exception($errorMessage); } - trigger_error($errorMessage, E_USER_ERROR); + + if (strlen($errorMessage) > 0) { + trigger_error($errorMessage, E_USER_ERROR); + } return false; } @@ -4610,34 +5143,35 @@ protected function raiseFormulaError($errorMessage) /** * Extract range values. * - * @param string &$pRange String based range representation - * @param Worksheet $pSheet Worksheet + * @param string $range String based range representation + * @param Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ - public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) + public function extractCellRange(&$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; - if ($pSheet !== null) { - $pSheetName = $pSheet->getTitle(); - if (strpos($pRange, '!') !== false) { - [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); - $pSheet = $this->spreadsheet->getSheetByName($pSheetName); + if ($worksheet !== null) { + $worksheetName = $worksheet->getTitle(); + + if (strpos($range, '!') !== false) { + [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Extract range - $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); - $pRange = $pSheetName . '!' . $pRange; + $aReferences = Coordinate::extractAllCellReferencesInRange($range); + $range = "'" . $worksheetName . "'" . '!' . $range; if (!isset($aReferences[1])) { $currentCol = ''; $currentRow = 0; // Single cell in range sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($aReferences[0])) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + if ($worksheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -4648,8 +5182,8 @@ public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = null, $res $currentRow = 0; // Extract range sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); - if ($pSheet->cellExists($reference)) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + if ($worksheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -4663,47 +5197,46 @@ public function extractCellRange(&$pRange = 'A1', Worksheet $pSheet = null, $res /** * Extract range values. * - * @param string &$pRange String based range representation - * @param Worksheet $pSheet Worksheet + * @param string $range String based range representation + * @param null|Worksheet $worksheet Worksheet * @param bool $resetLog Flag indicating whether calculation log should be reset or not * * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. */ - public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = null, $resetLog = true) + public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, $resetLog = true) { // Return value $returnValue = []; - if ($pSheet !== null) { - $pSheetName = $pSheet->getTitle(); - if (strpos($pRange, '!') !== false) { - [$pSheetName, $pRange] = Worksheet::extractSheetTitle($pRange, true); - $pSheet = $this->spreadsheet->getSheetByName($pSheetName); + if ($worksheet !== null) { + if (strpos($range, '!') !== false) { + [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); } // Named range? - $namedRange = NamedRange::resolveRange($pRange, $pSheet); - if ($namedRange !== null) { - $pSheet = $namedRange->getWorksheet(); - $pRange = $namedRange->getRange(); - $splitRange = Coordinate::splitRange($pRange); - // Convert row and column references - if (ctype_alpha($splitRange[0][0])) { - $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow(); - } elseif (ctype_digit($splitRange[0][0])) { - $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; - } - } else { - return Functions::REF(); + $namedRange = DefinedName::resolveName($range, $worksheet); + if ($namedRange === null) { + return Information\ExcelError::REF(); + } + + $worksheet = $namedRange->getWorksheet(); + $range = $namedRange->getValue(); + $splitRange = Coordinate::splitRange($range); + // Convert row and column references + if (ctype_alpha($splitRange[0][0])) { + $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow(); + } elseif (ctype_digit($splitRange[0][0])) { + $range = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; } // Extract range - $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); + $aReferences = Coordinate::extractAllCellReferencesInRange($range); if (!isset($aReferences[1])) { // Single cell (or single column or row) in range [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]); - if ($pSheet->cellExists($aReferences[0])) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + if ($worksheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -4712,8 +5245,8 @@ public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = null, $re foreach ($aReferences as $reference) { // Extract range [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference); - if ($pSheet->cellExists($reference)) { - $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + if ($worksheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog); } else { $returnValue[$currentRow][$currentCol] = null; } @@ -4727,24 +5260,22 @@ public function extractNamedRange(&$pRange = 'A1', Worksheet $pSheet = null, $re /** * Is a specific function implemented? * - * @param string $pFunction Function Name + * @param string $function Function Name * * @return bool */ - public function isImplemented($pFunction) + public function isImplemented($function) { - $pFunction = strtoupper($pFunction); - $notImplemented = !isset(self::$phpSpreadsheetFunctions[$pFunction]) || (is_array(self::$phpSpreadsheetFunctions[$pFunction]['functionCall']) && self::$phpSpreadsheetFunctions[$pFunction]['functionCall'][1] === 'DUMMY'); + $function = strtoupper($function); + $notImplemented = !isset(self::$phpSpreadsheetFunctions[$function]) || (is_array(self::$phpSpreadsheetFunctions[$function]['functionCall']) && self::$phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY'); return !$notImplemented; } /** * Get a list of all implemented functions as an array of function objects. - * - * @return array of Category */ - public function getFunctions() + public function getFunctions(): array { return self::$phpSpreadsheetFunctions; } @@ -4766,44 +5297,85 @@ public function getImplementedFunctionNames() return $returnValue; } + private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array + { + $reflector = new ReflectionMethod(implode('::', $functionCall)); + $methodArguments = $reflector->getParameters(); + + if (count($methodArguments) > 0) { + // Apply any defaults for empty argument values + foreach ($emptyArguments as $argumentId => $isArgumentEmpty) { + if ($isArgumentEmpty === true) { + $reflectedArgumentId = count($args) - (int) $argumentId - 1; + if ( + !array_key_exists($reflectedArgumentId, $methodArguments) || + $methodArguments[$reflectedArgumentId]->isVariadic() + ) { + break; + } + + $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]); + } + } + } + + return $args; + } + + /** + * @return null|mixed + */ + private function getArgumentDefaultValue(ReflectionParameter $methodArgument) + { + $defaultValue = null; + + if ($methodArgument->isDefaultValueAvailable()) { + $defaultValue = $methodArgument->getDefaultValue(); + if ($methodArgument->isDefaultValueConstant()) { + $constantName = $methodArgument->getDefaultValueConstantName() ?? ''; + // read constant value + if (strpos($constantName, '::') !== false) { + [$className, $constantName] = explode('::', $constantName); + $constantReflector = new ReflectionClassConstant($className, $constantName); + + return $constantReflector->getValue(); + } + + return constant($constantName); + } + } + + return $defaultValue; + } + /** * Add cell reference if needed while making sure that it is the last argument. * - * @param array $args * @param bool $passCellReference * @param array|string $functionCall - * @param null|Cell $pCell * * @return array */ - private function addCellReference(array $args, $passCellReference, $functionCall, Cell $pCell = null) + private function addCellReference(array $args, $passCellReference, $functionCall, ?Cell $cell = null) { if ($passCellReference) { if (is_array($functionCall)) { $className = $functionCall[0]; $methodName = $functionCall[1]; - $reflectionMethod = new \ReflectionMethod($className, $methodName); + $reflectionMethod = new ReflectionMethod($className, $methodName); $argumentCount = count($reflectionMethod->getParameters()); while (count($args) < $argumentCount - 1) { $args[] = null; } } - $args[] = $pCell; + $args[] = $cell; } return $args; } - private function getUnusedBranchStoreKey() - { - $storeKeyValue = 'storeKey-' . $this->branchStoreKeyCounter; - ++$this->branchStoreKeyCounter; - - return $storeKeyValue; - } - private function getTokensAsString($tokens) { $tokensStr = array_map(function ($token) { @@ -4817,4 +5389,57 @@ private function getTokensAsString($tokens) return '[ ' . implode(' | ', $tokensStr) . ' ]'; } + + /** + * @return mixed|string + */ + private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack) + { + $definedNameScope = $namedRange->getScope(); + if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet) { + // The defined name isn't in our current scope, so #REF + $result = Information\ExcelError::REF(); + $stack->push('Error', $result, $namedRange->getName()); + + return $result; + } + + $definedNameValue = $namedRange->getValue(); + $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range'; + $definedNameWorksheet = $namedRange->getWorksheet(); + + if ($definedNameValue[0] !== '=') { + $definedNameValue = '=' . $definedNameValue; + } + + $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue); + + $recursiveCalculationCell = ($definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet) + ? $definedNameWorksheet->getCell('A1') + : $cell; + $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate(); + + // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns + $definedNameValue = self::$referenceHelper->updateFormulaReferencesAnyWorksheet( + $definedNameValue, + Coordinate::columnIndexFromString($cell->getColumn()) - 1, + $cell->getRow() - 1 + ); + + $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue); + + $recursiveCalculator = new self($this->spreadsheet); + $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog()); + $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog()); + $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell); + + if ($this->getDebugLog()->getWriteDebugLog()) { + $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3)); + $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result)); + } + + $stack->push('Defined Name', $result, $namedRange->getName()); + + return $result; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php index 7574cb47..96bb72ad 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Category.php @@ -16,4 +16,5 @@ abstract class Category const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; const CATEGORY_STATISTICAL = 'Statistical'; const CATEGORY_TEXT_AND_DATA = 'Text and Data'; + const CATEGORY_WEB = 'Web'; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php index d31b00dd..65031674 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database.php @@ -2,126 +2,11 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +/** + * @deprecated 1.17.0 + */ class Database { - /** - * fieldExtract. - * - * Extracts the column ID to use for the data field. - * - * @param mixed[] $database The range of cells that makes up the list or database. - * A database is a list of related data in which rows of related - * information are records, and columns of data are fields. The - * first row of the list contains labels for each column. - * @param mixed $field Indicates which column is used in the function. Enter the - * column label enclosed between double quotation marks, such as - * "Age" or "Yield," or a number (without quotation marks) that - * represents the position of the column within the list: 1 for - * the first column, 2 for the second column, and so on. - * - * @return null|string - */ - private static function fieldExtract($database, $field) - { - $field = strtoupper(Functions::flattenSingleValue($field)); - $fieldNames = array_map('strtoupper', array_shift($database)); - - if (is_numeric($field)) { - $keys = array_keys($fieldNames); - - return $keys[$field - 1]; - } - $key = array_search($field, $fieldNames); - - return ($key) ? $key : null; - } - - /** - * filter. - * - * Parses the selection criteria, extracts the database rows that match those criteria, and - * returns that subset of rows. - * - * @param mixed[] $database The range of cells that makes up the list or database. - * A database is a list of related data in which rows of related - * information are records, and columns of data are fields. The - * first row of the list contains labels for each column. - * @param mixed[] $criteria The range of cells that contains the conditions you specify. - * You can use any range for the criteria argument, as long as it - * includes at least one column label and at least one cell below - * the column label in which you specify a condition for the - * column. - * - * @return array of mixed - */ - private static function filter($database, $criteria) - { - $fieldNames = array_shift($database); - $criteriaNames = array_shift($criteria); - - // Convert the criteria into a set of AND/OR conditions with [:placeholders] - $testConditions = $testValues = []; - $testConditionsCount = 0; - foreach ($criteriaNames as $key => $criteriaName) { - $testCondition = []; - $testConditionCount = 0; - foreach ($criteria as $row => $criterion) { - if ($criterion[$key] > '') { - $testCondition[] = '[:' . $criteriaName . ']' . Functions::ifCondition($criterion[$key]); - ++$testConditionCount; - } - } - if ($testConditionCount > 1) { - $testConditions[] = 'OR(' . implode(',', $testCondition) . ')'; - ++$testConditionsCount; - } elseif ($testConditionCount == 1) { - $testConditions[] = $testCondition[0]; - ++$testConditionsCount; - } - } - - if ($testConditionsCount > 1) { - $testConditionSet = 'AND(' . implode(',', $testConditions) . ')'; - } elseif ($testConditionsCount == 1) { - $testConditionSet = $testConditions[0]; - } - - // Loop through each row of the database - foreach ($database as $dataRow => $dataValues) { - // Substitute actual values from the database row for our [:placeholders] - $testConditionList = $testConditionSet; - foreach ($criteriaNames as $key => $criteriaName) { - $k = array_search($criteriaName, $fieldNames); - if (isset($dataValues[$k])) { - $dataValue = $dataValues[$k]; - $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; - $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList); - } - } - // evaluate the criteria against the row data - $result = Calculation::getInstance()->_calculateFormulaValue('=' . $testConditionList); - // If the row failed to meet the criteria, remove it from the database - if (!$result) { - unset($database[$dataRow]); - } - } - - return $database; - } - - private static function getFilteredColumn($database, $field, $criteria) - { - // reduce the database to a set of rows that match all the criteria - $database = self::filter($database, $criteria); - // extract an array of values for the requested column - $colData = []; - foreach ($database as $row) { - $colData[] = $row[$field]; - } - - return $colData; - } - /** * DAVERAGE. * @@ -130,7 +15,10 @@ private static function getFilteredColumn($database, $field, $criteria) * Excel Function: * DAVERAGE(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DAverage::evaluate() + * Use the evaluate() method in the Database\DAverage class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -147,19 +35,11 @@ private static function getFilteredColumn($database, $field, $criteria) * the column label in which you specify a condition for the * column. * - * @return float|string + * @return null|float|string */ public static function DAVERAGE($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::AVERAGE( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DAverage::evaluate($database, $field, $criteria); } /** @@ -171,16 +51,16 @@ public static function DAVERAGE($database, $field, $criteria) * Excel Function: * DCOUNT(database,[field],criteria) * - * Excel Function: - * DAVERAGE(database,field,criteria) + * @Deprecated 1.17.0 * - * @category Database Functions + * @see Database\DCount::evaluate() + * Use the evaluate() method in the Database\DCount class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. - * @param int|string $field Indicates which column is used in the function. Enter the + * @param null|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for @@ -198,15 +78,7 @@ public static function DAVERAGE($database, $field, $criteria) */ public static function DCOUNT($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::COUNT( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DCount::evaluate($database, $field, $criteria); } /** @@ -217,13 +89,16 @@ public static function DCOUNT($database, $field, $criteria) * Excel Function: * DCOUNTA(database,[field],criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DCountA::evaluate() + * Use the evaluate() method in the Database\DCountA class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related * information are records, and columns of data are fields. The * first row of the list contains labels for each column. - * @param int|string $field Indicates which column is used in the function. Enter the + * @param null|int|string $field Indicates which column is used in the function. Enter the * column label enclosed between double quotation marks, such as * "Age" or "Yield," or a number (without quotation marks) that * represents the position of the column within the list: 1 for @@ -235,29 +110,10 @@ public static function DCOUNT($database, $field, $criteria) * column. * * @return int - * - * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the - * database that match the criteria. */ public static function DCOUNTA($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // reduce the database to a set of rows that match all the criteria - $database = self::filter($database, $criteria); - // extract an array of values for the requested column - $colData = []; - foreach ($database as $row) { - $colData[] = $row[$field]; - } - - // Return - return Statistical::COUNTA( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DCountA::evaluate($database, $field, $criteria); } /** @@ -269,7 +125,10 @@ public static function DCOUNTA($database, $field, $criteria) * Excel Function: * DGET(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DGet::evaluate() + * Use the evaluate() method in the Database\DGet class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -290,18 +149,7 @@ public static function DCOUNTA($database, $field, $criteria) */ public static function DGET($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - $colData = self::getFilteredColumn($database, $field, $criteria); - if (count($colData) > 1) { - return Functions::NAN(); - } - - return $colData[0]; + return Database\DGet::evaluate($database, $field, $criteria); } /** @@ -313,7 +161,10 @@ public static function DGET($database, $field, $criteria) * Excel Function: * DMAX(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DMax::evaluate() + * Use the evaluate() method in the Database\DMax class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -334,15 +185,7 @@ public static function DGET($database, $field, $criteria) */ public static function DMAX($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::MAX( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DMax::evaluate($database, $field, $criteria); } /** @@ -354,7 +197,10 @@ public static function DMAX($database, $field, $criteria) * Excel Function: * DMIN(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DMin::evaluate() + * Use the evaluate() method in the Database\DMin class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -375,15 +221,7 @@ public static function DMAX($database, $field, $criteria) */ public static function DMIN($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::MIN( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DMin::evaluate($database, $field, $criteria); } /** @@ -394,7 +232,10 @@ public static function DMIN($database, $field, $criteria) * Excel Function: * DPRODUCT(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DProduct::evaluate() + * Use the evaluate() method in the Database\DProduct class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -411,19 +252,11 @@ public static function DMIN($database, $field, $criteria) * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string */ public static function DPRODUCT($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return MathTrig::PRODUCT( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DProduct::evaluate($database, $field, $criteria); } /** @@ -435,7 +268,10 @@ public static function DPRODUCT($database, $field, $criteria) * Excel Function: * DSTDEV(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DStDev::evaluate() + * Use the evaluate() method in the Database\DStDev class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -456,15 +292,7 @@ public static function DPRODUCT($database, $field, $criteria) */ public static function DSTDEV($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::STDEV( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DStDev::evaluate($database, $field, $criteria); } /** @@ -476,7 +304,10 @@ public static function DSTDEV($database, $field, $criteria) * Excel Function: * DSTDEVP(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DStDevP::evaluate() + * Use the evaluate() method in the Database\DStDevP class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -497,15 +328,7 @@ public static function DSTDEV($database, $field, $criteria) */ public static function DSTDEVP($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::STDEVP( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DStDevP::evaluate($database, $field, $criteria); } /** @@ -516,7 +339,10 @@ public static function DSTDEVP($database, $field, $criteria) * Excel Function: * DSUM(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DSum::evaluate() + * Use the evaluate() method in the Database\DSum class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -533,19 +359,11 @@ public static function DSTDEVP($database, $field, $criteria) * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string */ public static function DSUM($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return MathTrig::SUM( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DSum::evaluate($database, $field, $criteria); } /** @@ -557,7 +375,10 @@ public static function DSUM($database, $field, $criteria) * Excel Function: * DVAR(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DVar::evaluate() + * Use the evaluate() method in the Database\DVar class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -574,19 +395,11 @@ public static function DSUM($database, $field, $criteria) * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string (string if result is an error) */ public static function DVAR($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::VARFunc( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DVar::evaluate($database, $field, $criteria); } /** @@ -598,7 +411,10 @@ public static function DVAR($database, $field, $criteria) * Excel Function: * DVARP(database,field,criteria) * - * @category Database Functions + * @Deprecated 1.17.0 + * + * @see Database\DVarP::evaluate() + * Use the evaluate() method in the Database\DVarP class instead * * @param mixed[] $database The range of cells that makes up the list or database. * A database is a list of related data in which rows of related @@ -615,18 +431,10 @@ public static function DVAR($database, $field, $criteria) * the column label in which you specify a condition for the * column. * - * @return float + * @return float|string (string if result is an error) */ public static function DVARP($database, $field, $criteria) { - $field = self::fieldExtract($database, $field); - if ($field === null) { - return null; - } - - // Return - return Statistical::VARP( - self::getFilteredColumn($database, $field, $criteria) - ); + return Database\DVarP::evaluate($database, $field, $criteria); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php new file mode 100644 index 00000000..e30842dc --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DAverage.php @@ -0,0 +1,45 @@ + 1) { + return ExcelError::NAN(); + } + + $row = array_pop($columnData); + + return array_pop($row); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php new file mode 100644 index 00000000..9c5c7301 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Database/DMax.php @@ -0,0 +1,46 @@ + $row) { + $keys = array_keys($row); + $key = $keys[$field] ?? null; + $columnKey = $key ?? 'A'; + $columnData[$rowKey][$columnKey] = $row[$key] ?? $defaultReturnColumnValue; + } + + return $columnData; + } + + private static function buildQuery(array $criteriaNames, array $criteria): string + { + $baseQuery = []; + foreach ($criteria as $key => $criterion) { + foreach ($criterion as $field => $value) { + $criterionName = $criteriaNames[$field]; + if ($value !== null) { + $condition = self::buildCondition($value, $criterionName); + $baseQuery[$key][] = $condition; + } + } + } + + $rowQuery = array_map( + function ($rowValue) { + return (count($rowValue) > 1) ? 'AND(' . implode(',', $rowValue) . ')' : ($rowValue[0] ?? ''); + }, + $baseQuery + ); + + return (count($rowQuery) > 1) ? 'OR(' . implode(',', $rowQuery) . ')' : ($rowQuery[0] ?? ''); + } + + private static function buildCondition($criterion, string $criterionName): string + { + $ifCondition = Functions::ifCondition($criterion); + + // Check for wildcard characters used in the condition + $result = preg_match('/(?[^"]*)(?".*[*?].*")/ui', $ifCondition, $matches); + if ($result !== 1) { + return "[:{$criterionName}]{$ifCondition}"; + } + + $trueFalse = ($matches['operator'] !== '<>'); + $wildcard = WildcardMatch::wildcard($matches['operand']); + $condition = "WILDCARDMATCH([:{$criterionName}],{$wildcard})"; + if ($trueFalse === false) { + $condition = "NOT({$condition})"; + } + + return $condition; + } + + private static function executeQuery(array $database, string $query, array $criteria, array $fields): array + { + foreach ($database as $dataRow => $dataValues) { + // Substitute actual values from the database row for our [:placeholders] + $conditions = $query; + foreach ($criteria as $criterion) { + $conditions = self::processCondition($criterion, $fields, $dataValues, $conditions); + } + + // evaluate the criteria against the row data + $result = Calculation::getInstance()->_calculateFormulaValue('=' . $conditions); + + // If the row failed to meet the criteria, remove it from the database + if ($result !== true) { + unset($database[$dataRow]); + } + } + + return $database; + } + + private static function processCondition(string $criterion, array $fields, array $dataValues, string $conditions) + { + $key = array_search($criterion, $fields, true); + + $dataValue = 'NULL'; + if (is_bool($dataValues[$key])) { + $dataValue = ($dataValues[$key]) ? 'TRUE' : 'FALSE'; + } elseif ($dataValues[$key] !== null) { + $dataValue = $dataValues[$key]; + // escape quotes if we have a string containing quotes + if (is_string($dataValue) && strpos($dataValue, '"') !== false) { + $dataValue = str_replace('"', '""', $dataValue); + } + $dataValue = (is_string($dataValue)) ? Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; + } + + return str_replace('[:' . $criterion . ']', $dataValue, $conditions); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php index 4f85edeb..79fa8dc0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTime.php @@ -2,129 +2,49 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +use DateTimeInterface; +/** + * @deprecated 1.18.0 + */ class DateTime { /** * Identify if a year is a leap year or not. * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Helpers::isLeapYear() + * Use the isLeapYear method in the DateTimeExcel\Helpers class instead + * * @param int|string $year The year to test * * @return bool TRUE if the year is a leap year, otherwise FALSE */ public static function isLeapYear($year) { - return (($year % 4) === 0) && (($year % 100) !== 0) || (($year % 400) === 0); - } - - /** - * Return the number of days between two dates based on a 360 day calendar. - * - * @param int $startDay Day of month of the start date - * @param int $startMonth Month of the start date - * @param int $startYear Year of the start date - * @param int $endDay Day of month of the start date - * @param int $endMonth Month of the start date - * @param int $endYear Year of the start date - * @param bool $methodUS Whether to use the US method or the European method of calculation - * - * @return int Number of days between the start date and the end date - */ - private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) - { - if ($startDay == 31) { - --$startDay; - } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) { - $startDay = 30; - } - if ($endDay == 31) { - if ($methodUS && $startDay != 30) { - $endDay = 1; - if ($endMonth == 12) { - ++$endYear; - $endMonth = 1; - } else { - ++$endMonth; - } - } else { - $endDay = 30; - } - } - - return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; + return DateTimeExcel\Helpers::isLeapYear($year); } /** * getDateValue. * - * @param string $dateValue + * @Deprecated 1.18.0 * - * @return mixed Excel date/time serial value, or string if error - */ - public static function getDateValue($dateValue) - { - if (!is_numeric($dateValue)) { - if ((is_string($dateValue)) && - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) { - return Functions::VALUE(); - } - if ((is_object($dateValue)) && ($dateValue instanceof \DateTimeInterface)) { - $dateValue = Date::PHPToExcel($dateValue); - } else { - $saveReturnDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - $dateValue = self::DATEVALUE($dateValue); - Functions::setReturnDateType($saveReturnDateType); - } - } - - return $dateValue; - } - - /** - * getTimeValue. + * @See DateTimeExcel\Helpers::getDateValue() + * Use the getDateValue method in the DateTimeExcel\Helpers class instead * - * @param string $timeValue + * @param mixed $dateValue * * @return mixed Excel date/time serial value, or string if error */ - private static function getTimeValue($timeValue) - { - $saveReturnDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - $timeValue = self::TIMEVALUE($timeValue); - Functions::setReturnDateType($saveReturnDateType); - - return $timeValue; - } - - private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) + public static function getDateValue($dateValue) { - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - $oMonth = (int) $PHPDateObject->format('m'); - $oYear = (int) $PHPDateObject->format('Y'); - - $adjustmentMonthsString = (string) $adjustmentMonths; - if ($adjustmentMonths > 0) { - $adjustmentMonthsString = '+' . $adjustmentMonths; - } - if ($adjustmentMonths != 0) { - $PHPDateObject->modify($adjustmentMonthsString . ' months'); + try { + return DateTimeExcel\Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); } - $nMonth = (int) $PHPDateObject->format('m'); - $nYear = (int) $PHPDateObject->format('Y'); - - $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); - if ($monthDiff != $adjustmentMonths) { - $adjustDays = (int) $PHPDateObject->format('d'); - $adjustDaysString = '-' . $adjustDays . ' days'; - $PHPDateObject->modify($adjustDaysString); - } - - return $PHPDateObject; } /** @@ -141,33 +61,17 @@ private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0 * Excel Function: * NOW() * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Current::now() + * Use the now method in the DateTimeExcel\Current class instead * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATETIMENOW() { - $saveTimeZone = date_default_timezone_get(); - date_default_timezone_set('UTC'); - $retValue = false; - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $retValue = (float) Date::PHPToExcel(time()); - - break; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - $retValue = (int) time(); - - break; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $retValue = new \DateTime(); - - break; - } - date_default_timezone_set($saveTimeZone); - - return $retValue; + return DateTimeExcel\Current::now(); } /** @@ -184,34 +88,17 @@ public static function DATETIMENOW() * Excel Function: * TODAY() * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Current::today() + * Use the today method in the DateTimeExcel\Current class instead * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function DATENOW() { - $saveTimeZone = date_default_timezone_get(); - date_default_timezone_set('UTC'); - $retValue = false; - $excelDateTime = floor(Date::PHPToExcel(time())); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $retValue = (float) $excelDateTime; - - break; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - $retValue = (int) Date::excelToTimestamp($excelDateTime); - - break; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $retValue = Date::excelToDateTimeObject($excelDateTime); - - break; - } - date_default_timezone_set($saveTimeZone); - - return $retValue; + return DateTimeExcel\Current::today(); } /** @@ -222,15 +109,19 @@ public static function DATENOW() * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date * format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. * + * * Excel Function: * DATE(year,month,day) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Date::fromYMD() + * Use the fromYMD method in the DateTimeExcel\Date class instead + * * PhpSpreadsheet is a lot more forgiving than MS Excel when passing non numeric values to this function. * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. * - * @category Date/Time Functions - * * @param int $year The value of the year argument can include one to four digits. * Excel interprets the year argument according to the configured * date system: 1900 or 1904. @@ -267,69 +158,7 @@ public static function DATENOW() */ public static function DATE($year = 0, $month = 1, $day = 1) { - $year = Functions::flattenSingleValue($year); - $month = Functions::flattenSingleValue($month); - $day = Functions::flattenSingleValue($day); - - if (($month !== null) && (!is_numeric($month))) { - $month = Date::monthStringToNumber($month); - } - - if (($day !== null) && (!is_numeric($day))) { - $day = Date::dayStringToNumber($day); - } - - $year = ($year !== null) ? StringHelper::testStringAsNumeric($year) : 0; - $month = ($month !== null) ? StringHelper::testStringAsNumeric($month) : 0; - $day = ($day !== null) ? StringHelper::testStringAsNumeric($day) : 0; - if ((!is_numeric($year)) || - (!is_numeric($month)) || - (!is_numeric($day))) { - return Functions::VALUE(); - } - $year = (int) $year; - $month = (int) $month; - $day = (int) $day; - - $baseYear = Date::getExcelCalendar(); - // Validate parameters - if ($year < ($baseYear - 1900)) { - return Functions::NAN(); - } - if ((($baseYear - 1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { - return Functions::NAN(); - } - - if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { - $year += 1900; - } - - if ($month < 1) { - // Handle year/month adjustment if month < 1 - --$month; - $year += ceil($month / 12) - 1; - $month = 13 - abs($month % 12); - } elseif ($month > 12) { - // Handle year/month adjustment if month > 12 - $year += floor($month / 12); - $month = ($month % 12); - } - - // Re-validate the year parameter after adjustments - if (($year < $baseYear) || ($year >= 10000)) { - return Functions::NAN(); - } - - // Execute function - $excelDateValue = Date::formattedPHPToExcel($year, $month, $day); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($excelDateValue); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return Date::excelToDateTimeObject($excelDateValue); - } + return DateTimeExcel\Date::fromYMD($year, $month, $day); } /** @@ -343,7 +172,10 @@ public static function DATE($year = 0, $month = 1, $day = 1) * Excel Function: * TIME(hour,minute,second) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Time::fromHMS() + * Use the fromHMS method in the DateTimeExcel\Time class instead * * @param int $hour A number from 0 (zero) to 32767 representing the hour. * Any value greater than 23 will be divided by 24 and the remainder @@ -362,85 +194,7 @@ public static function DATE($year = 0, $month = 1, $day = 1) */ public static function TIME($hour = 0, $minute = 0, $second = 0) { - $hour = Functions::flattenSingleValue($hour); - $minute = Functions::flattenSingleValue($minute); - $second = Functions::flattenSingleValue($second); - - if ($hour == '') { - $hour = 0; - } - if ($minute == '') { - $minute = 0; - } - if ($second == '') { - $second = 0; - } - - if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) { - return Functions::VALUE(); - } - $hour = (int) $hour; - $minute = (int) $minute; - $second = (int) $second; - - if ($second < 0) { - $minute += floor($second / 60); - $second = 60 - abs($second % 60); - if ($second == 60) { - $second = 0; - } - } elseif ($second >= 60) { - $minute += floor($second / 60); - $second = $second % 60; - } - if ($minute < 0) { - $hour += floor($minute / 60); - $minute = 60 - abs($minute % 60); - if ($minute == 60) { - $minute = 0; - } - } elseif ($minute >= 60) { - $hour += floor($minute / 60); - $minute = $minute % 60; - } - - if ($hour > 23) { - $hour = $hour % 24; - } elseif ($hour < 0) { - return Functions::NAN(); - } - - // Execute function - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - $date = 0; - $calendar = Date::getExcelCalendar(); - if ($calendar != Date::CALENDAR_WINDOWS_1900) { - $date = 1; - } - - return (float) Date::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - $dayAdjust = 0; - if ($hour < 0) { - $dayAdjust = floor($hour / 24); - $hour = 24 - abs($hour % 24); - if ($hour == 24) { - $hour = 0; - } - } elseif ($hour >= 24) { - $dayAdjust = floor($hour / 24); - $hour = $hour % 24; - } - $phpDateObject = new \DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); - if ($dayAdjust != 0) { - $phpDateObject->modify($dayAdjust . ' days'); - } - - return $phpDateObject; - } + return DateTimeExcel\Time::fromHMS($hour, $minute, $second); } /** @@ -456,7 +210,10 @@ public static function TIME($hour = 0, $minute = 0, $second = 0) * Excel Function: * DATEVALUE(dateValue) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateValue::fromString() + * Use the fromString method in the DateTimeExcel\DateValue class instead * * @param string $dateValue Text that represents a date in a Microsoft Excel date format. * For example, "1/30/2008" or "30-Jan-2008" are text strings within @@ -470,112 +227,9 @@ public static function TIME($hour = 0, $minute = 0, $second = 0) * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ - public static function DATEVALUE($dateValue = 1) + public static function DATEVALUE($dateValue) { - $dateValue = trim(Functions::flattenSingleValue($dateValue), '"'); - // Strip any ordinals because they're allowed in Excel (English only) - $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); - // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) - $dateValue = str_replace(['/', '.', '-', ' '], ' ', $dateValue); - - $yearFound = false; - $t1 = explode(' ', $dateValue); - foreach ($t1 as &$t) { - if ((is_numeric($t)) && ($t > 31)) { - if ($yearFound) { - return Functions::VALUE(); - } - if ($t < 100) { - $t += 1900; - } - $yearFound = true; - } - } - if ((count($t1) == 1) && (strpos($t, ':') !== false)) { - // We've been fed a time value without any date - return 0.0; - } elseif (count($t1) == 2) { - // We only have two parts of the date: either day/month or month/year - if ($yearFound) { - array_unshift($t1, 1); - } else { - if ($t1[1] > 29) { - $t1[1] += 1900; - array_unshift($t1, 1); - } else { - $t1[] = date('Y'); - } - } - } - unset($t); - $dateValue = implode(' ', $t1); - - $PHPDateArray = date_parse($dateValue); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - $testVal1 = strtok($dateValue, '- '); - if ($testVal1 !== false) { - $testVal2 = strtok('- '); - if ($testVal2 !== false) { - $testVal3 = strtok('- '); - if ($testVal3 === false) { - $testVal3 = strftime('%Y'); - } - } else { - return Functions::VALUE(); - } - } else { - return Functions::VALUE(); - } - if ($testVal1 < 31 && $testVal2 < 12 && $testVal3 < 12 && strlen($testVal3) == 2) { - $testVal3 += 2000; - } - $PHPDateArray = date_parse($testVal1 . '-' . $testVal2 . '-' . $testVal3); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - $PHPDateArray = date_parse($testVal2 . '-' . $testVal1 . '-' . $testVal3); - if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { - return Functions::VALUE(); - } - } - } - - if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { - // Execute function - if ($PHPDateArray['year'] == '') { - $PHPDateArray['year'] = strftime('%Y'); - } - if ($PHPDateArray['year'] < 1900) { - return Functions::VALUE(); - } - if ($PHPDateArray['month'] == '') { - $PHPDateArray['month'] = strftime('%m'); - } - if ($PHPDateArray['day'] == '') { - $PHPDateArray['day'] = strftime('%d'); - } - if (!checkdate($PHPDateArray['month'], $PHPDateArray['day'], $PHPDateArray['year'])) { - return Functions::VALUE(); - } - $excelDateValue = floor( - Date::formattedPHPToExcel( - $PHPDateArray['year'], - $PHPDateArray['month'], - $PHPDateArray['day'], - $PHPDateArray['hour'], - $PHPDateArray['minute'], - $PHPDateArray['second'] - ) - ); - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($excelDateValue); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return new \DateTime($PHPDateArray['year'] . '-' . $PHPDateArray['month'] . '-' . $PHPDateArray['day'] . ' 00:00:00'); - } - } - - return Functions::VALUE(); + return DateTimeExcel\DateValue::fromString($dateValue); } /** @@ -591,7 +245,10 @@ public static function DATEVALUE($dateValue = 1) * Excel Function: * TIMEVALUE(timeValue) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeValue::fromString() + * Use the fromString method in the DateTimeExcel\TimeValue class instead * * @param string $timeValue A text string that represents a time in any one of the Microsoft * Excel time formats; for example, "6:45 PM" and "18:45" text strings @@ -603,163 +260,31 @@ public static function DATEVALUE($dateValue = 1) */ public static function TIMEVALUE($timeValue) { - $timeValue = trim(Functions::flattenSingleValue($timeValue), '"'); - $timeValue = str_replace(['/', '.'], '-', $timeValue); - - $arraySplit = preg_split('/[\/:\-\s]/', $timeValue); - if ((count($arraySplit) == 2 || count($arraySplit) == 3) && $arraySplit[0] > 24) { - $arraySplit[0] = ($arraySplit[0] % 24); - $timeValue = implode(':', $arraySplit); - } - - $PHPDateArray = date_parse($timeValue); - if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $excelDateValue = Date::formattedPHPToExcel( - $PHPDateArray['year'], - $PHPDateArray['month'], - $PHPDateArray['day'], - $PHPDateArray['hour'], - $PHPDateArray['minute'], - $PHPDateArray['second'] - ); - } else { - $excelDateValue = Date::formattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1; - } - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $excelDateValue; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) $phpDateValue = Date::excelToTimestamp($excelDateValue + 25569) - 3600; - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return new \DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); - } - } - - return Functions::VALUE(); + return DateTimeExcel\TimeValue::fromString($timeValue); } /** * DATEDIF. * + * Excel Function: + * DATEDIF(startdate, enddate, unit) + * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Difference::interval() + * Use the interval method in the DateTimeExcel\Difference class instead + * * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object * or a standard date string - * @param string $unit + * @param array|string $unit * - * @return int|string Interval between the dates + * @return array|int|string Interval between the dates */ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $unit = strtoupper(Functions::flattenSingleValue($unit)); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - - // Validate parameters - if ($startDate > $endDate) { - return Functions::NAN(); - } - - // Execute function - $difference = $endDate - $startDate; - - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $startDays = $PHPStartDateObject->format('j'); - $startMonths = $PHPStartDateObject->format('n'); - $startYears = $PHPStartDateObject->format('Y'); - - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - $endDays = $PHPEndDateObject->format('j'); - $endMonths = $PHPEndDateObject->format('n'); - $endYears = $PHPEndDateObject->format('Y'); - - switch ($unit) { - case 'D': - $retVal = (int) $difference; - - break; - case 'M': - $retVal = (int) ($endMonths - $startMonths) + ((int) ($endYears - $startYears) * 12); - // We're only interested in full months - if ($endDays < $startDays) { - --$retVal; - } - - break; - case 'Y': - $retVal = (int) ($endYears - $startYears); - // We're only interested in full months - if ($endMonths < $startMonths) { - --$retVal; - } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) { - // Remove start month - --$retVal; - // Remove end month - --$retVal; - } - - break; - case 'MD': - if ($endDays < $startDays) { - $retVal = $endDays; - $PHPEndDateObject->modify('-' . $endDays . ' days'); - $adjustDays = $PHPEndDateObject->format('j'); - $retVal += ($adjustDays - $startDays); - } else { - $retVal = $endDays - $startDays; - } - - break; - case 'YM': - $retVal = (int) ($endMonths - $startMonths); - if ($retVal < 0) { - $retVal += 12; - } - // We're only interested in full months - if ($endDays < $startDays) { - --$retVal; - } - - break; - case 'YD': - $retVal = (int) $difference; - if ($endYears > $startYears) { - $isLeapStartYear = $PHPStartDateObject->format('L'); - $wasLeapEndYear = $PHPEndDateObject->format('L'); - - // Adjust end year to be as close as possible as start year - while ($PHPEndDateObject >= $PHPStartDateObject) { - $PHPEndDateObject->modify('-1 year'); - $endYears = $PHPEndDateObject->format('Y'); - } - $PHPEndDateObject->modify('+1 year'); - - // Get the result - $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days; - - // Adjust for leap years cases - $isLeapEndYear = $PHPEndDateObject->format('L'); - $limit = new \DateTime($PHPEndDateObject->format('Y-02-29')); - if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { - --$retVal; - } - } - - break; - default: - $retVal = Functions::VALUE(); - } - - return $retVal; + return DateTimeExcel\Difference::interval($startDate, $endDate, $unit); } /** @@ -770,42 +295,21 @@ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') * Excel Function: * DAYS(endDate, startDate) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Days::between() + * Use the between method in the DateTimeExcel\Days class instead * - * @param \DateTimeImmutable|float|int|string $endDate Excel date serial value (float), + * @param array|DateTimeInterface|float|int|string $endDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string - * @param \DateTimeImmutable|float|int|string $startDate Excel date serial value (float), + * @param array|DateTimeInterface|float|int|string $startDate Excel date serial value (float), * PHP date timestamp (integer), PHP DateTime object, or a standard date string * - * @return int|string Number of days between start date and end date or an error + * @return array|int|string Number of days between start date and end date or an error */ public static function DAYS($endDate = 0, $startDate = 0) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - - $startDate = self::getDateValue($startDate); - if (is_string($startDate)) { - return Functions::VALUE(); - } - - $endDate = self::getDateValue($endDate); - if (is_string($endDate)) { - return Functions::VALUE(); - } - - // Execute function - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - - $diff = $PHPStartDateObject->diff($PHPEndDateObject); - $days = $diff->days; - - if ($diff->invert) { - $days = -$days; - } - - return $days; + return DateTimeExcel\Days::between($endDate, $startDate); } /** @@ -818,13 +322,16 @@ public static function DAYS($endDate = 0, $startDate = 0) * Excel Function: * DAYS360(startDate,endDate[,method]) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Days360::between() + * Use the between method in the DateTimeExcel\Days360 class instead * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string - * @param bool $method US or European Method + * @param array|bool $method US or European Method * FALSE or omitted: U.S. (NASD) method. If the starting date is * the last day of a month, it becomes equal to the 30th of the * same month. If the ending date is the last day of a month and @@ -836,36 +343,11 @@ public static function DAYS($endDate = 0, $startDate = 0) * occur on the 31st of a month become equal to the 30th of the * same month. * - * @return int|string Number of days between start date and end date + * @return array|int|string Number of days between start date and end date */ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - - if (!is_bool($method)) { - return Functions::VALUE(); - } - - // Execute function - $PHPStartDateObject = Date::excelToDateTimeObject($startDate); - $startDay = $PHPStartDateObject->format('j'); - $startMonth = $PHPStartDateObject->format('n'); - $startYear = $PHPStartDateObject->format('Y'); - - $PHPEndDateObject = Date::excelToDateTimeObject($endDate); - $endDay = $PHPEndDateObject->format('j'); - $endMonth = $PHPEndDateObject->format('n'); - $endYear = $PHPEndDateObject->format('Y'); - - return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); + return DateTimeExcel\Days360::between($startDate, $endDate, $method); } /** @@ -878,98 +360,31 @@ public static function DAYS360($startDate = 0, $endDate = 0, $method = false) * * Excel Function: * YEARFRAC(startDate,endDate[,method]) + * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\YearFrac::fraction() + * Use the fraction method in the DateTimeExcel\YearFrac class instead + * * See https://lists.oasis-open.org/archives/office-formula/200806/msg00039.html * for description of algorithm used in Excel * - * @category Date/Time Functions - * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string - * @param int $method Method used for the calculation + * @param array|int $method Method used for the calculation * 0 or omitted US (NASD) 30/360 * 1 Actual/actual * 2 Actual/360 * 3 Actual/365 * 4 European 30/360 * - * @return float|string fraction of the year, or a string containing an error + * @return array|float|string fraction of the year, or a string containing an error */ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) { - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - $method = Functions::flattenSingleValue($method); - - if (is_string($startDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - if (is_string($endDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - if ($startDate > $endDate) { - $temp = $startDate; - $startDate = $endDate; - $endDate = $temp; - } - - if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) { - switch ($method) { - case 0: - return self::DAYS360($startDate, $endDate) / 360; - case 1: - $days = self::DATEDIF($startDate, $endDate); - $startYear = self::YEAR($startDate); - $endYear = self::YEAR($endDate); - $years = $endYear - $startYear + 1; - $startMonth = self::MONTHOFYEAR($startDate); - $startDay = self::DAYOFMONTH($startDate); - $endMonth = self::MONTHOFYEAR($endDate); - $endDay = self::DAYOFMONTH($endDate); - $startMonthDay = 100 * $startMonth + $startDay; - $endMonthDay = 100 * $endMonth + $endDay; - if ($years == 1) { - if (self::isLeapYear($endYear)) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { - if (self::isLeapYear($startYear)) { - if ($startMonthDay <= 229) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } elseif (self::isLeapYear($endYear)) { - if ($endMonthDay >= 229) { - $tmpCalcAnnualBasis = 366; - } else { - $tmpCalcAnnualBasis = 365; - } - } else { - $tmpCalcAnnualBasis = 365; - } - } else { - $tmpCalcAnnualBasis = 0; - for ($year = $startYear; $year <= $endYear; ++$year) { - $tmpCalcAnnualBasis += self::isLeapYear($year) ? 366 : 365; - } - $tmpCalcAnnualBasis /= $years; - } - - return $days / $tmpCalcAnnualBasis; - case 2: - return self::DATEDIF($startDate, $endDate) / 360; - case 3: - return self::DATEDIF($startDate, $endDate) / 365; - case 4: - return self::DAYS360($startDate, $endDate, true) / 360; - } - } - - return Functions::VALUE(); + return DateTimeExcel\YearFrac::fraction($startDate, $endDate, $method); } /** @@ -983,73 +398,22 @@ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) * Excel Function: * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\NetworkDays::count() + * Use the count method in the DateTimeExcel\NetworkDays class instead * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string + * @param mixed $dateArgs * - * @return int|string Interval between the dates + * @return array|int|string Interval between the dates */ public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs) { - // Retrieve the mandatory start and end date that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDate = Functions::flattenSingleValue($endDate); - // Get the optional days - $dateArgs = Functions::flattenArray($dateArgs); - - // Validate the start and end dates - if (is_string($startDate = $sDate = self::getDateValue($startDate))) { - return Functions::VALUE(); - } - $startDate = (float) floor($startDate); - if (is_string($endDate = $eDate = self::getDateValue($endDate))) { - return Functions::VALUE(); - } - $endDate = (float) floor($endDate); - - if ($sDate > $eDate) { - $startDate = $eDate; - $endDate = $sDate; - } - - // Execute function - $startDoW = 6 - self::WEEKDAY($startDate, 2); - if ($startDoW < 0) { - $startDoW = 0; - } - $endDoW = self::WEEKDAY($endDate, 2); - if ($endDoW >= 6) { - $endDoW = 0; - } - - $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5; - $partWeekDays = $endDoW + $startDoW; - if ($partWeekDays > 5) { - $partWeekDays -= 5; - } - - // Test any extra holiday parameters - $holidayCountedArray = []; - foreach ($dateArgs as $holidayDate) { - if (is_string($holidayDate = self::getDateValue($holidayDate))) { - return Functions::VALUE(); - } - if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { - if ((self::WEEKDAY($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { - --$partWeekDays; - $holidayCountedArray[] = $holidayDate; - } - } - } - - if ($sDate > $eDate) { - return 0 - ($wholeWeekDays + $partWeekDays); - } - - return $wholeWeekDays + $partWeekDays; + return DateTimeExcel\NetworkDays::count($startDate, $endDate, ...$dateArgs); } /** @@ -1063,104 +427,24 @@ public static function NETWORKDAYS($startDate, $endDate, ...$dateArgs) * Excel Function: * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) * - * @category Date/Time Functions + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\WorkDay::date() + * Use the date method in the DateTimeExcel\WorkDay class instead * * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $endDays The number of nonweekend and nonholiday days before or after * startDate. A positive value for days yields a future date; a * negative value yields a past date. + * @param mixed $dateArgs * * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, * depending on the value of the ReturnDateType flag */ public static function WORKDAY($startDate, $endDays, ...$dateArgs) { - // Retrieve the mandatory start date and days that are referenced in the function definition - $startDate = Functions::flattenSingleValue($startDate); - $endDays = Functions::flattenSingleValue($endDays); - // Get the optional days - $dateArgs = Functions::flattenArray($dateArgs); - - if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) { - return Functions::VALUE(); - } - $startDate = (float) floor($startDate); - $endDays = (int) floor($endDays); - // If endDays is 0, we always return startDate - if ($endDays == 0) { - return $startDate; - } - - $decrementing = $endDays < 0; - - // Adjust the start date if it falls over a weekend - - $startDoW = self::WEEKDAY($startDate, 3); - if (self::WEEKDAY($startDate, 3) >= 5) { - $startDate += ($decrementing) ? -$startDoW + 4 : 7 - $startDoW; - ($decrementing) ? $endDays++ : $endDays--; - } - - // Add endDays - $endDate = (float) $startDate + ((int) ($endDays / 5) * 7) + ($endDays % 5); - - // Adjust the calculated end date if it falls over a weekend - $endDoW = self::WEEKDAY($endDate, 3); - if ($endDoW >= 5) { - $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW; - } - - // Test any extra holiday parameters - if (!empty($dateArgs)) { - $holidayCountedArray = $holidayDates = []; - foreach ($dateArgs as $holidayDate) { - if (($holidayDate !== null) && (trim($holidayDate) > '')) { - if (is_string($holidayDate = self::getDateValue($holidayDate))) { - return Functions::VALUE(); - } - if (self::WEEKDAY($holidayDate, 3) < 5) { - $holidayDates[] = $holidayDate; - } - } - } - if ($decrementing) { - rsort($holidayDates, SORT_NUMERIC); - } else { - sort($holidayDates, SORT_NUMERIC); - } - foreach ($holidayDates as $holidayDate) { - if ($decrementing) { - if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { - if (!in_array($holidayDate, $holidayCountedArray)) { - --$endDate; - $holidayCountedArray[] = $holidayDate; - } - } - } else { - if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { - if (!in_array($holidayDate, $holidayCountedArray)) { - ++$endDate; - $holidayCountedArray[] = $holidayDate; - } - } - } - // Adjust the calculated end date if it falls over a weekend - $endDoW = self::WEEKDAY($endDate, 3); - if ($endDoW >= 5) { - $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW; - } - } - } - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) $endDate; - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp($endDate); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return Date::excelToDateTimeObject($endDate); - } + return DateTimeExcel\WorkDay::date($startDate, $endDays, ...$dateArgs); } /** @@ -1172,33 +456,19 @@ public static function WORKDAY($startDate, $endDays, ...$dateArgs) * Excel Function: * DAY(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::day() + * Use the day method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * - * @return int|string Day of the month + * @return array|int|string Day of the month */ public static function DAYOFMONTH($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - if ($dateValue < 0.0) { - return Functions::NAN(); - } elseif ($dateValue < 1.0) { - return 0; - } - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('j'); + return DateTimeExcel\DateParts::day($dateValue); } /** @@ -1210,90 +480,185 @@ public static function DAYOFMONTH($dateValue = 1) * Excel Function: * WEEKDAY(dateValue[,style]) * - * @param int $dateValue Excel date serial value (float), PHP date timestamp (integer), + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::day() + * Use the day method in the DateTimeExcel\Week class instead + * + * @param float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $style A number that determines the type of return value * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). * 2 Numbers 1 (Monday) through 7 (Sunday). * 3 Numbers 0 (Monday) through 6 (Sunday). * - * @return int|string Day of the week value + * @return array|int|string Day of the week value */ public static function WEEKDAY($dateValue = 1, $style = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - $style = Functions::flattenSingleValue($style); - - if (!is_numeric($style)) { - return Functions::VALUE(); - } elseif (($style < 1) || ($style > 3)) { - return Functions::NAN(); - } - $style = floor($style); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - $DoW = (int) $PHPDateObject->format('w'); - - $firstDay = 1; - switch ($style) { - case 1: - ++$DoW; - - break; - case 2: - if ($DoW === 0) { - $DoW = 7; - } - - break; - case 3: - if ($DoW === 0) { - $DoW = 7; - } - $firstDay = 0; - --$DoW; - - break; - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - // Test for Excel's 1900 leap year, and introduce the error as required - if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) { - --$DoW; - if ($DoW < $firstDay) { - $DoW += 7; - } - } - } - - return $DoW; + return DateTimeExcel\Week::day($dateValue, $style); } + /** + * STARTWEEK_SUNDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY instead + */ const STARTWEEK_SUNDAY = 1; + + /** + * STARTWEEK_MONDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY instead + */ const STARTWEEK_MONDAY = 2; + + /** + * STARTWEEK_MONDAY_ALT. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ALT instead + */ const STARTWEEK_MONDAY_ALT = 11; + + /** + * STARTWEEK_TUESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_TUESDAY instead + */ const STARTWEEK_TUESDAY = 12; + + /** + * STARTWEEK_WEDNESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_WEDNESDAY instead + */ const STARTWEEK_WEDNESDAY = 13; + + /** + * STARTWEEK_THURSDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_THURSDAY instead + */ const STARTWEEK_THURSDAY = 14; + + /** + * STARTWEEK_FRIDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_FRIDAY instead + */ const STARTWEEK_FRIDAY = 15; + + /** + * STARTWEEK_SATURDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SATURDAY instead + */ const STARTWEEK_SATURDAY = 16; + + /** + * STARTWEEK_SUNDAY_ALT. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_SUNDAY_ALT instead + */ const STARTWEEK_SUNDAY_ALT = 17; + + /** + * DOW_SUNDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_SUNDAY instead + */ const DOW_SUNDAY = 1; + + /** + * DOW_MONDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_MONDAY instead + */ const DOW_MONDAY = 2; + + /** + * DOW_TUESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_TUESDAY instead + */ const DOW_TUESDAY = 3; + + /** + * DOW_WEDNESDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_WEDNESDAY instead + */ const DOW_WEDNESDAY = 4; + + /** + * DOW_THURSDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_THURSDAY instead + */ const DOW_THURSDAY = 5; + + /** + * DOW_FRIDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_FRIDAY instead + */ const DOW_FRIDAY = 6; + + /** + * DOW_SATURDAY. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\DOW_SATURDAY instead + */ const DOW_SATURDAY = 7; + + /** + * STARTWEEK_MONDAY_ISO. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\STARTWEEK_MONDAY_ISO instead + */ const STARTWEEK_MONDAY_ISO = 21; + + /** + * METHODARR. + * + * @Deprecated 1.18.0 + * + * @see Use DateTimeExcel\Constants\METHODARR instead + */ const METHODARR = [ self::STARTWEEK_SUNDAY => self::DOW_SUNDAY, self::DOW_MONDAY, @@ -1305,7 +670,7 @@ public static function WEEKDAY($dateValue = 1, $style = 1) self::DOW_SATURDAY, self::DOW_SUNDAY, self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, - ]; + ]; /** * WEEKNUM. @@ -1320,6 +685,11 @@ public static function WEEKDAY($dateValue = 1, $style = 1) * Excel Function: * WEEKNUM(dateValue[,style]) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::number(() + * Use the number method in the DateTimeExcel\Week class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $method Week begins on Sunday or Monday @@ -1334,44 +704,11 @@ public static function WEEKDAY($dateValue = 1, $style = 1) * 17 Week begins on Sunday. * 21 ISO (Jan. 4 is week 1, begins on Monday). * - * @return int|string Week Number + * @return array|int|string Week Number */ public static function WEEKNUM($dateValue = 1, $method = self::STARTWEEK_SUNDAY) { - $dateValue = Functions::flattenSingleValue($dateValue); - $method = Functions::flattenSingleValue($method); - - if (!is_numeric($method)) { - return Functions::VALUE(); - } - $method = (int) $method; - if (!array_key_exists($method, self::METHODARR)) { - return Functions::NaN(); - } - $method = self::METHODARR[$method]; - - $dateValue = self::getDateValue($dateValue); - if (is_string($dateValue)) { - return Functions::VALUE(); - } - if ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - if ($method == self::STARTWEEK_MONDAY_ISO) { - return (int) $PHPDateObject->format('W'); - } - $dayOfYear = $PHPDateObject->format('z'); - $PHPDateObject->modify('-' . $dayOfYear . ' days'); - $firstDayOfFirstWeek = $PHPDateObject->format('w'); - $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; - $daysInFirstWeek += 7 * !$daysInFirstWeek; - $endFirstWeek = $daysInFirstWeek - 1; - $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); - - return (int) $weekOfYear; + return DateTimeExcel\Week::number($dateValue, $method); } /** @@ -1382,27 +719,19 @@ public static function WEEKNUM($dateValue = 1, $method = self::STARTWEEK_SUNDAY) * Excel Function: * ISOWEEKNUM(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Week::isoWeekNumber() + * Use the isoWeekNumber method in the DateTimeExcel\Week class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * - * @return int|string Week Number + * @return array|int|string Week Number */ public static function ISOWEEKNUM($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('W'); + return DateTimeExcel\Week::isoWeekNumber($dateValue); } /** @@ -1414,28 +743,19 @@ public static function ISOWEEKNUM($dateValue = 1) * Excel Function: * MONTH(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::month() + * Use the month method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * - * @return int|string Month of the year + * @return array|int|string Month of the year */ public static function MONTHOFYEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if (empty($dateValue)) { - $dateValue = 1; - } - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('n'); + return DateTimeExcel\DateParts::month($dateValue); } /** @@ -1447,27 +767,19 @@ public static function MONTHOFYEAR($dateValue = 1) * Excel Function: * YEAR(dateValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\DateParts::year() + * Use the ear method in the DateTimeExcel\DateParts class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * - * @return int|string Year + * @return array|int|string Year */ public static function YEAR($dateValue = 1) { - $dateValue = Functions::flattenSingleValue($dateValue); - - if ($dateValue === null) { - $dateValue = 1; - } elseif (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } elseif ($dateValue < 0.0) { - return Functions::NAN(); - } - - // Execute function - $PHPDateObject = Date::excelToDateTimeObject($dateValue); - - return (int) $PHPDateObject->format('Y'); + return DateTimeExcel\DateParts::year($dateValue); } /** @@ -1479,36 +791,19 @@ public static function YEAR($dateValue = 1) * Excel Function: * HOUR(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::hour() + * Use the hour method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * - * @return int|string Hour + * @return array|int|string Hour */ public static function HOUROFDAY($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('G', $timeValue); + return DateTimeExcel\TimeParts::hour($timeValue); } /** @@ -1520,36 +815,19 @@ public static function HOUROFDAY($timeValue = 0) * Excel Function: * MINUTE(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::minute() + * Use the minute method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * - * @return int|string Minute + * @return array|int|string Minute */ public static function MINUTE($timeValue = 0) { - $timeValue = $timeTester = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('i', $timeValue); + return DateTimeExcel\TimeParts::minute($timeValue); } /** @@ -1561,36 +839,19 @@ public static function MINUTE($timeValue = 0) * Excel Function: * SECOND(timeValue) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\TimeParts::second() + * Use the second method in the DateTimeExcel\TimeParts class instead + * * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard time string * - * @return int|string Second + * @return array|int|string Second */ public static function SECOND($timeValue = 0) { - $timeValue = Functions::flattenSingleValue($timeValue); - - if (!is_numeric($timeValue)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $testVal = strtok($timeValue, '/-: '); - if (strlen($testVal) < strlen($timeValue)) { - return Functions::VALUE(); - } - } - $timeValue = self::getTimeValue($timeValue); - if (is_string($timeValue)) { - return Functions::VALUE(); - } - } - // Execute function - if ($timeValue >= 1) { - $timeValue = fmod($timeValue, 1); - } elseif ($timeValue < 0.0) { - return Functions::NAN(); - } - $timeValue = Date::excelToTimestamp($timeValue); - - return (int) gmdate('s', $timeValue); + return DateTimeExcel\TimeParts::second($timeValue); } /** @@ -1604,6 +865,11 @@ public static function SECOND($timeValue = 0) * Excel Function: * EDATE(dateValue,adjustmentMonths) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Month::adjust() + * Use the adjust method in the DateTimeExcel\Edate class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. @@ -1615,29 +881,7 @@ public static function SECOND($timeValue = 0) */ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); - - if (!is_numeric($adjustmentMonths)) { - return Functions::VALUE(); - } - $adjustmentMonths = floor($adjustmentMonths); - - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - // Execute function - $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths); - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) Date::PHPToExcel($PHPDateObject); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject)); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return $PHPDateObject; - } + return DateTimeExcel\Month::adjust($dateValue, $adjustmentMonths); } /** @@ -1650,6 +894,11 @@ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) * Excel Function: * EOMONTH(dateValue,adjustmentMonths) * + * @Deprecated 1.18.0 + * + * @See DateTimeExcel\Month::lastDay() + * Use the lastDay method in the DateTimeExcel\EoMonth class instead + * * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), * PHP DateTime object, or a standard date string * @param int $adjustmentMonths The number of months before or after start_date. @@ -1661,31 +910,6 @@ public static function EDATE($dateValue = 1, $adjustmentMonths = 0) */ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) { - $dateValue = Functions::flattenSingleValue($dateValue); - $adjustmentMonths = Functions::flattenSingleValue($adjustmentMonths); - - if (!is_numeric($adjustmentMonths)) { - return Functions::VALUE(); - } - $adjustmentMonths = floor($adjustmentMonths); - - if (is_string($dateValue = self::getDateValue($dateValue))) { - return Functions::VALUE(); - } - - // Execute function - $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths + 1); - $adjustDays = (int) $PHPDateObject->format('d'); - $adjustDaysString = '-' . $adjustDays . ' days'; - $PHPDateObject->modify($adjustDaysString); - - switch (Functions::getReturnDateType()) { - case Functions::RETURNDATE_EXCEL: - return (float) Date::PHPToExcel($PHPDateObject); - case Functions::RETURNDATE_UNIX_TIMESTAMP: - return (int) Date::excelToTimestamp(Date::PHPToExcel($PHPDateObject)); - case Functions::RETURNDATE_PHP_DATETIME_OBJECT: - return $PHPDateObject; - } + return DateTimeExcel\Month::lastDay($dateValue, $adjustmentMonths); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php new file mode 100644 index 00000000..1165eb1f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Constants.php @@ -0,0 +1,38 @@ + self::DOW_SUNDAY, + self::DOW_MONDAY, + self::STARTWEEK_MONDAY_ALT => self::DOW_MONDAY, + self::DOW_TUESDAY, + self::DOW_WEDNESDAY, + self::DOW_THURSDAY, + self::DOW_FRIDAY, + self::DOW_SATURDAY, + self::DOW_SUNDAY, + self::STARTWEEK_MONDAY_ISO => self::STARTWEEK_MONDAY_ISO, + ]; +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php new file mode 100644 index 00000000..5de671d3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Current.php @@ -0,0 +1,59 @@ +format('c')); + + return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray, true) : ExcelError::VALUE(); + } + + /** + * DATETIMENOW. + * + * Returns the current date and time. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PhpSpreadsheet does not change cell formatting in this way. + * + * Excel Function: + * NOW() + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function now() + { + $dti = new DateTimeImmutable(); + $dateArray = Helpers::dateParse($dti->format('c')); + + return Helpers::dateParseSucceeded($dateArray) ? Helpers::returnIn3FormatsArray($dateArray) : ExcelError::VALUE(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php new file mode 100644 index 00000000..56982c5c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Date.php @@ -0,0 +1,172 @@ +getMessage(); + } + + // Execute function + $excelDateValue = SharedDateHelper::formattedPHPToExcel($year, $month, $day); + + return Helpers::returnIn3FormatsFloat($excelDateValue); + } + + /** + * Convert year from multiple formats to int. + * + * @param mixed $year + */ + private static function getYear($year, int $baseYear): int + { + $year = ($year !== null) ? StringHelper::testStringAsNumeric((string) $year) : 0; + if (!is_numeric($year)) { + throw new Exception(ExcelError::VALUE()); + } + $year = (int) $year; + + if ($year < ($baseYear - 1900)) { + throw new Exception(ExcelError::NAN()); + } + if ((($baseYear - 1900) !== 0) && ($year < $baseYear) && ($year >= 1900)) { + throw new Exception(ExcelError::NAN()); + } + + if (($year < $baseYear) && ($year >= ($baseYear - 1900))) { + $year += 1900; + } + + return (int) $year; + } + + /** + * Convert month from multiple formats to int. + * + * @param mixed $month + */ + private static function getMonth($month): int + { + if (($month !== null) && (!is_numeric($month))) { + $month = SharedDateHelper::monthStringToNumber($month); + } + + $month = ($month !== null) ? StringHelper::testStringAsNumeric((string) $month) : 0; + if (!is_numeric($month)) { + throw new Exception(ExcelError::VALUE()); + } + + return (int) $month; + } + + /** + * Convert day from multiple formats to int. + * + * @param mixed $day + */ + private static function getDay($day): int + { + if (($day !== null) && (!is_numeric($day))) { + $day = SharedDateHelper::dayStringToNumber($day); + } + + $day = ($day !== null) ? StringHelper::testStringAsNumeric((string) $day) : 0; + if (!is_numeric($day)) { + throw new Exception(ExcelError::VALUE()); + } + + return (int) $day; + } + + private static function adjustYearMonth(int &$year, int &$month, int $baseYear): void + { + if ($month < 1) { + // Handle year/month adjustment if month < 1 + --$month; + $year += ceil($month / 12) - 1; + $month = 13 - abs($month % 12); + } elseif ($month > 12) { + // Handle year/month adjustment if month > 12 + $year += floor($month / 12); + $month = ($month % 12); + } + + // Re-validate the year parameter after adjustments + if (($year < $baseYear) || ($year >= 10000)) { + throw new Exception(ExcelError::NAN()); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php new file mode 100644 index 00000000..b669eb0a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateParts.php @@ -0,0 +1,151 @@ += 0) { + return $weirdResult; + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('j'); + } + + /** + * MONTHOFYEAR. + * + * Returns the month of a date represented by a serial number. + * The month is given as an integer, ranging from 1 (January) to 12 (December). + * + * Excel Function: + * MONTH(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * Or can be an array of date values + * + * @return array|int|string Month of the year + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function month($dateValue) + { + if (is_array($dateValue)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { + return 1; + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('n'); + } + + /** + * YEAR. + * + * Returns the year corresponding to a date. + * The year is returned as an integer in the range 1900-9999. + * + * Excel Function: + * YEAR(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * Or can be an array of date values + * + * @return array|int|string Year + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function year($dateValue) + { + if (is_array($dateValue)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($dateValue < 1 && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900) { + return 1900; + } + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + + return (int) $PHPDateObject->format('Y'); + } + + /** + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + */ + private static function weirdCondition($dateValue): int + { + // Excel does not treat 0 consistently for DAY vs. (MONTH or YEAR) + if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900 && Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { + if (is_bool($dateValue)) { + return (int) $dateValue; + } + if ($dateValue === null) { + return 0; + } + if (is_numeric($dateValue) && $dateValue < 1 && $dateValue >= 0) { + return 0; + } + } + + return -1; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php new file mode 100644 index 00000000..466fe4a6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/DateValue.php @@ -0,0 +1,157 @@ + 31)) { + if ($yearFound) { + return ExcelError::VALUE(); + } + if ($t < 100) { + $t += 1900; + } + $yearFound = true; + } + } + if (count($t1) === 1) { + // We've been fed a time value without any date + return ((strpos((string) $t, ':') === false)) ? ExcelError::Value() : 0.0; + } + unset($t); + + $dateValue = self::t1ToString($t1, $dti, $yearFound); + + $PHPDateArray = self::setUpArray($dateValue, $dti); + + return self::finalResults($PHPDateArray, $dti, $baseYear); + } + + private static function t1ToString(array $t1, DateTimeImmutable $dti, bool $yearFound): string + { + if (count($t1) == 2) { + // We only have two parts of the date: either day/month or month/year + if ($yearFound) { + array_unshift($t1, 1); + } else { + if (is_numeric($t1[1]) && $t1[1] > 29) { + $t1[1] += 1900; + array_unshift($t1, 1); + } else { + $t1[] = $dti->format('Y'); + } + } + } + $dateValue = implode(' ', $t1); + + return $dateValue; + } + + /** + * Parse date. + */ + private static function setUpArray(string $dateValue, DateTimeImmutable $dti): array + { + $PHPDateArray = Helpers::dateParse($dateValue); + if (!Helpers::dateParseSucceeded($PHPDateArray)) { + // If original count was 1, we've already returned. + // If it was 2, we added another. + // Therefore, neither of the first 2 stroks below can fail. + $testVal1 = strtok($dateValue, '- '); + $testVal2 = strtok('- '); + $testVal3 = strtok('- ') ?: $dti->format('Y'); + Helpers::adjustYear((string) $testVal1, (string) $testVal2, $testVal3); + $PHPDateArray = Helpers::dateParse($testVal1 . '-' . $testVal2 . '-' . $testVal3); + if (!Helpers::dateParseSucceeded($PHPDateArray)) { + $PHPDateArray = Helpers::dateParse($testVal2 . '-' . $testVal1 . '-' . $testVal3); + } + } + + return $PHPDateArray; + } + + /** + * Final results. + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + private static function finalResults(array $PHPDateArray, DateTimeImmutable $dti, int $baseYear) + { + $retValue = ExcelError::Value(); + if (Helpers::dateParseSucceeded($PHPDateArray)) { + // Execute function + Helpers::replaceIfEmpty($PHPDateArray['year'], $dti->format('Y')); + if ($PHPDateArray['year'] < $baseYear) { + return ExcelError::VALUE(); + } + Helpers::replaceIfEmpty($PHPDateArray['month'], $dti->format('m')); + Helpers::replaceIfEmpty($PHPDateArray['day'], $dti->format('d')); + $PHPDateArray['hour'] = 0; + $PHPDateArray['minute'] = 0; + $PHPDateArray['second'] = 0; + $month = (int) $PHPDateArray['month']; + $day = (int) $PHPDateArray['day']; + $year = (int) $PHPDateArray['year']; + if (!checkdate($month, $day, $year)) { + return ($year === 1900 && $month === 2 && $day === 29) ? Helpers::returnIn3FormatsFloat(60.0) : ExcelError::VALUE(); + } + $retValue = Helpers::returnIn3FormatsArray($PHPDateArray, true); + } + + return $retValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php new file mode 100644 index 00000000..a3b97451 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days.php @@ -0,0 +1,62 @@ +getMessage(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + + $days = ExcelError::VALUE(); + $diff = $PHPStartDateObject->diff($PHPEndDateObject); + if ($diff !== false && !is_bool($diff->days)) { + $days = $diff->days; + if ($diff->invert) { + $days = -$days; + } + } + + return $days; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php new file mode 100644 index 00000000..6f71621e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Days360.php @@ -0,0 +1,118 @@ +getMessage(); + } + + if (!is_bool($method)) { + return ExcelError::VALUE(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $startDay = $PHPStartDateObject->format('j'); + $startMonth = $PHPStartDateObject->format('n'); + $startYear = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + $endDay = $PHPEndDateObject->format('j'); + $endMonth = $PHPEndDateObject->format('n'); + $endYear = $PHPEndDateObject->format('Y'); + + return self::dateDiff360((int) $startDay, (int) $startMonth, (int) $startYear, (int) $endDay, (int) $endMonth, (int) $endYear, !$method); + } + + /** + * Return the number of days between two dates based on a 360 day calendar. + */ + private static function dateDiff360(int $startDay, int $startMonth, int $startYear, int $endDay, int $endMonth, int $endYear, bool $methodUS): int + { + $startDay = self::getStartDay($startDay, $startMonth, $startYear, $methodUS); + $endDay = self::getEndDay($endDay, $endMonth, $endYear, $startDay, $methodUS); + + return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; + } + + private static function getStartDay(int $startDay, int $startMonth, int $startYear, bool $methodUS): int + { + if ($startDay == 31) { + --$startDay; + } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !Helpers::isLeapYear($startYear))))) { + $startDay = 30; + } + + return $startDay; + } + + private static function getEndDay(int $endDay, int &$endMonth, int &$endYear, int $startDay, bool $methodUS): int + { + if ($endDay == 31) { + if ($methodUS && $startDay != 30) { + $endDay = 1; + if ($endMonth == 12) { + ++$endYear; + $endMonth = 1; + } else { + ++$endMonth; + } + } else { + $endDay = 30; + } + } + + return $endDay; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php new file mode 100644 index 00000000..ecb1cf0a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Difference.php @@ -0,0 +1,158 @@ +getMessage(); + } + + // Execute function + $PHPStartDateObject = SharedDateHelper::excelToDateTimeObject($startDate); + $startDays = (int) $PHPStartDateObject->format('j'); + $startMonths = (int) $PHPStartDateObject->format('n'); + $startYears = (int) $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = SharedDateHelper::excelToDateTimeObject($endDate); + $endDays = (int) $PHPEndDateObject->format('j'); + $endMonths = (int) $PHPEndDateObject->format('n'); + $endYears = (int) $PHPEndDateObject->format('Y'); + + $PHPDiffDateObject = $PHPEndDateObject->diff($PHPStartDateObject); + + $retVal = false; + $retVal = self::replaceRetValue($retVal, $unit, 'D') ?? self::datedifD($difference); + $retVal = self::replaceRetValue($retVal, $unit, 'M') ?? self::datedifM($PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'MD') ?? self::datedifMD($startDays, $endDays, $PHPEndDateObject, $PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'Y') ?? self::datedifY($PHPDiffDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'YD') ?? self::datedifYD($difference, $startYears, $endYears, $PHPStartDateObject, $PHPEndDateObject); + $retVal = self::replaceRetValue($retVal, $unit, 'YM') ?? self::datedifYM($PHPDiffDateObject); + + return is_bool($retVal) ? ExcelError::VALUE() : $retVal; + } + + private static function initialDiff(float $startDate, float $endDate): float + { + // Validate parameters + if ($startDate > $endDate) { + throw new Exception(ExcelError::NAN()); + } + + return $endDate - $startDate; + } + + /** + * Decide whether it's time to set retVal. + * + * @param bool|int $retVal + * + * @return null|bool|int + */ + private static function replaceRetValue($retVal, string $unit, string $compare) + { + if ($retVal !== false || $unit !== $compare) { + return $retVal; + } + + return null; + } + + private static function datedifD(float $difference): int + { + return (int) $difference; + } + + private static function datedifM(DateInterval $PHPDiffDateObject): int + { + return 12 * (int) $PHPDiffDateObject->format('%y') + (int) $PHPDiffDateObject->format('%m'); + } + + private static function datedifMD(int $startDays, int $endDays, DateTime $PHPEndDateObject, DateInterval $PHPDiffDateObject): int + { + if ($endDays < $startDays) { + $retVal = $endDays; + $PHPEndDateObject->modify('-' . $endDays . ' days'); + $adjustDays = (int) $PHPEndDateObject->format('j'); + $retVal += ($adjustDays - $startDays); + } else { + $retVal = (int) $PHPDiffDateObject->format('%d'); + } + + return $retVal; + } + + private static function datedifY(DateInterval $PHPDiffDateObject): int + { + return (int) $PHPDiffDateObject->format('%y'); + } + + private static function datedifYD(float $difference, int $startYears, int $endYears, DateTime $PHPStartDateObject, DateTime $PHPEndDateObject): int + { + $retVal = (int) $difference; + if ($endYears > $startYears) { + $isLeapStartYear = $PHPStartDateObject->format('L'); + $wasLeapEndYear = $PHPEndDateObject->format('L'); + + // Adjust end year to be as close as possible as start year + while ($PHPEndDateObject >= $PHPStartDateObject) { + $PHPEndDateObject->modify('-1 year'); + $endYears = $PHPEndDateObject->format('Y'); + } + $PHPEndDateObject->modify('+1 year'); + + // Get the result + $retVal = $PHPEndDateObject->diff($PHPStartDateObject)->days; + + // Adjust for leap years cases + $isLeapEndYear = $PHPEndDateObject->format('L'); + $limit = new DateTime($PHPEndDateObject->format('Y-02-29')); + if (!$isLeapStartYear && !$wasLeapEndYear && $isLeapEndYear && $PHPEndDateObject >= $limit) { + --$retVal; + } + } + + return (int) $retVal; + } + + private static function datedifYM(DateInterval $PHPDiffDateObject): int + { + return (int) $PHPDiffDateObject->format('%m'); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php new file mode 100644 index 00000000..23845153 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Helpers.php @@ -0,0 +1,307 @@ +format('m'); + $oYear = (int) $PHPDateObject->format('Y'); + + $adjustmentMonthsString = (string) $adjustmentMonths; + if ($adjustmentMonths > 0) { + $adjustmentMonthsString = '+' . $adjustmentMonths; + } + if ($adjustmentMonths != 0) { + $PHPDateObject->modify($adjustmentMonthsString . ' months'); + } + $nMonth = (int) $PHPDateObject->format('m'); + $nYear = (int) $PHPDateObject->format('Y'); + + $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); + if ($monthDiff != $adjustmentMonths) { + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-' . $adjustDays . ' days'; + $PHPDateObject->modify($adjustDaysString); + } + + return $PHPDateObject; + } + + /** + * Help reduce perceived complexity of some tests. + * + * @param mixed $value + * @param mixed $altValue + */ + public static function replaceIfEmpty(&$value, $altValue): void + { + $value = $value ?: $altValue; + } + + /** + * Adjust year in ambiguous situations. + */ + public static function adjustYear(string $testVal1, string $testVal2, string &$testVal3): void + { + if (!is_numeric($testVal1) || $testVal1 < 31) { + if (!is_numeric($testVal2) || $testVal2 < 12) { + if (is_numeric($testVal3) && $testVal3 < 12) { + $testVal3 += 2000; + } + } + } + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsArray(array $dateArray, bool $noFrac = false) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { + return new DateTime( + $dateArray['year'] + . '-' . $dateArray['month'] + . '-' . $dateArray['day'] + . ' ' . $dateArray['hour'] + . ':' . $dateArray['minute'] + . ':' . $dateArray['second'] + ); + } + $excelDateValue = + SharedDateHelper::formattedPHPToExcel( + $dateArray['year'], + $dateArray['month'], + $dateArray['day'], + $dateArray['hour'], + $dateArray['minute'], + $dateArray['second'] + ); + if ($retType === Functions::RETURNDATE_EXCEL) { + return $noFrac ? floor($excelDateValue) : (float) $excelDateValue; + } + // RETURNDATE_UNIX_TIMESTAMP) + + return (int) SharedDateHelper::excelToTimestamp($excelDateValue); + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsFloat(float $excelDateValue) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + return $excelDateValue; + } + if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + return (int) SharedDateHelper::excelToTimestamp($excelDateValue); + } + // RETURNDATE_PHP_DATETIME_OBJECT + + return SharedDateHelper::excelToDateTimeObject($excelDateValue); + } + + /** + * Return result in one of three formats. + * + * @return mixed + */ + public static function returnIn3FormatsObject(DateTime $PHPDateObject) + { + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_PHP_DATETIME_OBJECT) { + return $PHPDateObject; + } + if ($retType === Functions::RETURNDATE_EXCEL) { + return (float) SharedDateHelper::PHPToExcel($PHPDateObject); + } + // RETURNDATE_UNIX_TIMESTAMP + $stamp = SharedDateHelper::PHPToExcel($PHPDateObject); + $stamp = is_bool($stamp) ? ((int) $stamp) : $stamp; + + return (int) SharedDateHelper::excelToTimestamp($stamp); + } + + private static function baseDate(): int + { + if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { + return 0; + } + if (SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904) { + return 0; + } + + return 1; + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + */ + public static function nullFalseTrueToNumber(&$number, bool $allowBool = true): void + { + $number = Functions::flattenSingleValue($number); + $nullVal = self::baseDate(); + if ($number === null) { + $number = $nullVal; + } elseif ($allowBool && is_bool($number)) { + $number = $nullVal + (int) $number; + } + } + + /** + * Many functions accept null argument treated as 0. + * + * @param mixed $number + * + * @return float|int + */ + public static function validateNumericNull($number) + { + $number = Functions::flattenSingleValue($number); + if ($number === null) { + return 0; + } + if (is_int($number)) { + return $number; + } + if (is_numeric($number)) { + return (float) $number; + } + + throw new Exception(ExcelError::VALUE()); + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + * + * @return float + */ + public static function validateNotNegative($number) + { + if (!is_numeric($number)) { + throw new Exception(ExcelError::VALUE()); + } + if ($number >= 0) { + return (float) $number; + } + + throw new Exception(ExcelError::NAN()); + } + + public static function silly1900(DateTime $PHPDateObject, string $mod = '-1 day'): void + { + $isoDate = $PHPDateObject->format('c'); + if ($isoDate < '1900-03-01') { + $PHPDateObject->modify($mod); + } + } + + public static function dateParse(string $string): array + { + return self::forceArray(date_parse($string)); + } + + public static function dateParseSucceeded(array $dateArray): bool + { + return $dateArray['error_count'] === 0; + } + + /** + * Despite documentation, date_parse probably never returns false. + * Just in case, this routine helps guarantee it. + * + * @param array|false $dateArray + */ + private static function forceArray($dateArray): array + { + return is_array($dateArray) ? $dateArray : ['error_count' => 1]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php new file mode 100644 index 00000000..c72d006b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Month.php @@ -0,0 +1,101 @@ +getMessage(); + } + $adjustmentMonths = floor($adjustmentMonths); + + // Execute function + $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths); + + return Helpers::returnIn3FormatsObject($PHPDateObject); + } + + /** + * EOMONTH. + * + * Returns the date value for the last day of the month that is the indicated number of months + * before or after start_date. + * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. + * + * Excel Function: + * EOMONTH(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * Or can be an array of date values + * @param array|int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * Or can be an array of adjustment values + * + * @return array|mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + * If an array of values is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function lastDay($dateValue, $adjustmentMonths) + { + if (is_array($dateValue) || is_array($adjustmentMonths)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $adjustmentMonths); + } + + try { + $dateValue = Helpers::getDateValue($dateValue, false); + $adjustmentMonths = Helpers::validateNumericNull($adjustmentMonths); + } catch (Exception $e) { + return $e->getMessage(); + } + $adjustmentMonths = floor($adjustmentMonths); + + // Execute function + $PHPDateObject = Helpers::adjustDateByMonths($dateValue, $adjustmentMonths + 1); + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-' . $adjustDays . ' days'; + $PHPDateObject->modify($adjustDaysString); + + return Helpers::returnIn3FormatsObject($PHPDateObject); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php new file mode 100644 index 00000000..3b8942ba --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/NetworkDays.php @@ -0,0 +1,119 @@ +getMessage(); + } + + // Execute function + $startDow = self::calcStartDow($startDate); + $endDow = self::calcEndDow($endDate); + $wholeWeekDays = (int) floor(($endDate - $startDate) / 7) * 5; + $partWeekDays = self::calcPartWeekDays($startDow, $endDow); + + // Test any extra holiday parameters + $holidayCountedArray = []; + foreach ($holidayArray as $holidayDate) { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if ((Week::day($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { + --$partWeekDays; + $holidayCountedArray[] = $holidayDate; + } + } + } + + return self::applySign($wholeWeekDays + $partWeekDays, $sDate, $eDate); + } + + private static function calcStartDow(float $startDate): int + { + $startDow = 6 - (int) Week::day($startDate, 2); + if ($startDow < 0) { + $startDow = 5; + } + + return $startDow; + } + + private static function calcEndDow(float $endDate): int + { + $endDow = (int) Week::day($endDate, 2); + if ($endDow >= 6) { + $endDow = 0; + } + + return $endDow; + } + + private static function calcPartWeekDays(int $startDow, int $endDow): int + { + $partWeekDays = $endDow + $startDow; + if ($partWeekDays > 5) { + $partWeekDays -= 5; + } + + return $partWeekDays; + } + + private static function applySign(int $result, float $sDate, float $eDate): int + { + return ($sDate > $eDate) ? -$result : $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php new file mode 100644 index 00000000..4ff71983 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Time.php @@ -0,0 +1,130 @@ +getMessage(); + } + + self::adjustSecond($second, $minute); + self::adjustMinute($minute, $hour); + + if ($hour > 23) { + $hour = $hour % 24; + } elseif ($hour < 0) { + return ExcelError::NAN(); + } + + // Execute function + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + $calendar = SharedDateHelper::getExcelCalendar(); + $date = (int) ($calendar !== SharedDateHelper::CALENDAR_WINDOWS_1900); + + return (float) SharedDateHelper::formattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); + } + if ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + return (int) SharedDateHelper::excelToTimestamp(SharedDateHelper::formattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 + } + // RETURNDATE_PHP_DATETIME_OBJECT + // Hour has already been normalized (0-23) above + $phpDateObject = new DateTime('1900-01-01 ' . $hour . ':' . $minute . ':' . $second); + + return $phpDateObject; + } + + private static function adjustSecond(int &$second, int &$minute): void + { + if ($second < 0) { + $minute += floor($second / 60); + $second = 60 - abs($second % 60); + if ($second == 60) { + $second = 0; + } + } elseif ($second >= 60) { + $minute += floor($second / 60); + $second = $second % 60; + } + } + + private static function adjustMinute(int &$minute, int &$hour): void + { + if ($minute < 0) { + $hour += floor($minute / 60); + $minute = 60 - abs($minute % 60); + if ($minute == 60) { + $minute = 0; + } + } elseif ($minute >= 60) { + $hour += floor($minute / 60); + $minute = $minute % 60; + } + } + + /** + * @param mixed $value expect int + */ + private static function toIntWithNullBool($value): int + { + $value = $value ?? 0; + if (is_bool($value)) { + $value = (int) $value; + } + if (!is_numeric($value)) { + throw new Exception(ExcelError::VALUE()); + } + + return (int) $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php new file mode 100644 index 00000000..d9b99f3c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeParts.php @@ -0,0 +1,132 @@ +getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('H'); + } + + /** + * MINUTE. + * + * Returns the minutes of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * MINUTE(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * Or can be an array of date/time values + * + * @return array|int|string Minute + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function minute($timeValue) + { + if (is_array($timeValue)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); + } + + try { + Helpers::nullFalseTrueToNumber($timeValue); + if (!is_numeric($timeValue)) { + $timeValue = Helpers::getTimeValue($timeValue); + } + Helpers::validateNotNegative($timeValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('i'); + } + + /** + * SECOND. + * + * Returns the seconds of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * SECOND(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * Or can be an array of date/time values + * + * @return array|int|string Second + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function second($timeValue) + { + if (is_array($timeValue)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $timeValue); + } + + try { + Helpers::nullFalseTrueToNumber($timeValue); + if (!is_numeric($timeValue)) { + $timeValue = Helpers::getTimeValue($timeValue); + } + Helpers::validateNotNegative($timeValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $timeValue = fmod($timeValue, 1); + $timeValue = SharedDateHelper::excelToDateTimeObject($timeValue); + + return (int) $timeValue->format('s'); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php new file mode 100644 index 00000000..aa27206b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/TimeValue.php @@ -0,0 +1,78 @@ + 24) { + $arraySplit[0] = ($arraySplit[0] % 24); + $timeValue = implode(':', $arraySplit); + } + + $PHPDateArray = Helpers::dateParse($timeValue); + $retValue = ExcelError::VALUE(); + if (Helpers::dateParseSucceeded($PHPDateArray)) { + /** @var int */ + $hour = $PHPDateArray['hour']; + /** @var int */ + $minute = $PHPDateArray['minute']; + /** @var int */ + $second = $PHPDateArray['second']; + // OpenOffice-specific code removed - it works just like Excel + $excelDateValue = SharedDateHelper::formattedPHPToExcel(1900, 1, 1, $hour, $minute, $second) - 1; + + $retType = Functions::getReturnDateType(); + if ($retType === Functions::RETURNDATE_EXCEL) { + $retValue = (float) $excelDateValue; + } elseif ($retType === Functions::RETURNDATE_UNIX_TIMESTAMP) { + $retValue = (int) $phpDateValue = SharedDateHelper::excelToTimestamp($excelDateValue + 25569) - 3600; + } else { + $retValue = new DateTime('1900-01-01 ' . $PHPDateArray['hour'] . ':' . $PHPDateArray['minute'] . ':' . $PHPDateArray['second']); + } + } + + return $retValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php new file mode 100644 index 00000000..2f69007d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/Week.php @@ -0,0 +1,278 @@ +getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + if ($method == Constants::STARTWEEK_MONDAY_ISO) { + Helpers::silly1900($PHPDateObject); + + return (int) $PHPDateObject->format('W'); + } + if (self::buggyWeekNum1904($method, $origDateValueNull, $PHPDateObject)) { + return 0; + } + Helpers::silly1900($PHPDateObject, '+ 5 years'); // 1905 calendar matches + $dayOfYear = (int) $PHPDateObject->format('z'); + $PHPDateObject->modify('-' . $dayOfYear . ' days'); + $firstDayOfFirstWeek = (int) $PHPDateObject->format('w'); + $daysInFirstWeek = (6 - $firstDayOfFirstWeek + $method) % 7; + $daysInFirstWeek += 7 * !$daysInFirstWeek; + $endFirstWeek = $daysInFirstWeek - 1; + $weekOfYear = floor(($dayOfYear - $endFirstWeek + 13) / 7); + + return (int) $weekOfYear; + } + + /** + * ISOWEEKNUM. + * + * Returns the ISO 8601 week number of the year for a specified date. + * + * Excel Function: + * ISOWEEKNUM(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * Or can be an array of date values + * + * @return array|int|string Week Number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isoWeekNumber($dateValue) + { + if (is_array($dateValue)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $dateValue); + } + + if (self::apparentBug($dateValue)) { + return 52; + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + Helpers::silly1900($PHPDateObject); + + return (int) $PHPDateObject->format('W'); + } + + /** + * WEEKDAY. + * + * Returns the day of the week for a specified date. The day is given as an integer + * ranging from 0 to 7 (dependent on the requested style). + * + * Excel Function: + * WEEKDAY(dateValue[,style]) + * + * @param null|array|float|int|string $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * Or can be an array of date values + * @param mixed $style A number that determines the type of return value + * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). + * 2 Numbers 1 (Monday) through 7 (Sunday). + * 3 Numbers 0 (Monday) through 6 (Sunday). + * Or can be an array of styles + * + * @return array|int|string Day of the week value + * If an array of values is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function day($dateValue, $style = 1) + { + if (is_array($dateValue) || is_array($style)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $dateValue, $style); + } + + try { + $dateValue = Helpers::getDateValue($dateValue); + $style = self::validateStyle($style); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Execute function + $PHPDateObject = SharedDateHelper::excelToDateTimeObject($dateValue); + Helpers::silly1900($PHPDateObject); + $DoW = (int) $PHPDateObject->format('w'); + + switch ($style) { + case 1: + ++$DoW; + + break; + case 2: + $DoW = self::dow0Becomes7($DoW); + + break; + case 3: + $DoW = self::dow0Becomes7($DoW) - 1; + + break; + } + + return $DoW; + } + + /** + * @param mixed $style expect int + */ + private static function validateStyle($style): int + { + if (!is_numeric($style)) { + throw new Exception(ExcelError::VALUE()); + } + $style = (int) $style; + if (($style < 1) || ($style > 3)) { + throw new Exception(ExcelError::NAN()); + } + + return $style; + } + + private static function dow0Becomes7(int $DoW): int + { + return ($DoW === 0) ? 7 : $DoW; + } + + /** + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + */ + private static function apparentBug($dateValue): bool + { + if (SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { + if (is_bool($dateValue)) { + return true; + } + if (is_numeric($dateValue) && !((int) $dateValue)) { + return true; + } + } + + return false; + } + + /** + * Validate dateValue parameter. + * + * @param mixed $dateValue + */ + private static function validateDateValue($dateValue): float + { + if (is_bool($dateValue)) { + throw new Exception(ExcelError::VALUE()); + } + + return Helpers::getDateValue($dateValue); + } + + /** + * Validate method parameter. + * + * @param mixed $method + */ + private static function validateMethod($method): int + { + if ($method === null) { + $method = Constants::STARTWEEK_SUNDAY; + } + + if (!is_numeric($method)) { + throw new Exception(ExcelError::VALUE()); + } + + $method = (int) $method; + if (!array_key_exists($method, Constants::METHODARR)) { + throw new Exception(ExcelError::NAN()); + } + $method = Constants::METHODARR[$method]; + + return $method; + } + + private static function buggyWeekNum1900(int $method): bool + { + return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_WINDOWS_1900; + } + + private static function buggyWeekNum1904(int $method, bool $origNull, DateTime $dateObject): bool + { + // This appears to be another Excel bug. + + return $method === Constants::DOW_SUNDAY && SharedDateHelper::getExcelCalendar() === SharedDateHelper::CALENDAR_MAC_1904 && + !$origNull && $dateObject->format('Y-m-d') === '1904-01-01'; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php new file mode 100644 index 00000000..1f5735e8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/WorkDay.php @@ -0,0 +1,201 @@ +getMessage(); + } + + $startDate = (float) floor($startDate); + $endDays = (int) floor($endDays); + // If endDays is 0, we always return startDate + if ($endDays == 0) { + return $startDate; + } + if ($endDays < 0) { + return self::decrementing($startDate, $endDays, $holidayArray); + } + + return self::incrementing($startDate, $endDays, $holidayArray); + } + + /** + * Use incrementing logic to determine Workday. + * + * @return mixed + */ + private static function incrementing(float $startDate, int $endDays, array $holidayArray) + { + // Adjust the start date if it falls over a weekend + $startDoW = self::getWeekDay($startDate, 3); + if ($startDoW >= 5) { + $startDate += 7 - $startDoW; + --$endDays; + } + + // Add endDays + $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); + $endDays = $endDays % 5; + while ($endDays > 0) { + ++$endDate; + // Adjust the calculated end date if it falls over a weekend + $endDow = self::getWeekDay($endDate, 3); + if ($endDow >= 5) { + $endDate += 7 - $endDow; + } + --$endDays; + } + + // Test any extra holiday parameters + if (!empty($holidayArray)) { + $endDate = self::incrementingArray($startDate, $endDate, $holidayArray); + } + + return Helpers::returnIn3FormatsFloat($endDate); + } + + private static function incrementingArray(float $startDate, float $endDate, array $holidayArray): float + { + $holidayCountedArray = $holidayDates = []; + foreach ($holidayArray as $holidayDate) { + if (self::getWeekDay($holidayDate, 3) < 5) { + $holidayDates[] = $holidayDate; + } + } + sort($holidayDates, SORT_NUMERIC); + foreach ($holidayDates as $holidayDate) { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + ++$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::getWeekDay($endDate, 3); + if ($endDoW >= 5) { + $endDate += 7 - $endDoW; + } + } + + return $endDate; + } + + /** + * Use decrementing logic to determine Workday. + * + * @return mixed + */ + private static function decrementing(float $startDate, int $endDays, array $holidayArray) + { + // Adjust the start date if it falls over a weekend + $startDoW = self::getWeekDay($startDate, 3); + if ($startDoW >= 5) { + $startDate += -$startDoW + 4; + ++$endDays; + } + + // Add endDays + $endDate = (float) $startDate + ((int) ($endDays / 5) * 7); + $endDays = $endDays % 5; + while ($endDays < 0) { + --$endDate; + // Adjust the calculated end date if it falls over a weekend + $endDow = self::getWeekDay($endDate, 3); + if ($endDow >= 5) { + $endDate += 4 - $endDow; + } + ++$endDays; + } + + // Test any extra holiday parameters + if (!empty($holidayArray)) { + $endDate = self::decrementingArray($startDate, $endDate, $holidayArray); + } + + return Helpers::returnIn3FormatsFloat($endDate); + } + + private static function decrementingArray(float $startDate, float $endDate, array $holidayArray): float + { + $holidayCountedArray = $holidayDates = []; + foreach ($holidayArray as $holidayDate) { + if (self::getWeekDay($holidayDate, 3) < 5) { + $holidayDates[] = $holidayDate; + } + } + rsort($holidayDates, SORT_NUMERIC); + foreach ($holidayDates as $holidayDate) { + if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + --$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::getWeekDay($endDate, 3); + /** int $endDoW */ + if ($endDoW >= 5) { + $endDate += -$endDoW + 4; + } + } + + return $endDate; + } + + private static function getWeekDay(float $date, int $wd): int + { + $result = Functions::scalar(Week::day($date, $wd)); + + return is_int($result) ? $result : -1; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php new file mode 100644 index 00000000..394c6b73 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/DateTimeExcel/YearFrac.php @@ -0,0 +1,133 @@ +getMessage(); + } + + switch ($method) { + case 0: + return Functions::scalar(Days360::between($startDate, $endDate)) / 360; + case 1: + return self::method1($startDate, $endDate); + case 2: + return Functions::scalar(Difference::interval($startDate, $endDate)) / 360; + case 3: + return Functions::scalar(Difference::interval($startDate, $endDate)) / 365; + case 4: + return Functions::scalar(Days360::between($startDate, $endDate, true)) / 360; + } + + return ExcelError::NAN(); + } + + /** + * Excel 1900 calendar treats date argument of null as 1900-01-00. Really. + * + * @param mixed $startDate + * @param mixed $endDate + */ + private static function excelBug(float $sDate, $startDate, $endDate, int $method): float + { + if (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE && SharedDateHelper::getExcelCalendar() !== SharedDateHelper::CALENDAR_MAC_1904) { + if ($endDate === null && $startDate !== null) { + if (DateParts::month($sDate) == 12 && DateParts::day($sDate) === 31 && $method === 0) { + $sDate += 2; + } else { + ++$sDate; + } + } + } + + return $sDate; + } + + private static function method1(float $startDate, float $endDate): float + { + $days = Functions::scalar(Difference::interval($startDate, $endDate)); + $startYear = (int) DateParts::year($startDate); + $endYear = (int) DateParts::year($endDate); + $years = $endYear - $startYear + 1; + $startMonth = (int) DateParts::month($startDate); + $startDay = (int) DateParts::day($startDate); + $endMonth = (int) DateParts::month($endDate); + $endDay = (int) DateParts::day($endDate); + $startMonthDay = 100 * $startMonth + $startDay; + $endMonthDay = 100 * $endMonth + $endDay; + if ($years == 1) { + $tmpCalcAnnualBasis = 365 + (int) Helpers::isLeapYear($endYear); + } elseif ($years == 2 && $startMonthDay >= $endMonthDay) { + if (Helpers::isLeapYear($startYear)) { + $tmpCalcAnnualBasis = 365 + (int) ($startMonthDay <= 229); + } elseif (Helpers::isLeapYear($endYear)) { + $tmpCalcAnnualBasis = 365 + (int) ($endMonthDay >= 229); + } else { + $tmpCalcAnnualBasis = 365; + } + } else { + $tmpCalcAnnualBasis = 0; + for ($year = $startYear; $year <= $endYear; ++$year) { + $tmpCalcAnnualBasis += 365 + (int) Helpers::isLeapYear($year); + } + $tmpCalcAnnualBasis /= $years; + } + + return $days / $tmpCalcAnnualBasis; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php new file mode 100644 index 00000000..fae9d900 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentHelper.php @@ -0,0 +1,209 @@ +indexStart = (int) array_shift($keys); + $this->rows = $this->rows($arguments); + $this->columns = $this->columns($arguments); + + $this->argumentCount = count($arguments); + $this->arguments = $this->flattenSingleCellArrays($arguments, $this->rows, $this->columns); + + $this->rows = $this->rows($arguments); + $this->columns = $this->columns($arguments); + + if ($this->arrayArguments() > 2) { + throw new Exception('Formulae with more than two array arguments are not supported'); + } + } + + public function arguments(): array + { + return $this->arguments; + } + + public function hasArrayArgument(): bool + { + return $this->arrayArguments() > 0; + } + + public function getFirstArrayArgumentNumber(): int + { + $rowArrays = $this->filterArray($this->rows); + $columnArrays = $this->filterArray($this->columns); + + for ($index = $this->indexStart; $index < $this->argumentCount; ++$index) { + if (isset($rowArrays[$index]) || isset($columnArrays[$index])) { + return ++$index; + } + } + + return 0; + } + + public function getSingleRowVector(): ?int + { + $rowVectors = $this->getRowVectors(); + + return count($rowVectors) === 1 ? array_pop($rowVectors) : null; + } + + private function getRowVectors(): array + { + $rowVectors = []; + for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { + if ($this->rows[$index] === 1 && $this->columns[$index] > 1) { + $rowVectors[] = $index; + } + } + + return $rowVectors; + } + + public function getSingleColumnVector(): ?int + { + $columnVectors = $this->getColumnVectors(); + + return count($columnVectors) === 1 ? array_pop($columnVectors) : null; + } + + private function getColumnVectors(): array + { + $columnVectors = []; + for ($index = $this->indexStart; $index < ($this->indexStart + $this->argumentCount); ++$index) { + if ($this->rows[$index] > 1 && $this->columns[$index] === 1) { + $columnVectors[] = $index; + } + } + + return $columnVectors; + } + + public function getMatrixPair(): array + { + for ($i = $this->indexStart; $i < ($this->indexStart + $this->argumentCount - 1); ++$i) { + for ($j = $i + 1; $j < $this->argumentCount; ++$j) { + if (isset($this->rows[$i], $this->rows[$j])) { + return [$i, $j]; + } + } + } + + return []; + } + + public function isVector(int $argument): bool + { + return $this->rows[$argument] === 1 || $this->columns[$argument] === 1; + } + + public function isRowVector(int $argument): bool + { + return $this->rows[$argument] === 1; + } + + public function isColumnVector(int $argument): bool + { + return $this->columns[$argument] === 1; + } + + public function rowCount(int $argument): int + { + return $this->rows[$argument]; + } + + public function columnCount(int $argument): int + { + return $this->columns[$argument]; + } + + private function rows(array $arguments): array + { + return array_map( + function ($argument) { + return is_countable($argument) ? count($argument) : 1; + }, + $arguments + ); + } + + private function columns(array $arguments): array + { + return array_map( + function ($argument) { + return is_array($argument) && is_array($argument[array_keys($argument)[0]]) + ? count($argument[array_keys($argument)[0]]) + : 1; + }, + $arguments + ); + } + + public function arrayArguments(): int + { + $count = 0; + foreach (array_keys($this->arguments) as $argument) { + if ($this->rows[$argument] > 1 || $this->columns[$argument] > 1) { + ++$count; + } + } + + return $count; + } + + private function flattenSingleCellArrays(array $arguments, array $rows, array $columns): array + { + foreach ($arguments as $index => $argument) { + if ($rows[$index] === 1 && $columns[$index] === 1) { + while (is_array($argument)) { + $argument = array_pop($argument); + } + $arguments[$index] = $argument; + } + } + + return $arguments; + } + + private function filterArray(array $array): array + { + return array_filter( + $array, + function ($value) { + return $value > 1; + } + ); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php new file mode 100644 index 00000000..3e69d77f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/ArrayArgumentProcessor.php @@ -0,0 +1,175 @@ +hasArrayArgument() === false) { + return [$method(...$arguments)]; + } + + if (self::$arrayArgumentHelper->arrayArguments() === 1) { + $nthArgument = self::$arrayArgumentHelper->getFirstArrayArgumentNumber(); + + return self::evaluateNthArgumentAsArray($method, $nthArgument, ...$arguments); + } + + $singleRowVectorIndex = self::$arrayArgumentHelper->getSingleRowVector(); + $singleColumnVectorIndex = self::$arrayArgumentHelper->getSingleColumnVector(); + + if ($singleRowVectorIndex !== null && $singleColumnVectorIndex !== null) { + // Basic logic for a single row vector and a single column vector + return self::evaluateVectorPair($method, $singleRowVectorIndex, $singleColumnVectorIndex, ...$arguments); + } + + $matrixPair = self::$arrayArgumentHelper->getMatrixPair(); + if ($matrixPair !== []) { + if ( + (self::$arrayArgumentHelper->isVector($matrixPair[0]) === true && + self::$arrayArgumentHelper->isVector($matrixPair[1]) === false) || + (self::$arrayArgumentHelper->isVector($matrixPair[0]) === false && + self::$arrayArgumentHelper->isVector($matrixPair[1]) === true) + ) { + // Logic for a matrix and a vector (row or column) + return self::evaluateVectorMatrixPair($method, $matrixPair, ...$arguments); + } + // Logic for matrix/matrix, column vector/column vector or row vector/row vector + return self::evaluateMatrixPair($method, $matrixPair, ...$arguments); + } + + // Still need to work out the logic for more than two array arguments, + // For the moment, we're throwing an Exception when we initialise the ArrayArgumentHelper + return ['#VALUE!']; + } + + /** + * @param mixed ...$arguments + */ + private static function evaluateVectorMatrixPair(callable $method, array $matrixIndexes, ...$arguments): array + { + $matrix2 = array_pop($matrixIndexes); + /** @var array $matrixValues2 */ + $matrixValues2 = $arguments[$matrix2]; + $matrix1 = array_pop($matrixIndexes); + /** @var array $matrixValues1 */ + $matrixValues1 = $arguments[$matrix1]; + + $rows = min(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); + $columns = min(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); + + if ($rows === 1) { + $rows = max(array_map([self::$arrayArgumentHelper, 'rowCount'], [$matrix1, $matrix2])); + } + if ($columns === 1) { + $columns = max(array_map([self::$arrayArgumentHelper, 'columnCount'], [$matrix1, $matrix2])); + } + + $result = []; + for ($rowIndex = 0; $rowIndex < $rows; ++$rowIndex) { + for ($columnIndex = 0; $columnIndex < $columns; ++$columnIndex) { + $rowIndex1 = self::$arrayArgumentHelper->isRowVector($matrix1) ? 0 : $rowIndex; + $columnIndex1 = self::$arrayArgumentHelper->isColumnVector($matrix1) ? 0 : $columnIndex; + $value1 = $matrixValues1[$rowIndex1][$columnIndex1]; + $rowIndex2 = self::$arrayArgumentHelper->isRowVector($matrix2) ? 0 : $rowIndex; + $columnIndex2 = self::$arrayArgumentHelper->isColumnVector($matrix2) ? 0 : $columnIndex; + $value2 = $matrixValues2[$rowIndex2][$columnIndex2]; + $arguments[$matrix1] = $value1; + $arguments[$matrix2] = $value2; + + $result[$rowIndex][$columnIndex] = $method(...$arguments); + } + } + + return $result; + } + + /** + * @param mixed ...$arguments + */ + private static function evaluateMatrixPair(callable $method, array $matrixIndexes, ...$arguments): array + { + $matrix2 = array_pop($matrixIndexes); + /** @var array $matrixValues2 */ + $matrixValues2 = $arguments[$matrix2]; + $matrix1 = array_pop($matrixIndexes); + /** @var array $matrixValues1 */ + $matrixValues1 = $arguments[$matrix1]; + + $result = []; + foreach ($matrixValues1 as $rowIndex => $row) { + foreach ($row as $columnIndex => $value1) { + if (isset($matrixValues2[$rowIndex][$columnIndex]) === false) { + continue; + } + + $value2 = $matrixValues2[$rowIndex][$columnIndex]; + $arguments[$matrix1] = $value1; + $arguments[$matrix2] = $value2; + + $result[$rowIndex][$columnIndex] = $method(...$arguments); + } + } + + return $result; + } + + /** + * @param mixed ...$arguments + */ + private static function evaluateVectorPair(callable $method, int $rowIndex, int $columnIndex, ...$arguments): array + { + $rowVector = Functions::flattenArray($arguments[$rowIndex]); + $columnVector = Functions::flattenArray($arguments[$columnIndex]); + + $result = []; + foreach ($columnVector as $column) { + $rowResults = []; + foreach ($rowVector as $row) { + $arguments[$rowIndex] = $row; + $arguments[$columnIndex] = $column; + + $rowResults[] = $method(...$arguments); + } + $result[] = $rowResults; + } + + return $result; + } + + /** + * Note, offset is from 1 (for the first argument) rather than from 0. + * + * @param mixed ...$arguments + */ + private static function evaluateNthArgumentAsArray(callable $method, int $nthArgument, ...$arguments): array + { + $values = array_slice($arguments, $nthArgument - 1, 1); + /** @var array $values */ + $values = array_pop($values); + + $result = []; + foreach ($values as $value) { + $arguments[$nthArgument - 1] = $value; + $result[] = $method(...$arguments); + } + + return $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php new file mode 100644 index 00000000..9cd767e6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/BranchPruner.php @@ -0,0 +1,223 @@ +branchPruningEnabled = $branchPruningEnabled; + } + + public function clearBranchStore(): void + { + $this->branchStoreKeyCounter = 0; + } + + public function initialiseForLoop(): void + { + $this->currentCondition = null; + $this->currentOnlyIf = null; + $this->currentOnlyIfNot = null; + $this->previousStoreKey = null; + $this->pendingStoreKey = empty($this->storeKeysStack) ? null : end($this->storeKeysStack); + + if ($this->branchPruningEnabled) { + $this->initialiseCondition(); + $this->initialiseThen(); + $this->initialiseElse(); + } + } + + private function initialiseCondition(): void + { + if (isset($this->conditionMap[$this->pendingStoreKey]) && $this->conditionMap[$this->pendingStoreKey]) { + $this->currentCondition = $this->pendingStoreKey; + $stackDepth = count($this->storeKeysStack); + if ($stackDepth > 1) { + // nested if + $this->previousStoreKey = $this->storeKeysStack[$stackDepth - 2]; + } + } + } + + private function initialiseThen(): void + { + if (isset($this->thenMap[$this->pendingStoreKey]) && $this->thenMap[$this->pendingStoreKey]) { + $this->currentOnlyIf = $this->pendingStoreKey; + } elseif ( + isset($this->previousStoreKey, $this->thenMap[$this->previousStoreKey]) + && $this->thenMap[$this->previousStoreKey] + ) { + $this->currentOnlyIf = $this->previousStoreKey; + } + } + + private function initialiseElse(): void + { + if (isset($this->elseMap[$this->pendingStoreKey]) && $this->elseMap[$this->pendingStoreKey]) { + $this->currentOnlyIfNot = $this->pendingStoreKey; + } elseif ( + isset($this->previousStoreKey, $this->elseMap[$this->previousStoreKey]) + && $this->elseMap[$this->previousStoreKey] + ) { + $this->currentOnlyIfNot = $this->previousStoreKey; + } + } + + public function decrementDepth(): void + { + if (!empty($this->pendingStoreKey)) { + --$this->braceDepthMap[$this->pendingStoreKey]; + } + } + + public function incrementDepth(): void + { + if (!empty($this->pendingStoreKey)) { + ++$this->braceDepthMap[$this->pendingStoreKey]; + } + } + + public function functionCall(string $functionName): void + { + if ($this->branchPruningEnabled && ($functionName === 'IF(')) { + // we handle a new if + $this->pendingStoreKey = $this->getUnusedBranchStoreKey(); + $this->storeKeysStack[] = $this->pendingStoreKey; + $this->conditionMap[$this->pendingStoreKey] = true; + $this->braceDepthMap[$this->pendingStoreKey] = 0; + } elseif (!empty($this->pendingStoreKey) && array_key_exists($this->pendingStoreKey, $this->braceDepthMap)) { + // this is not an if but we go deeper + ++$this->braceDepthMap[$this->pendingStoreKey]; + } + } + + public function argumentSeparator(): void + { + if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === 0) { + // We must go to the IF next argument + if ($this->conditionMap[$this->pendingStoreKey]) { + $this->conditionMap[$this->pendingStoreKey] = false; + $this->thenMap[$this->pendingStoreKey] = true; + } elseif ($this->thenMap[$this->pendingStoreKey]) { + $this->thenMap[$this->pendingStoreKey] = false; + $this->elseMap[$this->pendingStoreKey] = true; + } elseif ($this->elseMap[$this->pendingStoreKey]) { + throw new Exception('Reaching fourth argument of an IF'); + } + } + } + + /** + * @param mixed $value + */ + public function closingBrace($value): void + { + if (!empty($this->pendingStoreKey) && $this->braceDepthMap[$this->pendingStoreKey] === -1) { + // we are closing an IF( + if ($value !== 'IF(') { + throw new Exception('Parser bug we should be in an "IF("'); + } + + if ($this->conditionMap[$this->pendingStoreKey]) { + throw new Exception('We should not be expecting a condition'); + } + + $this->thenMap[$this->pendingStoreKey] = false; + $this->elseMap[$this->pendingStoreKey] = false; + --$this->braceDepthMap[$this->pendingStoreKey]; + array_pop($this->storeKeysStack); + $this->pendingStoreKey = null; + } + } + + public function currentCondition(): ?string + { + return $this->currentCondition; + } + + public function currentOnlyIf(): ?string + { + return $this->currentOnlyIf; + } + + public function currentOnlyIfNot(): ?string + { + return $this->currentOnlyIfNot; + } + + private function getUnusedBranchStoreKey(): string + { + $storeKeyValue = 'storeKey-' . $this->branchStoreKeyCounter; + ++$this->branchStoreKeyCounter; + + return $storeKeyValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php index 5a54d83a..b688e056 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/CyclicReferenceStack.php @@ -26,7 +26,7 @@ public function count() * * @param mixed $value */ - public function push($value) + public function push($value): void { $this->stack[$value] = $value; } @@ -56,7 +56,7 @@ public function onStack($value) /** * Clear the stack. */ - public function clear() + public function clear(): void { $this->stack = []; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php index 6793dade..c6ee5969 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engine/Logger.php @@ -39,8 +39,6 @@ class Logger /** * Instantiate a Calculation engine logger. - * - * @param CyclicReferenceStack $stack */ public function __construct(CyclicReferenceStack $stack) { @@ -50,11 +48,11 @@ public function __construct(CyclicReferenceStack $stack) /** * Enable/Disable Calculation engine logging. * - * @param bool $pValue + * @param bool $writeDebugLog */ - public function setWriteDebugLog($pValue) + public function setWriteDebugLog($writeDebugLog): void { - $this->writeDebugLog = $pValue; + $this->writeDebugLog = $writeDebugLog; } /** @@ -70,11 +68,11 @@ public function getWriteDebugLog() /** * Enable/Disable echoing of debug log information. * - * @param bool $pValue + * @param bool $echoDebugLog */ - public function setEchoDebugLog($pValue) + public function setEchoDebugLog($echoDebugLog): void { - $this->echoDebugLog = $pValue; + $this->echoDebugLog = $echoDebugLog; } /** @@ -89,12 +87,14 @@ public function getEchoDebugLog() /** * Write an entry to the calculation engine debug log. + * + * @param mixed $args */ - public function writeDebugLog(...$args) + public function writeDebugLog(string $message, ...$args): void { // Only write the debug log if logging is enabled if ($this->writeDebugLog) { - $message = implode($args); + $message = sprintf($message, ...$args); $cellReference = implode(' -> ', $this->cellStack->showStack()); if ($this->echoDebugLog) { echo $cellReference, @@ -108,10 +108,24 @@ public function writeDebugLog(...$args) } } + /** + * Write a series of entries to the calculation engine debug log. + * + * @param string[] $args + */ + public function mergeDebugLog(array $args): void + { + if ($this->writeDebugLog) { + foreach ($args as $entry) { + $this->writeDebugLog($entry); + } + } + } + /** * Clear the calculation engine debug log. */ - public function clearLog() + public function clearLog(): void { $this->debugLog = []; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php index c3942b2b..d70b32d6 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering.php @@ -3,725 +3,28 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; use Complex\Complex; -use Complex\Exception as ComplexException; +use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexFunctions; +use PhpOffice\PhpSpreadsheet\Calculation\Engineering\ComplexOperations; +/** + * @deprecated 1.18.0 + */ class Engineering { /** * EULER. - */ - const EULER = 2.71828182845904523536; - - /** - * Details of the Units of measure that can be used in CONVERTUOM(). - * - * @var mixed[] - */ - private static $conversionUnits = [ - 'g' => ['Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true], - 'sg' => ['Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false], - 'lbm' => ['Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], - 'u' => ['Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], - 'ozm' => ['Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], - 'm' => ['Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true], - 'mi' => ['Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], - 'Nmi' => ['Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], - 'in' => ['Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false], - 'ft' => ['Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false], - 'yd' => ['Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false], - 'ang' => ['Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], - 'Pica' => ['Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], - 'yr' => ['Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false], - 'day' => ['Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false], - 'hr' => ['Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false], - 'mn' => ['Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false], - 'sec' => ['Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true], - 'Pa' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], - 'p' => ['Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true], - 'atm' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], - 'at' => ['Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], - 'mmHg' => ['Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], - 'N' => ['Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true], - 'dyn' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], - 'dy' => ['Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true], - 'lbf' => ['Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false], - 'J' => ['Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true], - 'e' => ['Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true], - 'c' => ['Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], - 'cal' => ['Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], - 'eV' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], - 'ev' => ['Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], - 'HPh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], - 'hh' => ['Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], - 'Wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], - 'wh' => ['Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], - 'flb' => ['Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], - 'BTU' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], - 'btu' => ['Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false], - 'HP' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], - 'h' => ['Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], - 'W' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], - 'w' => ['Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true], - 'T' => ['Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true], - 'ga' => ['Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true], - 'C' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], - 'cel' => ['Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false], - 'F' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], - 'fah' => ['Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false], - 'K' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], - 'kel' => ['Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], - 'tsp' => ['Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], - 'tbs' => ['Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], - 'oz' => ['Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], - 'cup' => ['Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false], - 'pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], - 'us_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], - 'uk_pt' => ['Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], - 'qt' => ['Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false], - 'gal' => ['Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false], - 'l' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], - 'lt' => ['Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true], - ]; - - /** - * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * - * @var mixed[] + * @deprecated 1.18.0 + * @see Use Engineering\Constants\EULER instead */ - private static $conversionMultipliers = [ - 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], - 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], - 'E' => ['multiplier' => 1E18, 'name' => 'exa'], - 'P' => ['multiplier' => 1E15, 'name' => 'peta'], - 'T' => ['multiplier' => 1E12, 'name' => 'tera'], - 'G' => ['multiplier' => 1E9, 'name' => 'giga'], - 'M' => ['multiplier' => 1E6, 'name' => 'mega'], - 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], - 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], - 'e' => ['multiplier' => 1E1, 'name' => 'deka'], - 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], - 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], - 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], - 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], - 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], - 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], - 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], - 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], - 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], - 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], - ]; - - /** - * Details of the Units of measure conversion factors, organised by group. - * - * @var mixed[] - */ - private static $unitConversions = [ - 'Mass' => [ - 'g' => [ - 'g' => 1.0, - 'sg' => 6.85220500053478E-05, - 'lbm' => 2.20462291469134E-03, - 'u' => 6.02217000000000E+23, - 'ozm' => 3.52739718003627E-02, - ], - 'sg' => [ - 'g' => 1.45938424189287E+04, - 'sg' => 1.0, - 'lbm' => 3.21739194101647E+01, - 'u' => 8.78866000000000E+27, - 'ozm' => 5.14782785944229E+02, - ], - 'lbm' => [ - 'g' => 4.5359230974881148E+02, - 'sg' => 3.10810749306493E-02, - 'lbm' => 1.0, - 'u' => 2.73161000000000E+26, - 'ozm' => 1.60000023429410E+01, - ], - 'u' => [ - 'g' => 1.66053100460465E-24, - 'sg' => 1.13782988532950E-28, - 'lbm' => 3.66084470330684E-27, - 'u' => 1.0, - 'ozm' => 5.85735238300524E-26, - ], - 'ozm' => [ - 'g' => 2.83495152079732E+01, - 'sg' => 1.94256689870811E-03, - 'lbm' => 6.24999908478882E-02, - 'u' => 1.70725600000000E+25, - 'ozm' => 1.0, - ], - ], - 'Distance' => [ - 'm' => [ - 'm' => 1.0, - 'mi' => 6.21371192237334E-04, - 'Nmi' => 5.39956803455724E-04, - 'in' => 3.93700787401575E+01, - 'ft' => 3.28083989501312E+00, - 'yd' => 1.09361329797891E+00, - 'ang' => 1.00000000000000E+10, - 'Pica' => 2.83464566929116E+03, - ], - 'mi' => [ - 'm' => 1.60934400000000E+03, - 'mi' => 1.0, - 'Nmi' => 8.68976241900648E-01, - 'in' => 6.33600000000000E+04, - 'ft' => 5.28000000000000E+03, - 'yd' => 1.76000000000000E+03, - 'ang' => 1.60934400000000E+13, - 'Pica' => 4.56191999999971E+06, - ], - 'Nmi' => [ - 'm' => 1.85200000000000E+03, - 'mi' => 1.15077944802354E+00, - 'Nmi' => 1.0, - 'in' => 7.29133858267717E+04, - 'ft' => 6.07611548556430E+03, - 'yd' => 2.02537182785694E+03, - 'ang' => 1.85200000000000E+13, - 'Pica' => 5.24976377952723E+06, - ], - 'in' => [ - 'm' => 2.54000000000000E-02, - 'mi' => 1.57828282828283E-05, - 'Nmi' => 1.37149028077754E-05, - 'in' => 1.0, - 'ft' => 8.33333333333333E-02, - 'yd' => 2.77777777686643E-02, - 'ang' => 2.54000000000000E+08, - 'Pica' => 7.19999999999955E+01, - ], - 'ft' => [ - 'm' => 3.04800000000000E-01, - 'mi' => 1.89393939393939E-04, - 'Nmi' => 1.64578833693305E-04, - 'in' => 1.20000000000000E+01, - 'ft' => 1.0, - 'yd' => 3.33333333223972E-01, - 'ang' => 3.04800000000000E+09, - 'Pica' => 8.63999999999946E+02, - ], - 'yd' => [ - 'm' => 9.14400000300000E-01, - 'mi' => 5.68181818368230E-04, - 'Nmi' => 4.93736501241901E-04, - 'in' => 3.60000000118110E+01, - 'ft' => 3.00000000000000E+00, - 'yd' => 1.0, - 'ang' => 9.14400000300000E+09, - 'Pica' => 2.59200000085023E+03, - ], - 'ang' => [ - 'm' => 1.00000000000000E-10, - 'mi' => 6.21371192237334E-14, - 'Nmi' => 5.39956803455724E-14, - 'in' => 3.93700787401575E-09, - 'ft' => 3.28083989501312E-10, - 'yd' => 1.09361329797891E-10, - 'ang' => 1.0, - 'Pica' => 2.83464566929116E-07, - ], - 'Pica' => [ - 'm' => 3.52777777777800E-04, - 'mi' => 2.19205948372629E-07, - 'Nmi' => 1.90484761219114E-07, - 'in' => 1.38888888888898E-02, - 'ft' => 1.15740740740748E-03, - 'yd' => 3.85802469009251E-04, - 'ang' => 3.52777777777800E+06, - 'Pica' => 1.0, - ], - ], - 'Time' => [ - 'yr' => [ - 'yr' => 1.0, - 'day' => 365.25, - 'hr' => 8766.0, - 'mn' => 525960.0, - 'sec' => 31557600.0, - ], - 'day' => [ - 'yr' => 2.73785078713210E-03, - 'day' => 1.0, - 'hr' => 24.0, - 'mn' => 1440.0, - 'sec' => 86400.0, - ], - 'hr' => [ - 'yr' => 1.14077116130504E-04, - 'day' => 4.16666666666667E-02, - 'hr' => 1.0, - 'mn' => 60.0, - 'sec' => 3600.0, - ], - 'mn' => [ - 'yr' => 1.90128526884174E-06, - 'day' => 6.94444444444444E-04, - 'hr' => 1.66666666666667E-02, - 'mn' => 1.0, - 'sec' => 60.0, - ], - 'sec' => [ - 'yr' => 3.16880878140289E-08, - 'day' => 1.15740740740741E-05, - 'hr' => 2.77777777777778E-04, - 'mn' => 1.66666666666667E-02, - 'sec' => 1.0, - ], - ], - 'Pressure' => [ - 'Pa' => [ - 'Pa' => 1.0, - 'p' => 1.0, - 'atm' => 9.86923299998193E-06, - 'at' => 9.86923299998193E-06, - 'mmHg' => 7.50061707998627E-03, - ], - 'p' => [ - 'Pa' => 1.0, - 'p' => 1.0, - 'atm' => 9.86923299998193E-06, - 'at' => 9.86923299998193E-06, - 'mmHg' => 7.50061707998627E-03, - ], - 'atm' => [ - 'Pa' => 1.01324996583000E+05, - 'p' => 1.01324996583000E+05, - 'atm' => 1.0, - 'at' => 1.0, - 'mmHg' => 760.0, - ], - 'at' => [ - 'Pa' => 1.01324996583000E+05, - 'p' => 1.01324996583000E+05, - 'atm' => 1.0, - 'at' => 1.0, - 'mmHg' => 760.0, - ], - 'mmHg' => [ - 'Pa' => 1.33322363925000E+02, - 'p' => 1.33322363925000E+02, - 'atm' => 1.31578947368421E-03, - 'at' => 1.31578947368421E-03, - 'mmHg' => 1.0, - ], - ], - 'Force' => [ - 'N' => [ - 'N' => 1.0, - 'dyn' => 1.0E+5, - 'dy' => 1.0E+5, - 'lbf' => 2.24808923655339E-01, - ], - 'dyn' => [ - 'N' => 1.0E-5, - 'dyn' => 1.0, - 'dy' => 1.0, - 'lbf' => 2.24808923655339E-06, - ], - 'dy' => [ - 'N' => 1.0E-5, - 'dyn' => 1.0, - 'dy' => 1.0, - 'lbf' => 2.24808923655339E-06, - ], - 'lbf' => [ - 'N' => 4.448222, - 'dyn' => 4.448222E+5, - 'dy' => 4.448222E+5, - 'lbf' => 1.0, - ], - ], - 'Energy' => [ - 'J' => [ - 'J' => 1.0, - 'e' => 9.99999519343231E+06, - 'c' => 2.39006249473467E-01, - 'cal' => 2.38846190642017E-01, - 'eV' => 6.24145700000000E+18, - 'ev' => 6.24145700000000E+18, - 'HPh' => 3.72506430801000E-07, - 'hh' => 3.72506430801000E-07, - 'Wh' => 2.77777916238711E-04, - 'wh' => 2.77777916238711E-04, - 'flb' => 2.37304222192651E+01, - 'BTU' => 9.47815067349015E-04, - 'btu' => 9.47815067349015E-04, - ], - 'e' => [ - 'J' => 1.00000048065700E-07, - 'e' => 1.0, - 'c' => 2.39006364353494E-08, - 'cal' => 2.38846305445111E-08, - 'eV' => 6.24146000000000E+11, - 'ev' => 6.24146000000000E+11, - 'HPh' => 3.72506609848824E-14, - 'hh' => 3.72506609848824E-14, - 'Wh' => 2.77778049754611E-11, - 'wh' => 2.77778049754611E-11, - 'flb' => 2.37304336254586E-06, - 'BTU' => 9.47815522922962E-11, - 'btu' => 9.47815522922962E-11, - ], - 'c' => [ - 'J' => 4.18399101363672E+00, - 'e' => 4.18398900257312E+07, - 'c' => 1.0, - 'cal' => 9.99330315287563E-01, - 'eV' => 2.61142000000000E+19, - 'ev' => 2.61142000000000E+19, - 'HPh' => 1.55856355899327E-06, - 'hh' => 1.55856355899327E-06, - 'Wh' => 1.16222030532950E-03, - 'wh' => 1.16222030532950E-03, - 'flb' => 9.92878733152102E+01, - 'BTU' => 3.96564972437776E-03, - 'btu' => 3.96564972437776E-03, - ], - 'cal' => [ - 'J' => 4.18679484613929E+00, - 'e' => 4.18679283372801E+07, - 'c' => 1.00067013349059E+00, - 'cal' => 1.0, - 'eV' => 2.61317000000000E+19, - 'ev' => 2.61317000000000E+19, - 'HPh' => 1.55960800463137E-06, - 'hh' => 1.55960800463137E-06, - 'Wh' => 1.16299914807955E-03, - 'wh' => 1.16299914807955E-03, - 'flb' => 9.93544094443283E+01, - 'BTU' => 3.96830723907002E-03, - 'btu' => 3.96830723907002E-03, - ], - 'eV' => [ - 'J' => 1.60219000146921E-19, - 'e' => 1.60218923136574E-12, - 'c' => 3.82933423195043E-20, - 'cal' => 3.82676978535648E-20, - 'eV' => 1.0, - 'ev' => 1.0, - 'HPh' => 5.96826078912344E-26, - 'hh' => 5.96826078912344E-26, - 'Wh' => 4.45053000026614E-23, - 'wh' => 4.45053000026614E-23, - 'flb' => 3.80206452103492E-18, - 'BTU' => 1.51857982414846E-22, - 'btu' => 1.51857982414846E-22, - ], - 'ev' => [ - 'J' => 1.60219000146921E-19, - 'e' => 1.60218923136574E-12, - 'c' => 3.82933423195043E-20, - 'cal' => 3.82676978535648E-20, - 'eV' => 1.0, - 'ev' => 1.0, - 'HPh' => 5.96826078912344E-26, - 'hh' => 5.96826078912344E-26, - 'Wh' => 4.45053000026614E-23, - 'wh' => 4.45053000026614E-23, - 'flb' => 3.80206452103492E-18, - 'BTU' => 1.51857982414846E-22, - 'btu' => 1.51857982414846E-22, - ], - 'HPh' => [ - 'J' => 2.68451741316170E+06, - 'e' => 2.68451612283024E+13, - 'c' => 6.41616438565991E+05, - 'cal' => 6.41186757845835E+05, - 'eV' => 1.67553000000000E+25, - 'ev' => 1.67553000000000E+25, - 'HPh' => 1.0, - 'hh' => 1.0, - 'Wh' => 7.45699653134593E+02, - 'wh' => 7.45699653134593E+02, - 'flb' => 6.37047316692964E+07, - 'BTU' => 2.54442605275546E+03, - 'btu' => 2.54442605275546E+03, - ], - 'hh' => [ - 'J' => 2.68451741316170E+06, - 'e' => 2.68451612283024E+13, - 'c' => 6.41616438565991E+05, - 'cal' => 6.41186757845835E+05, - 'eV' => 1.67553000000000E+25, - 'ev' => 1.67553000000000E+25, - 'HPh' => 1.0, - 'hh' => 1.0, - 'Wh' => 7.45699653134593E+02, - 'wh' => 7.45699653134593E+02, - 'flb' => 6.37047316692964E+07, - 'BTU' => 2.54442605275546E+03, - 'btu' => 2.54442605275546E+03, - ], - 'Wh' => [ - 'J' => 3.59999820554720E+03, - 'e' => 3.59999647518369E+10, - 'c' => 8.60422069219046E+02, - 'cal' => 8.59845857713046E+02, - 'eV' => 2.24692340000000E+22, - 'ev' => 2.24692340000000E+22, - 'HPh' => 1.34102248243839E-03, - 'hh' => 1.34102248243839E-03, - 'Wh' => 1.0, - 'wh' => 1.0, - 'flb' => 8.54294774062316E+04, - 'BTU' => 3.41213254164705E+00, - 'btu' => 3.41213254164705E+00, - ], - 'wh' => [ - 'J' => 3.59999820554720E+03, - 'e' => 3.59999647518369E+10, - 'c' => 8.60422069219046E+02, - 'cal' => 8.59845857713046E+02, - 'eV' => 2.24692340000000E+22, - 'ev' => 2.24692340000000E+22, - 'HPh' => 1.34102248243839E-03, - 'hh' => 1.34102248243839E-03, - 'Wh' => 1.0, - 'wh' => 1.0, - 'flb' => 8.54294774062316E+04, - 'BTU' => 3.41213254164705E+00, - 'btu' => 3.41213254164705E+00, - ], - 'flb' => [ - 'J' => 4.21400003236424E-02, - 'e' => 4.21399800687660E+05, - 'c' => 1.00717234301644E-02, - 'cal' => 1.00649785509554E-02, - 'eV' => 2.63015000000000E+17, - 'ev' => 2.63015000000000E+17, - 'HPh' => 1.56974211145130E-08, - 'hh' => 1.56974211145130E-08, - 'Wh' => 1.17055614802000E-05, - 'wh' => 1.17055614802000E-05, - 'flb' => 1.0, - 'BTU' => 3.99409272448406E-05, - 'btu' => 3.99409272448406E-05, - ], - 'BTU' => [ - 'J' => 1.05505813786749E+03, - 'e' => 1.05505763074665E+10, - 'c' => 2.52165488508168E+02, - 'cal' => 2.51996617135510E+02, - 'eV' => 6.58510000000000E+21, - 'ev' => 6.58510000000000E+21, - 'HPh' => 3.93015941224568E-04, - 'hh' => 3.93015941224568E-04, - 'Wh' => 2.93071851047526E-01, - 'wh' => 2.93071851047526E-01, - 'flb' => 2.50369750774671E+04, - 'BTU' => 1.0, - 'btu' => 1.0, - ], - 'btu' => [ - 'J' => 1.05505813786749E+03, - 'e' => 1.05505763074665E+10, - 'c' => 2.52165488508168E+02, - 'cal' => 2.51996617135510E+02, - 'eV' => 6.58510000000000E+21, - 'ev' => 6.58510000000000E+21, - 'HPh' => 3.93015941224568E-04, - 'hh' => 3.93015941224568E-04, - 'Wh' => 2.93071851047526E-01, - 'wh' => 2.93071851047526E-01, - 'flb' => 2.50369750774671E+04, - 'BTU' => 1.0, - 'btu' => 1.0, - ], - ], - 'Power' => [ - 'HP' => [ - 'HP' => 1.0, - 'h' => 1.0, - 'W' => 7.45701000000000E+02, - 'w' => 7.45701000000000E+02, - ], - 'h' => [ - 'HP' => 1.0, - 'h' => 1.0, - 'W' => 7.45701000000000E+02, - 'w' => 7.45701000000000E+02, - ], - 'W' => [ - 'HP' => 1.34102006031908E-03, - 'h' => 1.34102006031908E-03, - 'W' => 1.0, - 'w' => 1.0, - ], - 'w' => [ - 'HP' => 1.34102006031908E-03, - 'h' => 1.34102006031908E-03, - 'W' => 1.0, - 'w' => 1.0, - ], - ], - 'Magnetism' => [ - 'T' => [ - 'T' => 1.0, - 'ga' => 10000.0, - ], - 'ga' => [ - 'T' => 0.0001, - 'ga' => 1.0, - ], - ], - 'Liquid' => [ - 'tsp' => [ - 'tsp' => 1.0, - 'tbs' => 3.33333333333333E-01, - 'oz' => 1.66666666666667E-01, - 'cup' => 2.08333333333333E-02, - 'pt' => 1.04166666666667E-02, - 'us_pt' => 1.04166666666667E-02, - 'uk_pt' => 8.67558516821960E-03, - 'qt' => 5.20833333333333E-03, - 'gal' => 1.30208333333333E-03, - 'l' => 4.92999408400710E-03, - 'lt' => 4.92999408400710E-03, - ], - 'tbs' => [ - 'tsp' => 3.00000000000000E+00, - 'tbs' => 1.0, - 'oz' => 5.00000000000000E-01, - 'cup' => 6.25000000000000E-02, - 'pt' => 3.12500000000000E-02, - 'us_pt' => 3.12500000000000E-02, - 'uk_pt' => 2.60267555046588E-02, - 'qt' => 1.56250000000000E-02, - 'gal' => 3.90625000000000E-03, - 'l' => 1.47899822520213E-02, - 'lt' => 1.47899822520213E-02, - ], - 'oz' => [ - 'tsp' => 6.00000000000000E+00, - 'tbs' => 2.00000000000000E+00, - 'oz' => 1.0, - 'cup' => 1.25000000000000E-01, - 'pt' => 6.25000000000000E-02, - 'us_pt' => 6.25000000000000E-02, - 'uk_pt' => 5.20535110093176E-02, - 'qt' => 3.12500000000000E-02, - 'gal' => 7.81250000000000E-03, - 'l' => 2.95799645040426E-02, - 'lt' => 2.95799645040426E-02, - ], - 'cup' => [ - 'tsp' => 4.80000000000000E+01, - 'tbs' => 1.60000000000000E+01, - 'oz' => 8.00000000000000E+00, - 'cup' => 1.0, - 'pt' => 5.00000000000000E-01, - 'us_pt' => 5.00000000000000E-01, - 'uk_pt' => 4.16428088074541E-01, - 'qt' => 2.50000000000000E-01, - 'gal' => 6.25000000000000E-02, - 'l' => 2.36639716032341E-01, - 'lt' => 2.36639716032341E-01, - ], - 'pt' => [ - 'tsp' => 9.60000000000000E+01, - 'tbs' => 3.20000000000000E+01, - 'oz' => 1.60000000000000E+01, - 'cup' => 2.00000000000000E+00, - 'pt' => 1.0, - 'us_pt' => 1.0, - 'uk_pt' => 8.32856176149081E-01, - 'qt' => 5.00000000000000E-01, - 'gal' => 1.25000000000000E-01, - 'l' => 4.73279432064682E-01, - 'lt' => 4.73279432064682E-01, - ], - 'us_pt' => [ - 'tsp' => 9.60000000000000E+01, - 'tbs' => 3.20000000000000E+01, - 'oz' => 1.60000000000000E+01, - 'cup' => 2.00000000000000E+00, - 'pt' => 1.0, - 'us_pt' => 1.0, - 'uk_pt' => 8.32856176149081E-01, - 'qt' => 5.00000000000000E-01, - 'gal' => 1.25000000000000E-01, - 'l' => 4.73279432064682E-01, - 'lt' => 4.73279432064682E-01, - ], - 'uk_pt' => [ - 'tsp' => 1.15266000000000E+02, - 'tbs' => 3.84220000000000E+01, - 'oz' => 1.92110000000000E+01, - 'cup' => 2.40137500000000E+00, - 'pt' => 1.20068750000000E+00, - 'us_pt' => 1.20068750000000E+00, - 'uk_pt' => 1.0, - 'qt' => 6.00343750000000E-01, - 'gal' => 1.50085937500000E-01, - 'l' => 5.68260698087162E-01, - 'lt' => 5.68260698087162E-01, - ], - 'qt' => [ - 'tsp' => 1.92000000000000E+02, - 'tbs' => 6.40000000000000E+01, - 'oz' => 3.20000000000000E+01, - 'cup' => 4.00000000000000E+00, - 'pt' => 2.00000000000000E+00, - 'us_pt' => 2.00000000000000E+00, - 'uk_pt' => 1.66571235229816E+00, - 'qt' => 1.0, - 'gal' => 2.50000000000000E-01, - 'l' => 9.46558864129363E-01, - 'lt' => 9.46558864129363E-01, - ], - 'gal' => [ - 'tsp' => 7.68000000000000E+02, - 'tbs' => 2.56000000000000E+02, - 'oz' => 1.28000000000000E+02, - 'cup' => 1.60000000000000E+01, - 'pt' => 8.00000000000000E+00, - 'us_pt' => 8.00000000000000E+00, - 'uk_pt' => 6.66284940919265E+00, - 'qt' => 4.00000000000000E+00, - 'gal' => 1.0, - 'l' => 3.78623545651745E+00, - 'lt' => 3.78623545651745E+00, - ], - 'l' => [ - 'tsp' => 2.02840000000000E+02, - 'tbs' => 6.76133333333333E+01, - 'oz' => 3.38066666666667E+01, - 'cup' => 4.22583333333333E+00, - 'pt' => 2.11291666666667E+00, - 'us_pt' => 2.11291666666667E+00, - 'uk_pt' => 1.75975569552166E+00, - 'qt' => 1.05645833333333E+00, - 'gal' => 2.64114583333333E-01, - 'l' => 1.0, - 'lt' => 1.0, - ], - 'lt' => [ - 'tsp' => 2.02840000000000E+02, - 'tbs' => 6.76133333333333E+01, - 'oz' => 3.38066666666667E+01, - 'cup' => 4.22583333333333E+00, - 'pt' => 2.11291666666667E+00, - 'us_pt' => 2.11291666666667E+00, - 'uk_pt' => 1.75975569552166E+00, - 'qt' => 1.05645833333333E+00, - 'gal' => 2.64114583333333E-01, - 'l' => 1.0, - 'lt' => 1.0, - ], - ], - ]; + public const EULER = 2.71828182845904523536; /** * parseComplex. * * Parses a complex number into its real and imaginary parts, and an I or J suffix * - * @deprecated 2.0.0 No longer used by internal code. Please use the Complex\Complex class instead + * @deprecated 1.12.0 No longer used by internal code. Please use the \Complex\Complex class instead * * @param string $complexNumber The complex number * @@ -738,35 +41,6 @@ public static function parseComplex($complexNumber) ]; } - /** - * Formats a number base string value with leading zeroes. - * - * @param string $xVal The "number" to pad - * @param int $places The length that we want to pad this value - * - * @return string The padded "number" - */ - private static function nbrConversionFormat($xVal, $places) - { - if ($places !== null) { - if (is_numeric($places)) { - $places = (int) $places; - } else { - return Functions::VALUE(); - } - if ($places < 0) { - return Functions::NAN(); - } - if (strlen($xVal) <= $places) { - return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10); - } - - return Functions::NAN(); - } - - return substr($xVal, -10); - } - /** * BESSELI. * @@ -776,7 +50,9 @@ private static function nbrConversionFormat($xVal, $places) * Excel Function: * BESSELI(x,ord) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BESSELI() method in the Engineering\BesselI class instead * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELI returns the #VALUE! error value. @@ -785,42 +61,11 @@ private static function nbrConversionFormat($xVal, $places) * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. * If $ord < 0, BESSELI returns the #NUM! error value. * - * @return float|string Result, or a string containing an error + * @return array|float|string Result, or a string containing an error */ public static function BESSELI($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - $ord = floor($ord); - if ($ord < 0) { - return Functions::NAN(); - } - - if (abs($x) <= 30) { - $fResult = $fTerm = pow($x / 2, $ord) / MathTrig::FACT($ord); - $ordK = 1; - $fSqrX = ($x * $x) / 4; - do { - $fTerm *= $fSqrX; - $fTerm /= ($ordK * ($ordK + $ord)); - $fResult += $fTerm; - } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); - } else { - $f_2_PI = 2 * M_PI; - - $fXAbs = abs($x); - $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs); - if (($ord & 1) && ($x < 0)) { - $fResult = -$fResult; - } - } - - return (is_nan($fResult)) ? Functions::NAN() : $fResult; - } - - return Functions::VALUE(); + return Engineering\BesselI::BESSELI($x, $ord); } /** @@ -831,7 +76,9 @@ public static function BESSELI($x, $ord) * Excel Function: * BESSELJ(x,ord) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BESSELJ() method in the Engineering\BesselJ class instead * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELJ returns the #VALUE! error value. @@ -839,80 +86,11 @@ public static function BESSELI($x, $ord) * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. * If $ord < 0, BESSELJ returns the #NUM! error value. * - * @return float|string Result, or a string containing an error + * @return array|float|string Result, or a string containing an error */ public static function BESSELJ($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - $ord = floor($ord); - if ($ord < 0) { - return Functions::NAN(); - } - - $fResult = 0; - if (abs($x) <= 30) { - $fResult = $fTerm = pow($x / 2, $ord) / MathTrig::FACT($ord); - $ordK = 1; - $fSqrX = ($x * $x) / -4; - do { - $fTerm *= $fSqrX; - $fTerm /= ($ordK * ($ordK + $ord)); - $fResult += $fTerm; - } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); - } else { - $f_PI_DIV_2 = M_PI / 2; - $f_PI_DIV_4 = M_PI / 4; - - $fXAbs = abs($x); - $fResult = sqrt(Functions::M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4); - if (($ord & 1) && ($x < 0)) { - $fResult = -$fResult; - } - } - - return (is_nan($fResult)) ? Functions::NAN() : $fResult; - } - - return Functions::VALUE(); - } - - private static function besselK0($fNum) - { - if ($fNum <= 2) { - $fNum2 = $fNum * 0.5; - $y = ($fNum2 * $fNum2); - $fRet = -log($fNum2) * self::BESSELI($fNum, 0) + - (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * - (0.10750e-3 + $y * 0.74e-5)))))); - } else { - $y = 2 / $fNum; - $fRet = exp(-$fNum) / sqrt($fNum) * - (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * - (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); - } - - return $fRet; - } - - private static function besselK1($fNum) - { - if ($fNum <= 2) { - $fNum2 = $fNum * 0.5; - $y = ($fNum2 * $fNum2); - $fRet = log($fNum2) * self::BESSELI($fNum, 1) + - (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * - (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum; - } else { - $y = 2 / $fNum; - $fRet = exp(-$fNum) / sqrt($fNum) * - (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * - (0.325614e-2 + $y * (-0.68245e-3))))))); - } - - return $fRet; + return Engineering\BesselJ::BESSELJ($x, $ord); } /** @@ -924,7 +102,9 @@ private static function besselK1($fNum) * Excel Function: * BESSELK(x,ord) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BESSELK() method in the Engineering\BesselK class instead * * @param float $x The value at which to evaluate the function. * If x is nonnumeric, BESSELK returns the #VALUE! error value. @@ -932,77 +112,11 @@ private static function besselK1($fNum) * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. * If $ord < 0, BESSELK returns the #NUM! error value. * - * @return float|string Result, or a string containing an error + * @return array|float|string Result, or a string containing an error */ public static function BESSELK($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - if (($ord < 0) || ($x == 0.0)) { - return Functions::NAN(); - } - - switch (floor($ord)) { - case 0: - $fBk = self::besselK0($x); - - break; - case 1: - $fBk = self::besselK1($x); - - break; - default: - $fTox = 2 / $x; - $fBkm = self::besselK0($x); - $fBk = self::besselK1($x); - for ($n = 1; $n < $ord; ++$n) { - $fBkp = $fBkm + $n * $fTox * $fBk; - $fBkm = $fBk; - $fBk = $fBkp; - } - } - - return (is_nan($fBk)) ? Functions::NAN() : $fBk; - } - - return Functions::VALUE(); - } - - private static function besselY0($fNum) - { - if ($fNum < 8.0) { - $y = ($fNum * $fNum); - $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); - $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); - $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum); - } else { - $z = 8.0 / $fNum; - $y = ($z * $z); - $xx = $fNum - 0.785398164; - $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); - $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); - $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2); - } - - return $fRet; - } - - private static function besselY1($fNum) - { - if ($fNum < 8.0) { - $y = ($fNum * $fNum); - $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * - (-0.4237922726e7 + $y * 0.8511937935e4))))); - $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * - (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); - $fRet = $f1 / $f2 + 0.636619772 * (self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum); - } else { - $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491); - } - - return $fRet; + return Engineering\BesselK::BESSELK($x, $ord); } /** @@ -1013,50 +127,21 @@ private static function besselY1($fNum) * Excel Function: * BESSELY(x,ord) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BESSELY() method in the Engineering\BesselY class instead * * @param float $x The value at which to evaluate the function. - * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * If x is nonnumeric, BESSELY returns the #VALUE! error value. * @param int $ord The order of the Bessel function. If n is not an integer, it is truncated. - * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. - * If $ord < 0, BESSELK returns the #NUM! error value. + * If $ord is nonnumeric, BESSELY returns the #VALUE! error value. + * If $ord < 0, BESSELY returns the #NUM! error value. * - * @return float|string Result, or a string containing an error + * @return array|float|string Result, or a string containing an error */ public static function BESSELY($x, $ord) { - $x = ($x === null) ? 0.0 : Functions::flattenSingleValue($x); - $ord = ($ord === null) ? 0.0 : Functions::flattenSingleValue($ord); - - if ((is_numeric($x)) && (is_numeric($ord))) { - if (($ord < 0) || ($x == 0.0)) { - return Functions::NAN(); - } - - switch (floor($ord)) { - case 0: - $fBy = self::besselY0($x); - - break; - case 1: - $fBy = self::besselY1($x); - - break; - default: - $fTox = 2 / $x; - $fBym = self::besselY0($x); - $fBy = self::besselY1($x); - for ($n = 1; $n < $ord; ++$n) { - $fByp = $n * $fTox * $fBy - $fBym; - $fBym = $fBy; - $fBy = $fByp; - } - } - - return (is_nan($fBy)) ? Functions::NAN() : $fBy; - } - - return Functions::VALUE(); + return Engineering\BesselY::BESSELY($x, $ord); } /** @@ -1067,45 +152,22 @@ public static function BESSELY($x, $ord) * Excel Function: * BIN2DEC(x) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The binary number (as a string) that you want to convert. The number + * @see Use the toDecimal() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. * - * @return string + * @return array|string */ public static function BINTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - $x = substr($x, -9); - - return '-' . (512 - bindec($x)); - } - - return bindec($x); + return Engineering\ConvertBinary::toDecimal($x); } /** @@ -1116,52 +178,28 @@ public static function BINTODEC($x) * Excel Function: * BIN2HEX(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The binary number (as a string) that you want to convert. The number + * @see Use the toHex() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, BIN2HEX uses the + * @param mixed $places The number of characters to use. If places is omitted, BIN2HEX uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. * If places is negative, BIN2HEX returns the #NUM! error value. * - * @return string + * @return array|string */ public static function BINTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - // Argument X - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - return str_repeat('F', 8) . substr(strtoupper(dechex(bindec(substr($x, -9)))), -2); - } - $hexVal = (string) strtoupper(dechex(bindec($x))); - - return self::nbrConversionFormat($hexVal, $places); + return Engineering\ConvertBinary::toHex($x, $places); } /** @@ -1172,51 +210,28 @@ public static function BINTOHEX($x, $places = null) * Excel Function: * BIN2OCT(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The binary number (as a string) that you want to convert. The number + * @see Use the toOctal() method in the Engineering\ConvertBinary class instead + * + * @param mixed $x The binary number (as a string) that you want to convert. The number * cannot contain more than 10 characters (10 bits). The most significant * bit of number is the sign bit. The remaining 9 bits are magnitude bits. * Negative numbers are represented using two's-complement notation. * If number is not a valid binary number, or if number contains more than * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, BIN2OCT uses the + * @param mixed $places The number of characters to use. If places is omitted, BIN2OCT uses the * minimum number of characters necessary. Places is useful for padding the * return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. * If places is negative, BIN2OCT returns the #NUM! error value. * - * @return string + * @return array|string */ public static function BINTOOCT($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $x = floor($x); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { - return Functions::NAN(); - } - if (strlen($x) > 10) { - return Functions::NAN(); - } elseif (strlen($x) == 10) { - // Two's Complement - return str_repeat('7', 7) . substr(strtoupper(decoct(bindec(substr($x, -9)))), -3); - } - $octVal = (string) decoct(bindec($x)); - - return self::nbrConversionFormat($octVal, $places); + return Engineering\ConvertBinary::toOctal($x, $places); } /** @@ -1227,9 +242,11 @@ public static function BINTOOCT($x, $places = null) * Excel Function: * DEC2BIN(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the toBinary() method in the Engineering\ConvertDecimal class instead * - * @param string $x The decimal integer you want to convert. If number is negative, + * @param mixed $x The decimal integer you want to convert. If number is negative, * valid place values are ignored and DEC2BIN returns a 10-character * (10-bit) binary number in which the most significant bit is the sign * bit. The remaining 9 bits are magnitude bits. Negative numbers are @@ -1239,45 +256,18 @@ public static function BINTOOCT($x, $places = null) * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. * If DEC2BIN requires more than places characters, it returns the #NUM! * error value. - * @param int $places The number of characters to use. If places is omitted, DEC2BIN uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2BIN uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. * If places is zero or negative, DEC2BIN returns the #NUM! error value. * - * @return string + * @return array|string */ public static function DECTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - - $x = (string) floor($x); - if ($x < -512 || $x > 511) { - return Functions::NAN(); - } - - $r = decbin($x); - // Two's Complement - $r = substr($r, -10); - if (strlen($r) >= 11) { - return Functions::NAN(); - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toBinary($x, $places); } /** @@ -1288,9 +278,11 @@ public static function DECTOBIN($x, $places = null) * Excel Function: * DEC2HEX(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The decimal integer you want to convert. If number is negative, + * @see Use the toHex() method in the Engineering\ConvertDecimal class instead + * + * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2HEX returns a 10-character (40-bit) * hexadecimal number in which the most significant bit is the sign * bit. The remaining 39 bits are magnitude bits. Negative numbers @@ -1300,39 +292,18 @@ public static function DECTOBIN($x, $places = null) * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. * If DEC2HEX requires more than places characters, it returns the * #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, DEC2HEX uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2HEX uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. * If places is zero or negative, DEC2HEX returns the #NUM! error value. * - * @return string + * @return array|string */ public static function DECTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - $x = (string) floor($x); - $r = strtoupper(dechex($x)); - if (strlen($r) == 8) { - // Two's Complement - $r = 'FF' . $r; - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toHex($x, $places); } /** @@ -1343,9 +314,11 @@ public static function DECTOHEX($x, $places = null) * Excel Function: * DEC2OCT(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the toOctal() method in the Engineering\ConvertDecimal class instead * - * @param string $x The decimal integer you want to convert. If number is negative, + * @param mixed $x The decimal integer you want to convert. If number is negative, * places is ignored and DEC2OCT returns a 10-character (30-bit) * octal number in which the most significant bit is the sign bit. * The remaining 29 bits are magnitude bits. Negative numbers are @@ -1355,40 +328,18 @@ public static function DECTOHEX($x, $places = null) * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. * If DEC2OCT requires more than places characters, it returns the * #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, DEC2OCT uses + * @param mixed $places The number of characters to use. If places is omitted, DEC2OCT uses * the minimum number of characters necessary. Places is useful for * padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. * If places is zero or negative, DEC2OCT returns the #NUM! error value. * - * @return string + * @return array|string */ public static function DECTOOCT($x, $places = null) { - $xorig = $x; - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - $x = (int) $x; - } else { - return Functions::VALUE(); - } - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { - return Functions::VALUE(); - } - $x = (string) floor($x); - $r = decoct($x); - if (strlen($r) == 11) { - // Two's Complement - $r = substr($r, -10); - } - - return self::nbrConversionFormat($r, $places); + return Engineering\ConvertDecimal::toOctal($x, $places); } /** @@ -1399,9 +350,11 @@ public static function DECTOOCT($x, $places = null) * Excel Function: * HEX2BIN(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the toBinary() method in the Engineering\ConvertHex class instead * - * @param string $x the hexadecimal number you want to convert. + * @param mixed $x the hexadecimal number (as a string) that you want to convert. * Number cannot contain more than 10 characters. * The most significant bit of number is the sign bit (40th bit from the right). * The remaining 9 bits are magnitude bits. @@ -1411,29 +364,18 @@ public static function DECTOOCT($x, $places = null) * and if number is positive, it cannot be greater than 1FF. * If number is not a valid hexadecimal number, HEX2BIN returns the #NUM! error value. * If HEX2BIN requires more than places characters, it returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, + * @param mixed $places The number of characters to use. If places is omitted, * HEX2BIN uses the minimum number of characters necessary. Places * is useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. * If places is negative, HEX2BIN returns the #NUM! error value. * - * @return string + * @return array|string */ public static function HEXTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - return self::DECTOBIN(self::HEXTODEC($x), $places); + return Engineering\ConvertHex::toBinary($x, $places); } /** @@ -1444,9 +386,11 @@ public static function HEXTOBIN($x, $places = null) * Excel Function: * HEX2DEC(x) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the toDecimal() method in the Engineering\ConvertHex class instead * - * @param string $x The hexadecimal number you want to convert. This number cannot + * @param mixed $x The hexadecimal number (as a string) that you want to convert. This number cannot * contain more than 10 characters (40 bits). The most significant * bit of number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement @@ -1454,37 +398,11 @@ public static function HEXTOBIN($x, $places = null) * If number is not a valid hexadecimal number, HEX2DEC returns the * #NUM! error value. * - * @return string + * @return array|string */ public static function HEXTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - if (strlen($x) > 10) { - return Functions::NAN(); - } - - $binX = ''; - foreach (str_split($x) as $char) { - $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); - } - if (strlen($binX) == 40 && $binX[0] == '1') { - for ($i = 0; $i < 40; ++$i) { - $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); - } - - return (bindec($binX) + 1) * -1; - } - - return bindec($binX); + return Engineering\ConvertHex::toDecimal($x); } /** @@ -1495,9 +413,11 @@ public static function HEXTODEC($x) * Excel Function: * HEX2OCT(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The hexadecimal number you want to convert. Number cannot + * @see Use the toOctal() method in the Engineering\ConvertHex class instead + * + * @param mixed $x The hexadecimal number (as a string) that you want to convert. Number cannot * contain more than 10 characters. The most significant bit of * number is the sign bit. The remaining 39 bits are magnitude * bits. Negative numbers are represented using two's-complement @@ -1510,7 +430,7 @@ public static function HEXTODEC($x) * the #NUM! error value. * If HEX2OCT requires more than places characters, it returns * the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, HEX2OCT + * @param mixed $places The number of characters to use. If places is omitted, HEX2OCT * uses the minimum number of characters necessary. Places is * useful for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. @@ -1518,27 +438,11 @@ public static function HEXTODEC($x) * value. * If places is negative, HEX2OCT returns the #NUM! error value. * - * @return string + * @return array|string */ public static function HEXTOOCT($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { - return Functions::NAN(); - } - - $decimal = self::HEXTODEC($x); - if ($decimal < -536870912 || $decimal > 536870911) { - return Functions::NAN(); - } - - return self::DECTOOCT($decimal, $places); + return Engineering\ConvertHex::toOctal($x, $places); } /** @@ -1549,9 +453,11 @@ public static function HEXTOOCT($x, $places = null) * Excel Function: * OCT2BIN(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The octal number you want to convert. Number may not + * @see Use the toBinary() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not * contain more than 10 characters. The most significant * bit of number is the sign bit. The remaining 29 bits * are magnitude bits. Negative numbers are represented @@ -1564,7 +470,7 @@ public static function HEXTOOCT($x, $places = null) * the #NUM! error value. * If OCT2BIN requires more than places characters, it * returns the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, + * @param mixed $places The number of characters to use. If places is omitted, * OCT2BIN uses the minimum number of characters necessary. * Places is useful for padding the return value with * leading 0s (zeros). @@ -1574,22 +480,11 @@ public static function HEXTOOCT($x, $places = null) * If places is negative, OCT2BIN returns the #NUM! error * value. * - * @return string + * @return array|string */ public static function OCTTOBIN($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - - return self::DECTOBIN(self::OCTTODEC($x), $places); + return Engineering\ConvertOctal::toBinary($x, $places); } /** @@ -1600,9 +495,11 @@ public static function OCTTOBIN($x, $places = null) * Excel Function: * OCT2DEC(x) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The octal number you want to convert. Number may not contain + * @see Use the toDecimal() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using @@ -1610,32 +507,11 @@ public static function OCTTOBIN($x, $places = null) * If number is not a valid octal number, OCT2DEC returns the * #NUM! error value. * - * @return string + * @return array|string */ public static function OCTTODEC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - $binX = ''; - foreach (str_split($x) as $char) { - $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); - } - if (strlen($binX) == 30 && $binX[0] == '1') { - for ($i = 0; $i < 30; ++$i) { - $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); - } - - return (bindec($binX) + 1) * -1; - } - - return bindec($binX); + return Engineering\ConvertOctal::toDecimal($x); } /** @@ -1646,9 +522,11 @@ public static function OCTTODEC($x) * Excel Function: * OCT2HEX(x[,places]) * - * @category Engineering Functions + * @Deprecated 1.17.0 * - * @param string $x The octal number you want to convert. Number may not contain + * @see Use the toHex() method in the Engineering\ConvertOctal class instead + * + * @param mixed $x The octal number you want to convert. Number may not contain * more than 10 octal characters (30 bits). The most significant * bit of number is the sign bit. The remaining 29 bits are * magnitude bits. Negative numbers are represented using @@ -1659,30 +537,18 @@ public static function OCTTODEC($x) * #NUM! error value. * If OCT2HEX requires more than places characters, it returns * the #NUM! error value. - * @param int $places The number of characters to use. If places is omitted, OCT2HEX + * @param mixed $places The number of characters to use. If places is omitted, OCT2HEX * uses the minimum number of characters necessary. Places is useful * for padding the return value with leading 0s (zeros). * If places is not an integer, it is truncated. * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. * If places is negative, OCT2HEX returns the #NUM! error value. * - * @return string + * @return array|string */ public static function OCTTOHEX($x, $places = null) { - $x = Functions::flattenSingleValue($x); - $places = Functions::flattenSingleValue($places); - - if (is_bool($x)) { - return Functions::VALUE(); - } - $x = (string) $x; - if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { - return Functions::NAN(); - } - $hexVal = strtoupper(dechex(self::OCTTODEC($x))); - - return self::nbrConversionFormat($hexVal, $places); + return Engineering\ConvertOctal::toHex($x, $places); } /** @@ -1693,30 +559,20 @@ public static function OCTTOHEX($x, $places = null) * Excel Function: * COMPLEX(realNumber,imaginary[,suffix]) * - * @category Engineering Functions + * @Deprecated 1.18.0 + * + * @see Use the COMPLEX() method in the Engineering\Complex class instead * - * @param float $realNumber the real coefficient of the complex number - * @param float $imaginary the imaginary coefficient of the complex number - * @param string $suffix The suffix for the imaginary component of the complex number. + * @param array|float $realNumber the real coefficient of the complex number + * @param array|float $imaginary the imaginary coefficient of the complex number + * @param array|string $suffix The suffix for the imaginary component of the complex number. * If omitted, the suffix is assumed to be "i". * - * @return string + * @return array|string */ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i') { - $realNumber = ($realNumber === null) ? 0.0 : Functions::flattenSingleValue($realNumber); - $imaginary = ($imaginary === null) ? 0.0 : Functions::flattenSingleValue($imaginary); - $suffix = ($suffix === null) ? 'i' : Functions::flattenSingleValue($suffix); - - if (((is_numeric($realNumber)) && (is_numeric($imaginary))) && - (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) - ) { - $complex = new Complex($realNumber, $imaginary, $suffix); - - return (string) $complex; - } - - return Functions::VALUE(); + return Engineering\Complex::COMPLEX($realNumber, $imaginary, $suffix); } /** @@ -1727,18 +583,18 @@ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i * Excel Function: * IMAGINARY(complexNumber) * - * @category Engineering Functions + * @Deprecated 1.18.0 + * + * @see Use the IMAGINARY() method in the Engineering\Complex class instead * * @param string $complexNumber the complex number for which you want the imaginary * coefficient * - * @return float + * @return array|float|string */ public static function IMAGINARY($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->getImaginary(); + return Engineering\Complex::IMAGINARY($complexNumber); } /** @@ -1749,17 +605,17 @@ public static function IMAGINARY($complexNumber) * Excel Function: * IMREAL(complexNumber) * - * @category Engineering Functions + * @Deprecated 1.18.0 + * + * @see Use the IMREAL() method in the Engineering\Complex class instead * * @param string $complexNumber the complex number for which you want the real coefficient * - * @return float + * @return array|float|string */ public static function IMREAL($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->getReal(); + return Engineering\Complex::IMREAL($complexNumber); } /** @@ -1770,15 +626,17 @@ public static function IMREAL($complexNumber) * Excel Function: * IMABS(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMABS() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the absolute value * - * @return float + * @return array|float|string */ public static function IMABS($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (new Complex($complexNumber))->abs(); + return ComplexFunctions::IMABS($complexNumber); } /** @@ -1790,20 +648,17 @@ public static function IMABS($complexNumber) * Excel Function: * IMARGUMENT(complexNumber) * - * @param string $complexNumber the complex number for which you want the argument theta + * @Deprecated 1.18.0 * - * @return float|string + * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the argument theta + * + * @return array|float|string */ public static function IMARGUMENT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::DIV0(); - } - - return $complex->argument(); + return ComplexFunctions::IMARGUMENT($complexNumber); } /** @@ -1814,15 +669,17 @@ public static function IMARGUMENT($complexNumber) * Excel Function: * IMCONJUGATE(complexNumber) * - * @param string $complexNumber the complex number for which you want the conjugate + * @Deprecated 1.18.0 * - * @return string + * @see Use the IMARGUMENT() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the conjugate + * + * @return array|string */ public static function IMCONJUGATE($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->conjugate(); + return ComplexFunctions::IMCONJUGATE($complexNumber); } /** @@ -1833,15 +690,17 @@ public static function IMCONJUGATE($complexNumber) * Excel Function: * IMCOS(complexNumber) * - * @param string $complexNumber the complex number for which you want the cosine + * @Deprecated 1.18.0 * - * @return float|string + * @see Use the IMCOS() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the cosine + * + * @return array|float|string */ public static function IMCOS($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cos(); + return ComplexFunctions::IMCOS($complexNumber); } /** @@ -1852,15 +711,17 @@ public static function IMCOS($complexNumber) * Excel Function: * IMCOSH(complexNumber) * - * @param string $complexNumber the complex number for which you want the hyperbolic cosine + * @Deprecated 1.18.0 + * + * @see Use the IMCOSH() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine * - * @return float|string + * @return array|float|string */ public static function IMCOSH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cosh(); + return ComplexFunctions::IMCOSH($complexNumber); } /** @@ -1871,15 +732,17 @@ public static function IMCOSH($complexNumber) * Excel Function: * IMCOT(complexNumber) * - * @param string $complexNumber the complex number for which you want the cotangent + * @Deprecated 1.18.0 + * + * @see Use the IMCOT() method in the Engineering\ComplexFunctions class instead * - * @return float|string + * @param array|string $complexNumber the complex number for which you want the cotangent + * + * @return array|float|string */ public static function IMCOT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->cot(); + return ComplexFunctions::IMCOT($complexNumber); } /** @@ -1890,15 +753,17 @@ public static function IMCOT($complexNumber) * Excel Function: * IMCSC(complexNumber) * - * @param string $complexNumber the complex number for which you want the cosecant + * @Deprecated 1.18.0 * - * @return float|string + * @see Use the IMCSC() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the cosecant + * + * @return array|float|string */ public static function IMCSC($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->csc(); + return ComplexFunctions::IMCSC($complexNumber); } /** @@ -1909,15 +774,17 @@ public static function IMCSC($complexNumber) * Excel Function: * IMCSCH(complexNumber) * - * @param string $complexNumber the complex number for which you want the hyperbolic cosecant + * @Deprecated 1.18.0 + * + * @see Use the IMCSCH() method in the Engineering\ComplexFunctions class instead + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant * - * @return float|string + * @return array|float|string */ public static function IMCSCH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->csch(); + return ComplexFunctions::IMCSCH($complexNumber); } /** @@ -1928,15 +795,17 @@ public static function IMCSCH($complexNumber) * Excel Function: * IMSIN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSIN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the sine * - * @return float|string + * @return array|float|string */ public static function IMSIN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sin(); + return ComplexFunctions::IMSIN($complexNumber); } /** @@ -1947,15 +816,17 @@ public static function IMSIN($complexNumber) * Excel Function: * IMSINH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSINH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic sine * - * @return float|string + * @return array|float|string */ public static function IMSINH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sinh(); + return ComplexFunctions::IMSINH($complexNumber); } /** @@ -1966,15 +837,17 @@ public static function IMSINH($complexNumber) * Excel Function: * IMSEC(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSEC() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the secant * - * @return float|string + * @return array|float|string */ public static function IMSEC($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sec(); + return ComplexFunctions::IMSEC($complexNumber); } /** @@ -1985,15 +858,17 @@ public static function IMSEC($complexNumber) * Excel Function: * IMSECH(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSECH() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the hyperbolic secant * - * @return float|string + * @return array|float|string */ public static function IMSECH($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->sech(); + return ComplexFunctions::IMSECH($complexNumber); } /** @@ -2004,15 +879,17 @@ public static function IMSECH($complexNumber) * Excel Function: * IMTAN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMTAN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the tangent * - * @return float|string + * @return array|float|string */ public static function IMTAN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->tan(); + return ComplexFunctions::IMTAN($complexNumber); } /** @@ -2023,20 +900,17 @@ public static function IMTAN($complexNumber) * Excel Function: * IMSQRT(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMSQRT() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the square root * - * @return string + * @return array|string */ public static function IMSQRT($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $theta = self::IMARGUMENT($complexNumber); - if ($theta === Functions::DIV0()) { - return '0'; - } - - return (string) (new Complex($complexNumber))->sqrt(); + return ComplexFunctions::IMSQRT($complexNumber); } /** @@ -2047,20 +921,17 @@ public static function IMSQRT($complexNumber) * Excel Function: * IMLN(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLN() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the natural logarithm * - * @return string + * @return array|string */ public static function IMLN($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->ln(); + return ComplexFunctions::IMLN($complexNumber); } /** @@ -2071,20 +942,17 @@ public static function IMLN($complexNumber) * Excel Function: * IMLOG10(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLOG10() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the common logarithm * - * @return string + * @return array|string */ public static function IMLOG10($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->log10(); + return ComplexFunctions::IMLOG10($complexNumber); } /** @@ -2095,20 +963,17 @@ public static function IMLOG10($complexNumber) * Excel Function: * IMLOG2(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMLOG2() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the base-2 logarithm * - * @return string + * @return array|string */ public static function IMLOG2($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - $complex = new Complex($complexNumber); - if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { - return Functions::NAN(); - } - - return (string) (new Complex($complexNumber))->log2(); + return ComplexFunctions::IMLOG2($complexNumber); } /** @@ -2119,15 +984,17 @@ public static function IMLOG2($complexNumber) * Excel Function: * IMEXP(complexNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMEXP() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number for which you want the exponential * - * @return string + * @return array|string */ public static function IMEXP($complexNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - - return (string) (new Complex($complexNumber))->exp(); + return ComplexFunctions::IMEXP($complexNumber); } /** @@ -2138,21 +1005,18 @@ public static function IMEXP($complexNumber) * Excel Function: * IMPOWER(complexNumber,realNumber) * + * @Deprecated 1.18.0 + * + * @see Use the IMPOWER() method in the Engineering\ComplexFunctions class instead + * * @param string $complexNumber the complex number you want to raise to a power * @param float $realNumber the power to which you want to raise the complex number * - * @return string + * @return array|string */ public static function IMPOWER($complexNumber, $realNumber) { - $complexNumber = Functions::flattenSingleValue($complexNumber); - $realNumber = Functions::flattenSingleValue($realNumber); - - if (!is_numeric($realNumber)) { - return Functions::VALUE(); - } - - return (string) (new Complex($complexNumber))->pow($realNumber); + return ComplexFunctions::IMPOWER($complexNumber, $realNumber); } /** @@ -2163,21 +1027,18 @@ public static function IMPOWER($complexNumber, $realNumber) * Excel Function: * IMDIV(complexDividend,complexDivisor) * + * @Deprecated 1.18.0 + * + * @see Use the IMDIV() method in the Engineering\ComplexOperations class instead + * * @param string $complexDividend the complex numerator or dividend * @param string $complexDivisor the complex denominator or divisor * - * @return string + * @return array|string */ public static function IMDIV($complexDividend, $complexDivisor) { - $complexDividend = Functions::flattenSingleValue($complexDividend); - $complexDivisor = Functions::flattenSingleValue($complexDivisor); - - try { - return (string) (new Complex($complexDividend))->divideby(new Complex($complexDivisor)); - } catch (ComplexException $e) { - return Functions::NAN(); - } + return ComplexOperations::IMDIV($complexDividend, $complexDivisor); } /** @@ -2188,21 +1049,18 @@ public static function IMDIV($complexDividend, $complexDivisor) * Excel Function: * IMSUB(complexNumber1,complexNumber2) * + * @Deprecated 1.18.0 + * + * @see Use the IMSUB() method in the Engineering\ComplexOperations class instead + * * @param string $complexNumber1 the complex number from which to subtract complexNumber2 * @param string $complexNumber2 the complex number to subtract from complexNumber1 * - * @return string + * @return array|string */ public static function IMSUB($complexNumber1, $complexNumber2) { - $complexNumber1 = Functions::flattenSingleValue($complexNumber1); - $complexNumber2 = Functions::flattenSingleValue($complexNumber2); - - try { - return (string) (new Complex($complexNumber1))->subtract(new Complex($complexNumber2)); - } catch (ComplexException $e) { - return Functions::NAN(); - } + return ComplexOperations::IMSUB($complexNumber1, $complexNumber2); } /** @@ -2213,26 +1071,17 @@ public static function IMSUB($complexNumber1, $complexNumber2) * Excel Function: * IMSUM(complexNumber[,complexNumber[,...]]) * + * @Deprecated 1.18.0 + * + * @see Use the IMSUM() method in the Engineering\ComplexOperations class instead + * * @param string ...$complexNumbers Series of complex numbers to add * * @return string */ public static function IMSUM(...$complexNumbers) { - // Return value - $returnValue = new Complex(0.0); - $aArgs = Functions::flattenArray($complexNumbers); - - try { - // Loop through the arguments - foreach ($aArgs as $complex) { - $returnValue = $returnValue->add(new Complex($complex)); - } - } catch (ComplexException $e) { - return Functions::NAN(); - } - - return (string) $returnValue; + return ComplexOperations::IMSUM(...$complexNumbers); } /** @@ -2243,50 +1092,42 @@ public static function IMSUM(...$complexNumbers) * Excel Function: * IMPRODUCT(complexNumber[,complexNumber[,...]]) * + * @Deprecated 1.18.0 + * + * @see Use the IMPRODUCT() method in the Engineering\ComplexOperations class instead + * * @param string ...$complexNumbers Series of complex numbers to multiply * * @return string */ public static function IMPRODUCT(...$complexNumbers) { - // Return value - $returnValue = new Complex(1.0); - $aArgs = Functions::flattenArray($complexNumbers); - - try { - // Loop through the arguments - foreach ($aArgs as $complex) { - $returnValue = $returnValue->multiply(new Complex($complex)); - } - } catch (ComplexException $e) { - return Functions::NAN(); - } - - return (string) $returnValue; + return ComplexOperations::IMPRODUCT(...$complexNumbers); } /** * DELTA. * * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. - * Use this function to filter a set of values. For example, by summing several DELTA - * functions you calculate the count of equal pairs. This function is also known as the - * Kronecker Delta function. + * Use this function to filter a set of values. For example, by summing several DELTA + * functions you calculate the count of equal pairs. This function is also known as the + * Kronecker Delta function. * * Excel Function: * DELTA(a[,b]) * + * @Deprecated 1.17.0 + * + * @see Use the DELTA() method in the Engineering\Compare class instead + * * @param float $a the first number * @param float $b The second number. If omitted, b is assumed to be zero. * - * @return int + * @return array|int|string (string in the event of an error) */ public static function DELTA($a, $b = 0) { - $a = Functions::flattenSingleValue($a); - $b = Functions::flattenSingleValue($b); - - return (int) ($a == $b); + return Engineering\Compare::DELTA($a, $b); } /** @@ -2297,79 +1138,20 @@ public static function DELTA($a, $b = 0) * * Returns 1 if number >= step; returns 0 (zero) otherwise * Use this function to filter a set of values. For example, by summing several GESTEP - * functions you calculate the count of values that exceed a threshold. - * - * @param float $number the value to test against step - * @param float $step The threshold value. - * If you omit a value for step, GESTEP uses zero. + * functions you calculate the count of values that exceed a threshold. * - * @return int - */ - public static function GESTEP($number, $step = 0) - { - $number = Functions::flattenSingleValue($number); - $step = Functions::flattenSingleValue($step); - - return (int) ($number >= $step); - } - - // - // Private method to calculate the erf value - // - private static $twoSqrtPi = 1.128379167095512574; - - public static function erfVal($x) - { - if (abs($x) > 2.2) { - return 1 - self::erfcVal($x); - } - $sum = $term = $x; - $xsqr = ($x * $x); - $j = 1; - do { - $term *= $xsqr / $j; - $sum -= $term / (2 * $j + 1); - ++$j; - $term *= $xsqr / $j; - $sum += $term / (2 * $j + 1); - ++$j; - if ($sum == 0.0) { - break; - } - } while (abs($term / $sum) > Functions::PRECISION); - - return self::$twoSqrtPi * $sum; - } - - /** - * Validate arguments passed to the bitwise functions. + * @Deprecated 1.17.0 * - * @param mixed $value + * @see Use the GESTEP() method in the Engineering\Compare class instead * - * @throws Exception + * @param float $number the value to test against step + * @param float $step The threshold value. If you omit a value for step, GESTEP uses zero. * - * @return int + * @return array|int|string (string in the event of an error) */ - private static function validateBitwiseArgument($value) + public static function GESTEP($number, $step = 0) { - $value = Functions::flattenSingleValue($value); - - if (is_int($value)) { - return $value; - } elseif (is_numeric($value)) { - if ($value == (int) ($value)) { - $value = (int) ($value); - if (($value > pow(2, 48) - 1) || ($value < 0)) { - throw new Exception(Functions::NAN()); - } - - return $value; - } - - throw new Exception(Functions::NAN()); - } - - throw new Exception(Functions::VALUE()); + return Engineering\Compare::GESTEP($number, $step); } /** @@ -2380,23 +1162,18 @@ private static function validateBitwiseArgument($value) * Excel Function: * BITAND(number1, number2) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BITAND() method in the Engineering\BitWise class instead * * @param int $number1 * @param int $number2 * - * @return int|string + * @return array|int|string */ public static function BITAND($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 & $number2; + return Engineering\BitWise::BITAND($number1, $number2); } /** @@ -2407,23 +1184,18 @@ public static function BITAND($number1, $number2) * Excel Function: * BITOR(number1, number2) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BITOR() method in the Engineering\BitWise class instead * * @param int $number1 * @param int $number2 * - * @return int|string + * @return array|int|string */ public static function BITOR($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 | $number2; + return Engineering\BitWise::BITOR($number1, $number2); } /** @@ -2434,23 +1206,18 @@ public static function BITOR($number1, $number2) * Excel Function: * BITXOR(number1, number2) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BITXOR() method in the Engineering\BitWise class instead * * @param int $number1 * @param int $number2 * - * @return int|string + * @return array|int|string */ public static function BITXOR($number1, $number2) { - try { - $number1 = self::validateBitwiseArgument($number1); - $number2 = self::validateBitwiseArgument($number2); - } catch (Exception $e) { - return $e->getMessage(); - } - - return $number1 ^ $number2; + return Engineering\BitWise::BITXOR($number1, $number2); } /** @@ -2461,29 +1228,18 @@ public static function BITXOR($number1, $number2) * Excel Function: * BITLSHIFT(number, shift_amount) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BITLSHIFT() method in the Engineering\BitWise class instead * * @param int $number * @param int $shiftAmount * - * @return int|string + * @return array|float|int|string */ public static function BITLSHIFT($number, $shiftAmount) { - try { - $number = self::validateBitwiseArgument($number); - } catch (Exception $e) { - return $e->getMessage(); - } - - $shiftAmount = Functions::flattenSingleValue($shiftAmount); - - $result = $number << $shiftAmount; - if ($result > pow(2, 48) - 1) { - return Functions::NAN(); - } - - return $result; + return Engineering\BitWise::BITLSHIFT($number, $shiftAmount); } /** @@ -2494,24 +1250,18 @@ public static function BITLSHIFT($number, $shiftAmount) * Excel Function: * BITRSHIFT(number, shift_amount) * - * @category Engineering Functions + * @Deprecated 1.17.0 + * + * @see Use the BITRSHIFT() method in the Engineering\BitWise class instead * * @param int $number * @param int $shiftAmount * - * @return int|string + * @return array|float|int|string */ public static function BITRSHIFT($number, $shiftAmount) { - try { - $number = self::validateBitwiseArgument($number); - } catch (Exception $e) { - return $e->getMessage(); - } - - $shiftAmount = Functions::flattenSingleValue($shiftAmount); - - return $number >> $shiftAmount; + return Engineering\BitWise::BITRSHIFT($number, $shiftAmount); } /** @@ -2527,27 +1277,19 @@ public static function BITRSHIFT($number, $shiftAmount) * Excel Function: * ERF(lower[,upper]) * + * @Deprecated 1.17.0 + * + * @see Use the ERF() method in the Engineering\Erf class instead + * * @param float $lower lower bound for integrating ERF * @param float $upper upper bound for integrating ERF. * If omitted, ERF integrates between zero and lower_limit * - * @return float|string + * @return array|float|string */ public static function ERF($lower, $upper = null) { - $lower = Functions::flattenSingleValue($lower); - $upper = Functions::flattenSingleValue($upper); - - if (is_numeric($lower)) { - if ($upper === null) { - return self::erfVal($lower); - } - if (is_numeric($upper)) { - return self::erfVal($upper) - self::erfVal($lower); - } - } - - return Functions::VALUE(); + return Engineering\Erf::ERF($lower, $upper); } /** @@ -2558,48 +1300,17 @@ public static function ERF($lower, $upper = null) * Excel Function: * ERF.PRECISE(limit) * + * @Deprecated 1.17.0 + * + * @see Use the ERFPRECISE() method in the Engineering\Erf class instead + * * @param float $limit bound for integrating ERF * - * @return float|string + * @return array|float|string */ public static function ERFPRECISE($limit) { - $limit = Functions::flattenSingleValue($limit); - - return self::ERF($limit); - } - - // - // Private method to calculate the erfc value - // - private static $oneSqrtPi = 0.564189583547756287; - - private static function erfcVal($x) - { - if (abs($x) < 2.2) { - return 1 - self::erfVal($x); - } - if ($x < 0) { - return 2 - self::ERFC(-$x); - } - $a = $n = 1; - $b = $c = $x; - $d = ($x * $x) + 0.5; - $q1 = $q2 = $b / $d; - $t = 0; - do { - $t = $a * $n + $b * $x; - $a = $b; - $b = $t; - $t = $c * $n + $d * $x; - $c = $d; - $d = $t; - $n += 0.5; - $q1 = $q2; - $q2 = $b / $d; - } while ((abs($q1 - $q2) / $q2) > Functions::PRECISION); - - return self::$oneSqrtPi * exp(-$x * $x) * $q2; + return Engineering\Erf::ERFPRECISE($limit); } /** @@ -2615,88 +1326,97 @@ private static function erfcVal($x) * Excel Function: * ERFC(x) * + * @Deprecated 1.17.0 + * + * @see Use the ERFC() method in the Engineering\ErfC class instead + * * @param float $x The lower bound for integrating ERFC * - * @return float|string + * @return array|float|string */ public static function ERFC($x) { - $x = Functions::flattenSingleValue($x); - - if (is_numeric($x)) { - return self::erfcVal($x); - } - - return Functions::VALUE(); + return Engineering\ErfC::ERFC($x); } /** * getConversionGroups * Returns a list of the different conversion groups for UOM conversions. * + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategories() method in the Engineering\ConvertUOM class instead + * * @return array */ public static function getConversionGroups() { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit) { - $conversionGroups[] = $conversionUnit['Group']; - } - - return array_merge(array_unique($conversionGroups)); + return Engineering\ConvertUOM::getConversionCategories(); } /** * getConversionGroupUnits * Returns an array of units of measure, for a specified conversion group, or for all groups. * - * @param string $group The group whose units of measure you want to retrieve + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategoryUnits() method in the ConvertUOM class instead + * + * @param null|mixed $category * * @return array */ - public static function getConversionGroupUnits($group = null) + public static function getConversionGroupUnits($category = null) { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { - if (($group === null) || ($conversionGroup['Group'] == $group)) { - $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; - } - } - - return $conversionGroups; + return Engineering\ConvertUOM::getConversionCategoryUnits($category); } /** * getConversionGroupUnitDetails. * - * @param string $group The group whose units of measure you want to retrieve + * @Deprecated 1.16.0 + * + * @see Use the getConversionCategoryUnitDetails() method in the ConvertUOM class instead + * + * @param null|mixed $category * * @return array */ - public static function getConversionGroupUnitDetails($group = null) + public static function getConversionGroupUnitDetails($category = null) { - $conversionGroups = []; - foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { - if (($group === null) || ($conversionGroup['Group'] == $group)) { - $conversionGroups[$conversionGroup['Group']][] = [ - 'unit' => $conversionUnit, - 'description' => $conversionGroup['Unit Name'], - ]; - } - } - - return $conversionGroups; + return Engineering\ConvertUOM::getConversionCategoryUnitDetails($category); } /** * getConversionMultipliers * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). * - * @return array of mixed + * @Deprecated 1.16.0 + * + * @see Use the getConversionMultipliers() method in the ConvertUOM class instead + * + * @return mixed[] */ public static function getConversionMultipliers() { - return self::$conversionMultipliers; + return Engineering\ConvertUOM::getConversionMultipliers(); + } + + /** + * getBinaryConversionMultipliers. + * + * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure + * in CONVERTUOM(). + * + * @Deprecated 1.16.0 + * + * @see Use the getBinaryConversionMultipliers() method in the ConvertUOM class instead + * + * @return mixed[] + */ + public static function getBinaryConversionMultipliers() + { + return Engineering\ConvertUOM::getBinaryConversionMultipliers(); } /** @@ -2709,99 +1429,18 @@ public static function getConversionMultipliers() * Excel Function: * CONVERT(value,fromUOM,toUOM) * - * @param float $value the value in fromUOM to convert + * @Deprecated 1.16.0 + * + * @see Use the CONVERT() method in the ConvertUOM class instead + * + * @param float|int $value the value in fromUOM to convert * @param string $fromUOM the units for value * @param string $toUOM the units for the result * - * @return float|string + * @return array|float|string */ public static function CONVERTUOM($value, $fromUOM, $toUOM) { - $value = Functions::flattenSingleValue($value); - $fromUOM = Functions::flattenSingleValue($fromUOM); - $toUOM = Functions::flattenSingleValue($toUOM); - - if (!is_numeric($value)) { - return Functions::VALUE(); - } - $fromMultiplier = 1.0; - if (isset(self::$conversionUnits[$fromUOM])) { - $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; - } else { - $fromMultiplier = substr($fromUOM, 0, 1); - $fromUOM = substr($fromUOM, 1); - if (isset(self::$conversionMultipliers[$fromMultiplier])) { - $fromMultiplier = self::$conversionMultipliers[$fromMultiplier]['multiplier']; - } else { - return Functions::NA(); - } - if ((isset(self::$conversionUnits[$fromUOM])) && (self::$conversionUnits[$fromUOM]['AllowPrefix'])) { - $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; - } else { - return Functions::NA(); - } - } - $value *= $fromMultiplier; - - $toMultiplier = 1.0; - if (isset(self::$conversionUnits[$toUOM])) { - $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; - } else { - $toMultiplier = substr($toUOM, 0, 1); - $toUOM = substr($toUOM, 1); - if (isset(self::$conversionMultipliers[$toMultiplier])) { - $toMultiplier = self::$conversionMultipliers[$toMultiplier]['multiplier']; - } else { - return Functions::NA(); - } - if ((isset(self::$conversionUnits[$toUOM])) && (self::$conversionUnits[$toUOM]['AllowPrefix'])) { - $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; - } else { - return Functions::NA(); - } - } - if ($unitGroup1 != $unitGroup2) { - return Functions::NA(); - } - - if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) { - // We've already factored $fromMultiplier into the value, so we need - // to reverse it again - return $value / $fromMultiplier; - } elseif ($unitGroup1 == 'Temperature') { - if (($fromUOM == 'F') || ($fromUOM == 'fah')) { - if (($toUOM == 'F') || ($toUOM == 'fah')) { - return $value; - } - $value = (($value - 32) / 1.8); - if (($toUOM == 'K') || ($toUOM == 'kel')) { - $value += 273.15; - } - - return $value; - } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) && - (($toUOM == 'K') || ($toUOM == 'kel')) - ) { - return $value; - } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) && - (($toUOM == 'C') || ($toUOM == 'cel')) - ) { - return $value; - } - if (($toUOM == 'F') || ($toUOM == 'fah')) { - if (($fromUOM == 'K') || ($fromUOM == 'kel')) { - $value -= 273.15; - } - - return ($value * 1.8) + 32; - } - if (($toUOM == 'C') || ($toUOM == 'cel')) { - return $value - 273.15; - } - - return $value + 273.15; - } - - return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier; + return Engineering\ConvertUOM::CONVERT($value, $fromUOM, $toUOM); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php new file mode 100644 index 00000000..2afb52bd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselI.php @@ -0,0 +1,145 @@ +getMessage(); + } + + if ($ord < 0) { + return ExcelError::NAN(); + } + + $fResult = self::calculate($x, $ord); + + return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselI0($x); + case 1: + return self::besselI1($x); + } + + return self::besselI2($x, $ord); + } + + private static function besselI0(float $x): float + { + $ax = abs($x); + + if ($ax < 3.75) { + $y = $x / 3.75; + $y = $y * $y; + + return 1.0 + $y * (3.5156229 + $y * (3.0899424 + $y * (1.2067492 + + $y * (0.2659732 + $y * (0.360768e-1 + $y * 0.45813e-2))))); + } + + $y = 3.75 / $ax; + + return (exp($ax) / sqrt($ax)) * (0.39894228 + $y * (0.1328592e-1 + $y * (0.225319e-2 + $y * (-0.157565e-2 + + $y * (0.916281e-2 + $y * (-0.2057706e-1 + $y * (0.2635537e-1 + + $y * (-0.1647633e-1 + $y * 0.392377e-2)))))))); + } + + private static function besselI1(float $x): float + { + $ax = abs($x); + + if ($ax < 3.75) { + $y = $x / 3.75; + $y = $y * $y; + $ans = $ax * (0.5 + $y * (0.87890594 + $y * (0.51498869 + $y * (0.15084934 + $y * (0.2658733e-1 + + $y * (0.301532e-2 + $y * 0.32411e-3)))))); + + return ($x < 0.0) ? -$ans : $ans; + } + + $y = 3.75 / $ax; + $ans = 0.2282967e-1 + $y * (-0.2895312e-1 + $y * (0.1787654e-1 - $y * 0.420059e-2)); + $ans = 0.39894228 + $y * (-0.3988024e-1 + $y * (-0.362018e-2 + $y * (0.163801e-2 + + $y * (-0.1031555e-1 + $y * $ans)))); + $ans *= exp($ax) / sqrt($ax); + + return ($x < 0.0) ? -$ans : $ans; + } + + private static function besselI2(float $x, int $ord): float + { + if ($x === 0.0) { + return 0.0; + } + + $tox = 2.0 / abs($x); + $bip = 0; + $ans = 0.0; + $bi = 1.0; + + for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { + $bim = $bip + $j * $tox * $bi; + $bip = $bi; + $bi = $bim; + + if (abs($bi) > 1.0e+12) { + $ans *= 1.0e-12; + $bi *= 1.0e-12; + $bip *= 1.0e-12; + } + + if ($j === $ord) { + $ans = $bip; + } + } + + $ans *= self::besselI0($x) / $bi; + + return ($x < 0.0 && (($ord % 2) === 1)) ? -$ans : $ans; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php new file mode 100644 index 00000000..e23b0157 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselJ.php @@ -0,0 +1,180 @@ + 8. This code provides a more accurate calculation + * + * @param mixed $x A float value at which to evaluate the function. + * If x is nonnumeric, BESSELJ returns the #VALUE! error value. + * Or can be an array of values + * @param mixed $ord The integer order of the Bessel function. + * If ord is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. + * If $ord < 0, BESSELJ returns the #NUM! error value. + * Or can be an array of values + * + * @return array|float|string Result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function BESSELJ($x, $ord) + { + if (is_array($x) || is_array($ord)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $ord); + } + + try { + $x = EngineeringValidations::validateFloat($x); + $ord = EngineeringValidations::validateInt($ord); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($ord < 0) { + return ExcelError::NAN(); + } + + $fResult = self::calculate($x, $ord); + + return (is_nan($fResult)) ? ExcelError::NAN() : $fResult; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselJ0($x); + case 1: + return self::besselJ1($x); + } + + return self::besselJ2($x, $ord); + } + + private static function besselJ0(float $x): float + { + $ax = abs($x); + + if ($ax < 8.0) { + $y = $x * $x; + $ans1 = 57568490574.0 + $y * (-13362590354.0 + $y * (651619640.7 + $y * (-11214424.18 + $y * + (77392.33017 + $y * (-184.9052456))))); + $ans2 = 57568490411.0 + $y * (1029532985.0 + $y * (9494680.718 + $y * (59272.64853 + $y * + (267.8532712 + $y * 1.0)))); + + return $ans1 / $ans2; + } + + $z = 8.0 / $ax; + $y = $z * $z; + $xx = $ax - 0.785398164; + $ans1 = 1.0 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * + (0.7621095161e-6 - $y * 0.934935152e-7))); + + return sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); + } + + private static function besselJ1(float $x): float + { + $ax = abs($x); + + if ($ax < 8.0) { + $y = $x * $x; + $ans1 = $x * (72362614232.0 + $y * (-7895059235.0 + $y * (242396853.1 + $y * + (-2972611.439 + $y * (15704.48260 + $y * (-30.16036606)))))); + $ans2 = 144725228442.0 + $y * (2300535178.0 + $y * (18583304.74 + $y * (99447.43394 + $y * + (376.9991397 + $y * 1.0)))); + + return $ans1 / $ans2; + } + + $z = 8.0 / $ax; + $y = $z * $z; + $xx = $ax - 2.356194491; + + $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); + $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * + (-0.88228987e-6 + $y * 0.105787412e-6))); + $ans = sqrt(0.636619772 / $ax) * (cos($xx) * $ans1 - $z * sin($xx) * $ans2); + + return ($x < 0.0) ? -$ans : $ans; + } + + private static function besselJ2(float $x, int $ord): float + { + $ax = abs($x); + if ($ax === 0.0) { + return 0.0; + } + + if ($ax > $ord) { + return self::besselj2a($ax, $ord, $x); + } + + return self::besselj2b($ax, $ord, $x); + } + + private static function besselj2a(float $ax, int $ord, float $x) + { + $tox = 2.0 / $ax; + $bjm = self::besselJ0($ax); + $bj = self::besselJ1($ax); + for ($j = 1; $j < $ord; ++$j) { + $bjp = $j * $tox * $bj - $bjm; + $bjm = $bj; + $bj = $bjp; + } + $ans = $bj; + + return ($x < 0.0 && ($ord % 2) == 1) ? -$ans : $ans; + } + + private static function besselj2b(float $ax, int $ord, float $x) + { + $tox = 2.0 / $ax; + $jsum = false; + $bjp = $ans = $sum = 0.0; + $bj = 1.0; + for ($j = 2 * ($ord + (int) sqrt(40.0 * $ord)); $j > 0; --$j) { + $bjm = $j * $tox * $bj - $bjp; + $bjp = $bj; + $bj = $bjm; + if (abs($bj) > 1.0e+10) { + $bj *= 1.0e-10; + $bjp *= 1.0e-10; + $ans *= 1.0e-10; + $sum *= 1.0e-10; + } + if ($jsum === true) { + $sum += $bj; + } + $jsum = !$jsum; + if ($j === $ord) { + $ans = $bjp; + } + } + $sum = 2.0 * $sum - $bj; + $ans /= $sum; + + return ($x < 0.0 && ($ord % 2) === 1) ? -$ans : $ans; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php new file mode 100644 index 00000000..2d21e752 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselK.php @@ -0,0 +1,135 @@ +getMessage(); + } + + if (($ord < 0) || ($x <= 0.0)) { + return ExcelError::NAN(); + } + + $fBk = self::calculate($x, $ord); + + return (is_nan($fBk)) ? ExcelError::NAN() : $fBk; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselK0($x); + case 1: + return self::besselK1($x); + } + + return self::besselK2($x, $ord); + } + + /** + * Mollify Phpstan. + * + * @codeCoverageIgnore + */ + private static function callBesselI(float $x, int $ord): float + { + $rslt = BesselI::BESSELI($x, $ord); + if (!is_float($rslt)) { + throw new Exception('Unexpected array or string'); + } + + return $rslt; + } + + private static function besselK0(float $x): float + { + if ($x <= 2) { + $fNum2 = $x * 0.5; + $y = ($fNum2 * $fNum2); + + return -log($fNum2) * self::callBesselI($x, 0) + + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * + (0.10750e-3 + $y * 0.74e-5)))))); + } + + $y = 2 / $x; + + return exp(-$x) / sqrt($x) * + (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * + (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); + } + + private static function besselK1(float $x): float + { + if ($x <= 2) { + $fNum2 = $x * 0.5; + $y = ($fNum2 * $fNum2); + + return log($fNum2) * self::callBesselI($x, 1) + + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * + (-0.110404e-2 + $y * (-0.4686e-4))))))) / $x; + } + + $y = 2 / $x; + + return exp(-$x) / sqrt($x) * + (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * + (0.325614e-2 + $y * (-0.68245e-3))))))); + } + + private static function besselK2(float $x, int $ord): float + { + $fTox = 2 / $x; + $fBkm = self::besselK0($x); + $fBk = self::besselK1($x); + for ($n = 1; $n < $ord; ++$n) { + $fBkp = $fBkm + $n * $fTox * $fBk; + $fBkm = $fBk; + $fBk = $fBkp; + } + + return $fBk; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php new file mode 100644 index 00000000..31d9694a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BesselY.php @@ -0,0 +1,141 @@ +getMessage(); + } + + if (($ord < 0) || ($x <= 0.0)) { + return ExcelError::NAN(); + } + + $fBy = self::calculate($x, $ord); + + return (is_nan($fBy)) ? ExcelError::NAN() : $fBy; + } + + private static function calculate(float $x, int $ord): float + { + // special cases + switch ($ord) { + case 0: + return self::besselY0($x); + case 1: + return self::besselY1($x); + } + + return self::besselY2($x, $ord); + } + + /** + * Mollify Phpstan. + * + * @codeCoverageIgnore + */ + private static function callBesselJ(float $x, int $ord): float + { + $rslt = BesselJ::BESSELJ($x, $ord); + if (!is_float($rslt)) { + throw new Exception('Unexpected array or string'); + } + + return $rslt; + } + + private static function besselY0(float $x): float + { + if ($x < 8.0) { + $y = ($x * $x); + $ans1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * + (-86327.92757 + $y * 228.4622733)))); + $ans2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * + (47447.26470 + $y * (226.1030244 + $y)))); + + return $ans1 / $ans2 + 0.636619772 * self::callBesselJ($x, 0) * log($x); + } + + $z = 8.0 / $x; + $y = ($z * $z); + $xx = $x - 0.785398164; + $ans1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $ans2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * + (-0.934945152e-7)))); + + return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); + } + + private static function besselY1(float $x): float + { + if ($x < 8.0) { + $y = ($x * $x); + $ans1 = $x * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * + (0.7349264551e9 + $y * (-0.4237922726e7 + $y * 0.8511937935e4))))); + $ans2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * + (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); + + return ($ans1 / $ans2) + 0.636619772 * (self::callBesselJ($x, 1) * log($x) - 1 / $x); + } + + $z = 8.0 / $x; + $y = $z * $z; + $xx = $x - 2.356194491; + $ans1 = 1.0 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e-6)))); + $ans2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * + (-0.88228987e-6 + $y * 0.105787412e-6))); + + return sqrt(0.636619772 / $x) * (sin($xx) * $ans1 + $z * cos($xx) * $ans2); + } + + private static function besselY2(float $x, int $ord): float + { + $fTox = 2.0 / $x; + $fBym = self::besselY0($x); + $fBy = self::besselY1($x); + for ($n = 1; $n < $ord; ++$n) { + $fByp = $n * $fTox * $fBy - $fBym; + $fBym = $fBy; + $fBy = $fByp; + } + + return $fBy; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php new file mode 100644 index 00000000..adeb1b55 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/BitWise.php @@ -0,0 +1,275 @@ +getMessage(); + } + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] & $split2[0]) + ($split1[1] & $split2[1]); + } + + /** + * BITOR. + * + * Returns the bitwise OR of two integer values. + * + * Excel Function: + * BITOR(number1, number2) + * + * @param array|int $number1 + * Or can be an array of values + * @param array|int $number2 + * Or can be an array of values + * + * @return array|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function BITOR($number1, $number2) + { + if (is_array($number1) || is_array($number2)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); + } + + try { + $number1 = self::validateBitwiseArgument($number1); + $number2 = self::validateBitwiseArgument($number2); + } catch (Exception $e) { + return $e->getMessage(); + } + + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] | $split2[0]) + ($split1[1] | $split2[1]); + } + + /** + * BITXOR. + * + * Returns the bitwise XOR of two integer values. + * + * Excel Function: + * BITXOR(number1, number2) + * + * @param array|int $number1 + * Or can be an array of values + * @param array|int $number2 + * Or can be an array of values + * + * @return array|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function BITXOR($number1, $number2) + { + if (is_array($number1) || is_array($number2)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number1, $number2); + } + + try { + $number1 = self::validateBitwiseArgument($number1); + $number2 = self::validateBitwiseArgument($number2); + } catch (Exception $e) { + return $e->getMessage(); + } + + $split1 = self::splitNumber($number1); + $split2 = self::splitNumber($number2); + + return self::SPLIT_DIVISOR * ($split1[0] ^ $split2[0]) + ($split1[1] ^ $split2[1]); + } + + /** + * BITLSHIFT. + * + * Returns the number value shifted left by shift_amount bits. + * + * Excel Function: + * BITLSHIFT(number, shift_amount) + * + * @param array|int $number + * Or can be an array of values + * @param array|int $shiftAmount + * Or can be an array of values + * + * @return array|float|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function BITLSHIFT($number, $shiftAmount) + { + if (is_array($number) || is_array($shiftAmount)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); + } + + try { + $number = self::validateBitwiseArgument($number); + $shiftAmount = self::validateShiftAmount($shiftAmount); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = floor($number * (2 ** $shiftAmount)); + if ($result > 2 ** 48 - 1) { + return ExcelError::NAN(); + } + + return $result; + } + + /** + * BITRSHIFT. + * + * Returns the number value shifted right by shift_amount bits. + * + * Excel Function: + * BITRSHIFT(number, shift_amount) + * + * @param array|int $number + * Or can be an array of values + * @param array|int $shiftAmount + * Or can be an array of values + * + * @return array|float|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function BITRSHIFT($number, $shiftAmount) + { + if (is_array($number) || is_array($shiftAmount)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $shiftAmount); + } + + try { + $number = self::validateBitwiseArgument($number); + $shiftAmount = self::validateShiftAmount($shiftAmount); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = floor($number / (2 ** $shiftAmount)); + if ($result > 2 ** 48 - 1) { // possible because shiftAmount can be negative + return ExcelError::NAN(); + } + + return $result; + } + + /** + * Validate arguments passed to the bitwise functions. + * + * @param mixed $value + * + * @return float + */ + private static function validateBitwiseArgument($value) + { + $value = self::nullFalseTrueToNumber($value); + + if (is_numeric($value)) { + $value = (float) $value; + if ($value == floor($value)) { + if (($value > 2 ** 48 - 1) || ($value < 0)) { + throw new Exception(ExcelError::NAN()); + } + + return floor($value); + } + + throw new Exception(ExcelError::NAN()); + } + + throw new Exception(ExcelError::VALUE()); + } + + /** + * Validate arguments passed to the bitwise functions. + * + * @param mixed $value + * + * @return int + */ + private static function validateShiftAmount($value) + { + $value = self::nullFalseTrueToNumber($value); + + if (is_numeric($value)) { + if (abs($value) > 53) { + throw new Exception(ExcelError::NAN()); + } + + return (int) $value; + } + + throw new Exception(ExcelError::VALUE()); + } + + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @param mixed $number + * + * @return mixed + */ + private static function nullFalseTrueToNumber(&$number) + { + if ($number === null) { + $number = 0; + } elseif (is_bool($number)) { + $number = (int) $number; + } + + return $number; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php new file mode 100644 index 00000000..4d4bc07e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Compare.php @@ -0,0 +1,82 @@ +getMessage(); + } + + return (int) (abs($a - $b) < 1.0e-15); + } + + /** + * GESTEP. + * + * Excel Function: + * GESTEP(number[,step]) + * + * Returns 1 if number >= step; returns 0 (zero) otherwise + * Use this function to filter a set of values. For example, by summing several GESTEP + * functions you calculate the count of values that exceed a threshold. + * + * @param array|float $number the value to test against step + * Or can be an array of values + * @param array|float $step The threshold value. If you omit a value for step, GESTEP uses zero. + * Or can be an array of values + * + * @return array|int|string (string in the event of an error) + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function GESTEP($number, $step = 0.0) + { + if (is_array($number) || is_array($step)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $step); + } + + try { + $number = EngineeringValidations::validateFloat($number); + $step = EngineeringValidations::validateFloat($step); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (int) ($number >= $step); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php new file mode 100644 index 00000000..691de8b7 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Complex.php @@ -0,0 +1,121 @@ +getMessage(); + } + + if (($suffix == 'i') || ($suffix == 'j') || ($suffix == '')) { + $complex = new ComplexObject($realNumber, $imaginary, $suffix); + + return (string) $complex; + } + + return ExcelError::VALUE(); + } + + /** + * IMAGINARY. + * + * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMAGINARY(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the imaginary + * coefficient + * Or can be an array of values + * + * @return array|float|string (string if an error) + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMAGINARY($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return $complex->getImaginary(); + } + + /** + * IMREAL. + * + * Returns the real coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMREAL(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the real coefficient + * Or can be an array of values + * + * @return array|float|string (string if an error) + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMREAL($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return $complex->getReal(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php new file mode 100644 index 00000000..28a27a03 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexFunctions.php @@ -0,0 +1,611 @@ +abs(); + } + + /** + * IMARGUMENT. + * + * Returns the argument theta of a complex number, i.e. the angle in radians from the real + * axis to the representation of the number in polar coordinates. + * + * Excel Function: + * IMARGUMENT(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the argument theta + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMARGUMENT($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return ExcelError::DIV0(); + } + + return $complex->argument(); + } + + /** + * IMCONJUGATE. + * + * Returns the complex conjugate of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCONJUGATE(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the conjugate + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCONJUGATE($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->conjugate(); + } + + /** + * IMCOS. + * + * Returns the cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOS(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the cosine + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCOS($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->cos(); + } + + /** + * IMCOSH. + * + * Returns the hyperbolic cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOSH(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic cosine + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCOSH($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->cosh(); + } + + /** + * IMCOT. + * + * Returns the cotangent of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOT(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the cotangent + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCOT($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->cot(); + } + + /** + * IMCSC. + * + * Returns the cosecant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCSC(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the cosecant + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCSC($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->csc(); + } + + /** + * IMCSCH. + * + * Returns the hyperbolic cosecant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCSCH(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic cosecant + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMCSCH($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->csch(); + } + + /** + * IMSIN. + * + * Returns the sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSIN(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the sine + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSIN($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->sin(); + } + + /** + * IMSINH. + * + * Returns the hyperbolic sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSINH(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic sine + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSINH($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->sinh(); + } + + /** + * IMSEC. + * + * Returns the secant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSEC(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the secant + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSEC($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->sec(); + } + + /** + * IMSECH. + * + * Returns the hyperbolic secant of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSECH(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the hyperbolic secant + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSECH($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->sech(); + } + + /** + * IMTAN. + * + * Returns the tangent of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMTAN(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the tangent + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMTAN($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->tan(); + } + + /** + * IMSQRT. + * + * Returns the square root of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSQRT(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the square root + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSQRT($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + $theta = self::IMARGUMENT($complexNumber); + if ($theta === ExcelError::DIV0()) { + return '0'; + } + + return (string) $complex->sqrt(); + } + + /** + * IMLN. + * + * Returns the natural logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLN(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the natural logarithm + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMLN($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return ExcelError::NAN(); + } + + return (string) $complex->ln(); + } + + /** + * IMLOG10. + * + * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG10(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the common logarithm + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMLOG10($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return ExcelError::NAN(); + } + + return (string) $complex->log10(); + } + + /** + * IMLOG2. + * + * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG2(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the base-2 logarithm + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMLOG2($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) { + return ExcelError::NAN(); + } + + return (string) $complex->log2(); + } + + /** + * IMEXP. + * + * Returns the exponential of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMEXP(complexNumber) + * + * @param array|string $complexNumber the complex number for which you want the exponential + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMEXP($complexNumber) + { + if (is_array($complexNumber)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $complexNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $complex->exp(); + } + + /** + * IMPOWER. + * + * Returns a complex number in x + yi or x + yj text format raised to a power. + * + * Excel Function: + * IMPOWER(complexNumber,realNumber) + * + * @param array|string $complexNumber the complex number you want to raise to a power + * Or can be an array of values + * @param array|float|int|string $realNumber the power to which you want to raise the complex number + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMPOWER($complexNumber, $realNumber) + { + if (is_array($complexNumber) || is_array($realNumber)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber, $realNumber); + } + + try { + $complex = new ComplexObject($complexNumber); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + if (!is_numeric($realNumber)) { + return ExcelError::VALUE(); + } + + return (string) $complex->pow((float) $realNumber); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php new file mode 100644 index 00000000..e525b4b9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ComplexOperations.php @@ -0,0 +1,134 @@ +divideby(new ComplexObject($complexDivisor)); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + } + + /** + * IMSUB. + * + * Returns the difference of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUB(complexNumber1,complexNumber2) + * + * @param array|string $complexNumber1 the complex number from which to subtract complexNumber2 + * Or can be an array of values + * @param array|string $complexNumber2 the complex number to subtract from complexNumber1 + * Or can be an array of values + * + * @return array|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function IMSUB($complexNumber1, $complexNumber2) + { + if (is_array($complexNumber1) || is_array($complexNumber2)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $complexNumber1, $complexNumber2); + } + + try { + return (string) (new ComplexObject($complexNumber1))->subtract(new ComplexObject($complexNumber2)); + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + } + + /** + * IMSUM. + * + * Returns the sum of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUM(complexNumber[,complexNumber[,...]]) + * + * @param string ...$complexNumbers Series of complex numbers to add + * + * @return string + */ + public static function IMSUM(...$complexNumbers) + { + // Return value + $returnValue = new ComplexObject(0.0); + $aArgs = Functions::flattenArray($complexNumbers); + + try { + // Loop through the arguments + foreach ($aArgs as $complex) { + $returnValue = $returnValue->add(new ComplexObject($complex)); + } + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $returnValue; + } + + /** + * IMPRODUCT. + * + * Returns the product of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMPRODUCT(complexNumber[,complexNumber[,...]]) + * + * @param string ...$complexNumbers Series of complex numbers to multiply + * + * @return string + */ + public static function IMPRODUCT(...$complexNumbers) + { + // Return value + $returnValue = new ComplexObject(1.0); + $aArgs = Functions::flattenArray($complexNumbers); + + try { + // Loop through the arguments + foreach ($aArgs as $complex) { + $returnValue = $returnValue->multiply(new ComplexObject($complex)); + } + } catch (ComplexException $e) { + return ExcelError::NAN(); + } + + return (string) $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php new file mode 100644 index 00000000..a926db6e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/Constants.php @@ -0,0 +1,11 @@ + 10) { + throw new Exception(ExcelError::NAN()); + } + + return (int) $places; + } + + throw new Exception(ExcelError::VALUE()); + } + + /** + * Formats a number base string value with leading zeroes. + * + * @param string $value The "number" to pad + * @param ?int $places The length that we want to pad this value + * + * @return string The padded "number" + */ + protected static function nbrConversionFormat(string $value, ?int $places): string + { + if ($places !== null) { + if (strlen($value) <= $places) { + return substr(str_pad($value, $places, '0', STR_PAD_LEFT), -10); + } + + return ExcelError::NAN(); + } + + return substr($value, -10); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php new file mode 100644 index 00000000..4741f301 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertBinary.php @@ -0,0 +1,163 @@ +getMessage(); + } + + if (strlen($value) == 10) { + // Two's Complement + $value = substr($value, -9); + + return '-' . (512 - bindec($value)); + } + + return (string) bindec($value); + } + + /** + * toHex. + * + * Return a binary value as hex. + * + * Excel Function: + * BIN2HEX(x[,places]) + * + * @param array|string $value The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, BIN2HEX uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. + * If places is negative, BIN2HEX returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toHex($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateBinary($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) == 10) { + $high2 = substr($value, 0, 2); + $low8 = substr($value, 2); + $xarr = ['00' => '00000000', '01' => '00000001', '10' => 'FFFFFFFE', '11' => 'FFFFFFFF']; + + return $xarr[$high2] . strtoupper(substr('0' . dechex((int) bindec($low8)), -2)); + } + $hexVal = (string) strtoupper(dechex((int) bindec($value))); + + return self::nbrConversionFormat($hexVal, $places); + } + + /** + * toOctal. + * + * Return a binary value as octal. + * + * Excel Function: + * BIN2OCT(x[,places]) + * + * @param array|string $value The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, BIN2OCT uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. + * If places is negative, BIN2OCT returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toOctal($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateBinary($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) == 10 && substr($value, 0, 1) === '1') { // Two's Complement + return str_repeat('7', 6) . strtoupper(decoct((int) bindec("11$value"))); + } + $octVal = (string) decoct((int) bindec($value)); + + return self::nbrConversionFormat($octVal, $places); + } + + protected static function validateBinary(string $value): string + { + if ((strlen($value) > preg_match_all('/[01]/', $value)) || (strlen($value) > 10)) { + throw new Exception(ExcelError::NAN()); + } + + return $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php new file mode 100644 index 00000000..9b59d399 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertDecimal.php @@ -0,0 +1,213 @@ + 511, DEC2BIN returns the #NUM! error + * value. + * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If DEC2BIN requires more than places characters, it returns the #NUM! + * error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, DEC2BIN uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If places is zero or negative, DEC2BIN returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toBinary($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateDecimal($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = (int) floor((float) $value); + if ($value > self::LARGEST_BINARY_IN_DECIMAL || $value < self::SMALLEST_BINARY_IN_DECIMAL) { + return ExcelError::NAN(); + } + + $r = decbin($value); + // Two's Complement + $r = substr($r, -10); + + return self::nbrConversionFormat($r, $places); + } + + /** + * toHex. + * + * Return a decimal value as hex. + * + * Excel Function: + * DEC2HEX(x[,places]) + * + * @param array|string $value The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2HEX returns a 10-character (40-bit) + * hexadecimal number in which the most significant bit is the sign + * bit. The remaining 39 bits are magnitude bits. Negative numbers + * are represented using two's-complement notation. + * If number < -549,755,813,888 or if number > 549,755,813,887, + * DEC2HEX returns the #NUM! error value. + * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If DEC2HEX requires more than places characters, it returns the + * #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, DEC2HEX uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If places is zero or negative, DEC2HEX returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toHex($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateDecimal($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = floor((float) $value); + if ($value > self::LARGEST_HEX_IN_DECIMAL || $value < self::SMALLEST_HEX_IN_DECIMAL) { + return ExcelError::NAN(); + } + $r = strtoupper(dechex((int) $value)); + $r = self::hex32bit($value, $r); + + return self::nbrConversionFormat($r, $places); + } + + public static function hex32bit(float $value, string $hexstr, bool $force = false): string + { + if (PHP_INT_SIZE === 4 || $force) { + if ($value >= 2 ** 32) { + $quotient = (int) ($value / (2 ** 32)); + + return strtoupper(substr('0' . dechex($quotient), -2) . $hexstr); + } + if ($value < -(2 ** 32)) { + $quotient = 256 - (int) ceil((-$value) / (2 ** 32)); + + return strtoupper(substr('0' . dechex($quotient), -2) . substr("00000000$hexstr", -8)); + } + if ($value < 0) { + return "FF$hexstr"; + } + } + + return $hexstr; + } + + /** + * toOctal. + * + * Return an decimal value as octal. + * + * Excel Function: + * DEC2OCT(x[,places]) + * + * @param array|string $value The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2OCT returns a 10-character (30-bit) + * octal number in which the most significant bit is the sign bit. + * The remaining 29 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -536,870,912 or if number > 536,870,911, DEC2OCT + * returns the #NUM! error value. + * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If DEC2OCT requires more than places characters, it returns the + * #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, DEC2OCT uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If places is zero or negative, DEC2OCT returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toOctal($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateDecimal($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + $value = (int) floor((float) $value); + if ($value > self::LARGEST_OCTAL_IN_DECIMAL || $value < self::SMALLEST_OCTAL_IN_DECIMAL) { + return ExcelError::NAN(); + } + $r = decoct($value); + $r = substr($r, -10); + + return self::nbrConversionFormat($r, $places); + } + + protected static function validateDecimal(string $value): string + { + if (strlen($value) > preg_match_all('/[-0123456789.]/', $value)) { + throw new Exception(ExcelError::VALUE()); + } + + return $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php new file mode 100644 index 00000000..55ce209e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertHex.php @@ -0,0 +1,175 @@ +getMessage(); + } + + $dec = self::toDecimal($value); + + return ConvertDecimal::toBinary($dec, $places); + } + + /** + * toDecimal. + * + * Return a hex value as decimal. + * + * Excel Function: + * HEX2DEC(x) + * + * @param array|string $value The hexadecimal number you want to convert. This number cannot + * contain more than 10 characters (40 bits). The most significant + * bit of number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is not a valid hexadecimal number, HEX2DEC returns the + * #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toDecimal($value) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + try { + $value = self::validateValue($value); + $value = self::validateHex($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (strlen($value) > 10) { + return ExcelError::NAN(); + } + + $binX = ''; + foreach (str_split($value) as $char) { + $binX .= str_pad(base_convert($char, 16, 2), 4, '0', STR_PAD_LEFT); + } + if (strlen($binX) == 40 && $binX[0] == '1') { + for ($i = 0; $i < 40; ++$i) { + $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); + } + + return (string) ((bindec($binX) + 1) * -1); + } + + return (string) bindec($binX); + } + + /** + * toOctal. + * + * Return a hex value as octal. + * + * Excel Function: + * HEX2OCT(x[,places]) + * + * @param array|string $value The hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is negative, HEX2OCT ignores places and returns a + * 10-character octal number. + * If number is negative, it cannot be less than FFE0000000, and + * if number is positive, it cannot be greater than 1FFFFFFF. + * If number is not a valid hexadecimal number, HEX2OCT returns + * the #NUM! error value. + * If HEX2OCT requires more than places characters, it returns + * the #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, HEX2OCT + * uses the minimum number of characters necessary. Places is + * useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2OCT returns the #VALUE! error + * value. + * If places is negative, HEX2OCT returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toOctal($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateHex($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + $decimal = self::toDecimal($value); + + return ConvertDecimal::toOctal($decimal, $places); + } + + protected static function validateHex(string $value): string + { + if (strlen($value) > preg_match_all('/[0123456789ABCDEF]/', $value)) { + throw new Exception(ExcelError::NAN()); + } + + return $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php new file mode 100644 index 00000000..add7aba0 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertOctal.php @@ -0,0 +1,174 @@ +getMessage(); + } + + return ConvertDecimal::toBinary(self::toDecimal($value), $places); + } + + /** + * toDecimal. + * + * Return an octal value as decimal. + * + * Excel Function: + * OCT2DEC(x) + * + * @param array|string $value The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is not a valid octal number, OCT2DEC returns the + * #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toDecimal($value) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + try { + $value = self::validateValue($value); + $value = self::validateOctal($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + $binX = ''; + foreach (str_split($value) as $char) { + $binX .= str_pad(decbin((int) $char), 3, '0', STR_PAD_LEFT); + } + if (strlen($binX) == 30 && $binX[0] == '1') { + for ($i = 0; $i < 30; ++$i) { + $binX[$i] = ($binX[$i] == '1' ? '0' : '1'); + } + + return (string) ((bindec($binX) + 1) * -1); + } + + return (string) bindec($binX); + } + + /** + * toHex. + * + * Return an octal value as hex. + * + * Excel Function: + * OCT2HEX(x[,places]) + * + * @param array|string $value The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is negative, OCT2HEX ignores places and returns a + * 10-character hexadecimal number. + * If number is not a valid octal number, OCT2HEX returns the + * #NUM! error value. + * If OCT2HEX requires more than places characters, it returns + * the #NUM! error value. + * Or can be an array of values + * @param array|int $places The number of characters to use. If places is omitted, OCT2HEX + * uses the minimum number of characters necessary. Places is useful + * for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. + * If places is negative, OCT2HEX returns the #NUM! error value. + * Or can be an array of values + * + * @return array|string Result, or an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toHex($value, $places = null) + { + if (is_array($value) || is_array($places)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $places); + } + + try { + $value = self::validateValue($value); + $value = self::validateOctal($value); + $places = self::validatePlaces($places); + } catch (Exception $e) { + return $e->getMessage(); + } + + $hexVal = strtoupper(dechex((int) self::toDecimal($value))); + $hexVal = (PHP_INT_SIZE === 4 && strlen($value) === 10 && $value[0] >= '4') ? "FF{$hexVal}" : $hexVal; + + return self::nbrConversionFormat($hexVal, $places); + } + + protected static function validateOctal(string $value): string + { + $numDigits = (int) preg_match_all('/[01234567]/', $value); + if (strlen($value) > $numDigits || $numDigits > 10) { + throw new Exception(ExcelError::NAN()); + } + + return $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php new file mode 100644 index 00000000..677fb0fb --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ConvertUOM.php @@ -0,0 +1,693 @@ + ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Gram', 'AllowPrefix' => true], + 'sg' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Slug', 'AllowPrefix' => false], + 'lbm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false], + 'u' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true], + 'ozm' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false], + 'grain' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Grain', 'AllowPrefix' => false], + 'cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], + 'shweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'U.S. (short) hundredweight', 'AllowPrefix' => false], + 'uk_cwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'lcwt' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'hweight' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial hundredweight', 'AllowPrefix' => false], + 'stone' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Stone', 'AllowPrefix' => false], + 'ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Ton', 'AllowPrefix' => false], + 'uk_ton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + 'LTON' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + 'brton' => ['Group' => self::CATEGORY_WEIGHT_AND_MASS, 'Unit Name' => 'Imperial ton', 'AllowPrefix' => false], + // Distance + 'm' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Meter', 'AllowPrefix' => true], + 'mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Statute mile', 'AllowPrefix' => false], + 'Nmi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false], + 'in' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Inch', 'AllowPrefix' => false], + 'ft' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Foot', 'AllowPrefix' => false], + 'yd' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Yard', 'AllowPrefix' => false], + 'ang' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Angstrom', 'AllowPrefix' => true], + 'ell' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Ell', 'AllowPrefix' => false], + 'ly' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Light Year', 'AllowPrefix' => false], + 'parsec' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], + 'pc' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Parsec', 'AllowPrefix' => false], + 'Pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], + 'Picapt' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false], + 'pica' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'Pica (1/6 in)', 'AllowPrefix' => false], + 'survey_mi' => ['Group' => self::CATEGORY_DISTANCE, 'Unit Name' => 'U.S survey mile (statute mile)', 'AllowPrefix' => false], + // Time + 'yr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Year', 'AllowPrefix' => false], + 'day' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], + 'd' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Day', 'AllowPrefix' => false], + 'hr' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Hour', 'AllowPrefix' => false], + 'mn' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], + 'min' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Minute', 'AllowPrefix' => false], + 'sec' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], + 's' => ['Group' => self::CATEGORY_TIME, 'Unit Name' => 'Second', 'AllowPrefix' => true], + // Pressure + 'Pa' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'p' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Pascal', 'AllowPrefix' => true], + 'atm' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'at' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true], + 'mmHg' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true], + 'psi' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'PSI', 'AllowPrefix' => true], + 'Torr' => ['Group' => self::CATEGORY_PRESSURE, 'Unit Name' => 'Torr', 'AllowPrefix' => true], + // Force + 'N' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Newton', 'AllowPrefix' => true], + 'dyn' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'dy' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Dyne', 'AllowPrefix' => true], + 'lbf' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pound force', 'AllowPrefix' => false], + 'pond' => ['Group' => self::CATEGORY_FORCE, 'Unit Name' => 'Pond', 'AllowPrefix' => true], + // Energy + 'J' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Joule', 'AllowPrefix' => true], + 'e' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Erg', 'AllowPrefix' => true], + 'c' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true], + 'cal' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'IT calorie', 'AllowPrefix' => true], + 'eV' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'ev' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Electron volt', 'AllowPrefix' => true], + 'HPh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'hh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false], + 'Wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'wh' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true], + 'flb' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false], + 'BTU' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], + 'btu' => ['Group' => self::CATEGORY_ENERGY, 'Unit Name' => 'BTU', 'AllowPrefix' => false], + // Power + 'HP' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'h' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Horsepower', 'AllowPrefix' => false], + 'W' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'w' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Watt', 'AllowPrefix' => true], + 'PS' => ['Group' => self::CATEGORY_POWER, 'Unit Name' => 'Pferdestärke', 'AllowPrefix' => false], + 'T' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Tesla', 'AllowPrefix' => true], + 'ga' => ['Group' => self::CATEGORY_MAGNETISM, 'Unit Name' => 'Gauss', 'AllowPrefix' => true], + // Temperature + 'C' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], + 'cel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Celsius', 'AllowPrefix' => false], + 'F' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], + 'fah' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Fahrenheit', 'AllowPrefix' => false], + 'K' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'kel' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Kelvin', 'AllowPrefix' => false], + 'Rank' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Rankine', 'AllowPrefix' => false], + 'Reau' => ['Group' => self::CATEGORY_TEMPERATURE, 'Unit Name' => 'Degrees Réaumur', 'AllowPrefix' => false], + // Volume + 'l' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'L' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'lt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Litre', 'AllowPrefix' => true], + 'tsp' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false], + 'tspm' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Modern Teaspoon', 'AllowPrefix' => false], + 'tbs' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false], + 'oz' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false], + 'cup' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cup', 'AllowPrefix' => false], + 'pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'us_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false], + 'uk_pt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false], + 'qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Quart', 'AllowPrefix' => false], + 'uk_qt' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Quart (UK)', 'AllowPrefix' => false], + 'gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gallon', 'AllowPrefix' => false], + 'uk_gal' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Imperial Gallon (UK)', 'AllowPrefix' => false], + 'ang3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], + 'ang^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Angstrom', 'AllowPrefix' => true], + 'barrel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Oil Barrel', 'AllowPrefix' => false], + 'bushel' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'US Bushel', 'AllowPrefix' => false], + 'in3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], + 'in^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Inch', 'AllowPrefix' => false], + 'ft3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], + 'ft^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Foot', 'AllowPrefix' => false], + 'ly3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], + 'ly^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Light Year', 'AllowPrefix' => false], + 'm3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], + 'm^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Meter', 'AllowPrefix' => true], + 'mi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], + 'mi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Mile', 'AllowPrefix' => false], + 'yd3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], + 'yd^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Yard', 'AllowPrefix' => false], + 'Nmi3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], + 'Nmi^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Nautical Mile', 'AllowPrefix' => false], + 'Pica3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Pica^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Picapt3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'Picapt^3' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Cubic Pica', 'AllowPrefix' => false], + 'GRT' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], + 'regton' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Gross Registered Ton', 'AllowPrefix' => false], + 'MTON' => ['Group' => self::CATEGORY_VOLUME, 'Unit Name' => 'Measurement Ton (Freight Ton)', 'AllowPrefix' => false], + // Area + 'ha' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Hectare', 'AllowPrefix' => true], + 'uk_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'International Acre', 'AllowPrefix' => false], + 'us_acre' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'US Survey/Statute Acre', 'AllowPrefix' => false], + 'ang2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], + 'ang^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Angstrom', 'AllowPrefix' => true], + 'ar' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Are', 'AllowPrefix' => true], + 'ft2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], + 'ft^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Feet', 'AllowPrefix' => false], + 'in2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], + 'in^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Inches', 'AllowPrefix' => false], + 'ly2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], + 'ly^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Light Years', 'AllowPrefix' => false], + 'm2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], + 'm^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Meters', 'AllowPrefix' => true], + 'Morgen' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Morgen', 'AllowPrefix' => false], + 'mi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], + 'mi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Miles', 'AllowPrefix' => false], + 'Nmi2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], + 'Nmi^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Nautical Miles', 'AllowPrefix' => false], + 'Pica2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Pica^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Picapt2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'Picapt^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Pica', 'AllowPrefix' => false], + 'yd2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], + 'yd^2' => ['Group' => self::CATEGORY_AREA, 'Unit Name' => 'Square Yards', 'AllowPrefix' => false], + // Information + 'byte' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Byte', 'AllowPrefix' => true], + 'bit' => ['Group' => self::CATEGORY_INFORMATION, 'Unit Name' => 'Bit', 'AllowPrefix' => true], + // Speed + 'm/s' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], + 'm/sec' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per second', 'AllowPrefix' => true], + 'm/h' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], + 'm/hr' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Meters per hour', 'AllowPrefix' => true], + 'mph' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Miles per hour', 'AllowPrefix' => false], + 'admkn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Admiralty Knot', 'AllowPrefix' => false], + 'kn' => ['Group' => self::CATEGORY_SPEED, 'Unit Name' => 'Knot', 'AllowPrefix' => false], + ]; + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @var mixed[] + */ + private static $conversionMultipliers = [ + 'Y' => ['multiplier' => 1E24, 'name' => 'yotta'], + 'Z' => ['multiplier' => 1E21, 'name' => 'zetta'], + 'E' => ['multiplier' => 1E18, 'name' => 'exa'], + 'P' => ['multiplier' => 1E15, 'name' => 'peta'], + 'T' => ['multiplier' => 1E12, 'name' => 'tera'], + 'G' => ['multiplier' => 1E9, 'name' => 'giga'], + 'M' => ['multiplier' => 1E6, 'name' => 'mega'], + 'k' => ['multiplier' => 1E3, 'name' => 'kilo'], + 'h' => ['multiplier' => 1E2, 'name' => 'hecto'], + 'e' => ['multiplier' => 1E1, 'name' => 'dekao'], + 'da' => ['multiplier' => 1E1, 'name' => 'dekao'], + 'd' => ['multiplier' => 1E-1, 'name' => 'deci'], + 'c' => ['multiplier' => 1E-2, 'name' => 'centi'], + 'm' => ['multiplier' => 1E-3, 'name' => 'milli'], + 'u' => ['multiplier' => 1E-6, 'name' => 'micro'], + 'n' => ['multiplier' => 1E-9, 'name' => 'nano'], + 'p' => ['multiplier' => 1E-12, 'name' => 'pico'], + 'f' => ['multiplier' => 1E-15, 'name' => 'femto'], + 'a' => ['multiplier' => 1E-18, 'name' => 'atto'], + 'z' => ['multiplier' => 1E-21, 'name' => 'zepto'], + 'y' => ['multiplier' => 1E-24, 'name' => 'yocto'], + ]; + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @var mixed[] + */ + private static $binaryConversionMultipliers = [ + 'Yi' => ['multiplier' => 2 ** 80, 'name' => 'yobi'], + 'Zi' => ['multiplier' => 2 ** 70, 'name' => 'zebi'], + 'Ei' => ['multiplier' => 2 ** 60, 'name' => 'exbi'], + 'Pi' => ['multiplier' => 2 ** 50, 'name' => 'pebi'], + 'Ti' => ['multiplier' => 2 ** 40, 'name' => 'tebi'], + 'Gi' => ['multiplier' => 2 ** 30, 'name' => 'gibi'], + 'Mi' => ['multiplier' => 2 ** 20, 'name' => 'mebi'], + 'ki' => ['multiplier' => 2 ** 10, 'name' => 'kibi'], + ]; + + /** + * Details of the Units of measure conversion factors, organised by group. + * + * @var mixed[] + */ + private static $unitConversions = [ + // Conversion uses gram (g) as an intermediate unit + self::CATEGORY_WEIGHT_AND_MASS => [ + 'g' => 1.0, + 'sg' => 6.85217658567918E-05, + 'lbm' => 2.20462262184878E-03, + 'u' => 6.02214179421676E+23, + 'ozm' => 3.52739619495804E-02, + 'grain' => 1.54323583529414E+01, + 'cwt' => 2.20462262184878E-05, + 'shweight' => 2.20462262184878E-05, + 'uk_cwt' => 1.96841305522212E-05, + 'lcwt' => 1.96841305522212E-05, + 'hweight' => 1.96841305522212E-05, + 'stone' => 1.57473044417770E-04, + 'ton' => 1.10231131092439E-06, + 'uk_ton' => 9.84206527611061E-07, + 'LTON' => 9.84206527611061E-07, + 'brton' => 9.84206527611061E-07, + ], + // Conversion uses meter (m) as an intermediate unit + self::CATEGORY_DISTANCE => [ + 'm' => 1.0, + 'mi' => 6.21371192237334E-04, + 'Nmi' => 5.39956803455724E-04, + 'in' => 3.93700787401575E+01, + 'ft' => 3.28083989501312E+00, + 'yd' => 1.09361329833771E+00, + 'ang' => 1.0E+10, + 'ell' => 8.74890638670166E-01, + 'ly' => 1.05700083402462E-16, + 'parsec' => 3.24077928966473E-17, + 'pc' => 3.24077928966473E-17, + 'Pica' => 2.83464566929134E+03, + 'Picapt' => 2.83464566929134E+03, + 'pica' => 2.36220472440945E+02, + 'survey_mi' => 6.21369949494950E-04, + ], + // Conversion uses second (s) as an intermediate unit + self::CATEGORY_TIME => [ + 'yr' => 3.16880878140289E-08, + 'day' => 1.15740740740741E-05, + 'd' => 1.15740740740741E-05, + 'hr' => 2.77777777777778E-04, + 'mn' => 1.66666666666667E-02, + 'min' => 1.66666666666667E-02, + 'sec' => 1.0, + 's' => 1.0, + ], + // Conversion uses Pascal (Pa) as an intermediate unit + self::CATEGORY_PRESSURE => [ + 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923266716013E-06, + 'at' => 9.86923266716013E-06, + 'mmHg' => 7.50063755419211E-03, + 'psi' => 1.45037737730209E-04, + 'Torr' => 7.50061682704170E-03, + ], + // Conversion uses Newton (N) as an intermediate unit + self::CATEGORY_FORCE => [ + 'N' => 1.0, + 'dyn' => 1.0E+5, + 'dy' => 1.0E+5, + 'lbf' => 2.24808923655339E-01, + 'pond' => 1.01971621297793E+02, + ], + // Conversion uses Joule (J) as an intermediate unit + self::CATEGORY_ENERGY => [ + 'J' => 1.0, + 'e' => 9.99999519343231E+06, + 'c' => 2.39006249473467E-01, + 'cal' => 2.38846190642017E-01, + 'eV' => 6.24145700000000E+18, + 'ev' => 6.24145700000000E+18, + 'HPh' => 3.72506430801000E-07, + 'hh' => 3.72506430801000E-07, + 'Wh' => 2.77777916238711E-04, + 'wh' => 2.77777916238711E-04, + 'flb' => 2.37304222192651E+01, + 'BTU' => 9.47815067349015E-04, + 'btu' => 9.47815067349015E-04, + ], + // Conversion uses Horsepower (HP) as an intermediate unit + self::CATEGORY_POWER => [ + 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45699871582270E+02, + 'w' => 7.45699871582270E+02, + 'PS' => 1.01386966542400E+00, + ], + // Conversion uses Tesla (T) as an intermediate unit + self::CATEGORY_MAGNETISM => [ + 'T' => 1.0, + 'ga' => 10000.0, + ], + // Conversion uses litre (l) as an intermediate unit + self::CATEGORY_VOLUME => [ + 'l' => 1.0, + 'L' => 1.0, + 'lt' => 1.0, + 'tsp' => 2.02884136211058E+02, + 'tspm' => 2.0E+02, + 'tbs' => 6.76280454036860E+01, + 'oz' => 3.38140227018430E+01, + 'cup' => 4.22675283773038E+00, + 'pt' => 2.11337641886519E+00, + 'us_pt' => 2.11337641886519E+00, + 'uk_pt' => 1.75975398639270E+00, + 'qt' => 1.05668820943259E+00, + 'uk_qt' => 8.79876993196351E-01, + 'gal' => 2.64172052358148E-01, + 'uk_gal' => 2.19969248299088E-01, + 'ang3' => 1.0E+27, + 'ang^3' => 1.0E+27, + 'barrel' => 6.28981077043211E-03, + 'bushel' => 2.83775932584017E-02, + 'in3' => 6.10237440947323E+01, + 'in^3' => 6.10237440947323E+01, + 'ft3' => 3.53146667214886E-02, + 'ft^3' => 3.53146667214886E-02, + 'ly3' => 1.18093498844171E-51, + 'ly^3' => 1.18093498844171E-51, + 'm3' => 1.0E-03, + 'm^3' => 1.0E-03, + 'mi3' => 2.39912758578928E-13, + 'mi^3' => 2.39912758578928E-13, + 'yd3' => 1.30795061931439E-03, + 'yd^3' => 1.30795061931439E-03, + 'Nmi3' => 1.57426214685811E-13, + 'Nmi^3' => 1.57426214685811E-13, + 'Pica3' => 2.27769904358706E+07, + 'Pica^3' => 2.27769904358706E+07, + 'Picapt3' => 2.27769904358706E+07, + 'Picapt^3' => 2.27769904358706E+07, + 'GRT' => 3.53146667214886E-04, + 'regton' => 3.53146667214886E-04, + 'MTON' => 8.82866668037215E-04, + ], + // Conversion uses hectare (ha) as an intermediate unit + self::CATEGORY_AREA => [ + 'ha' => 1.0, + 'uk_acre' => 2.47105381467165E+00, + 'us_acre' => 2.47104393046628E+00, + 'ang2' => 1.0E+24, + 'ang^2' => 1.0E+24, + 'ar' => 1.0E+02, + 'ft2' => 1.07639104167097E+05, + 'ft^2' => 1.07639104167097E+05, + 'in2' => 1.55000310000620E+07, + 'in^2' => 1.55000310000620E+07, + 'ly2' => 1.11725076312873E-28, + 'ly^2' => 1.11725076312873E-28, + 'm2' => 1.0E+04, + 'm^2' => 1.0E+04, + 'Morgen' => 4.0E+00, + 'mi2' => 3.86102158542446E-03, + 'mi^2' => 3.86102158542446E-03, + 'Nmi2' => 2.91553349598123E-03, + 'Nmi^2' => 2.91553349598123E-03, + 'Pica2' => 8.03521607043214E+10, + 'Pica^2' => 8.03521607043214E+10, + 'Picapt2' => 8.03521607043214E+10, + 'Picapt^2' => 8.03521607043214E+10, + 'yd2' => 1.19599004630108E+04, + 'yd^2' => 1.19599004630108E+04, + ], + // Conversion uses bit (bit) as an intermediate unit + self::CATEGORY_INFORMATION => [ + 'bit' => 1.0, + 'byte' => 0.125, + ], + // Conversion uses Meters per Second (m/s) as an intermediate unit + self::CATEGORY_SPEED => [ + 'm/s' => 1.0, + 'm/sec' => 1.0, + 'm/h' => 3.60E+03, + 'm/hr' => 3.60E+03, + 'mph' => 2.23693629205440E+00, + 'admkn' => 1.94260256941567E+00, + 'kn' => 1.94384449244060E+00, + ], + ]; + + /** + * getConversionGroups + * Returns a list of the different conversion groups for UOM conversions. + * + * @return array + */ + public static function getConversionCategories() + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit) { + $conversionGroups[] = $conversionUnit['Group']; + } + + return array_merge(array_unique($conversionGroups)); + } + + /** + * getConversionGroupUnits + * Returns an array of units of measure, for a specified conversion group, or for all groups. + * + * @param string $category The group whose units of measure you want to retrieve + * + * @return array + */ + public static function getConversionCategoryUnits($category = null) + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if (($category === null) || ($conversionGroup['Group'] == $category)) { + $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; + } + } + + return $conversionGroups; + } + + /** + * getConversionGroupUnitDetails. + * + * @param string $category The group whose units of measure you want to retrieve + * + * @return array + */ + public static function getConversionCategoryUnitDetails($category = null) + { + $conversionGroups = []; + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if (($category === null) || ($conversionGroup['Group'] == $category)) { + $conversionGroups[$conversionGroup['Group']][] = [ + 'unit' => $conversionUnit, + 'description' => $conversionGroup['Unit Name'], + ]; + } + } + + return $conversionGroups; + } + + /** + * getConversionMultipliers + * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM(). + * + * @return mixed[] + */ + public static function getConversionMultipliers() + { + return self::$conversionMultipliers; + } + + /** + * getBinaryConversionMultipliers + * Returns an array of the additional Multiplier prefixes that can be used with Information Units of Measure in CONVERTUOM(). + * + * @return mixed[] + */ + public static function getBinaryConversionMultipliers() + { + return self::$binaryConversionMultipliers; + } + + /** + * CONVERT. + * + * Converts a number from one measurement system to another. + * For example, CONVERT can translate a table of distances in miles to a table of distances + * in kilometers. + * + * Excel Function: + * CONVERT(value,fromUOM,toUOM) + * + * @param array|float|int|string $value the value in fromUOM to convert + * Or can be an array of values + * @param array|string $fromUOM the units for value + * Or can be an array of values + * @param array|string $toUOM the units for the result + * Or can be an array of values + * + * @return array|float|string Result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function CONVERT($value, $fromUOM, $toUOM) + { + if (is_array($value) || is_array($fromUOM) || is_array($toUOM)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $fromUOM, $toUOM); + } + + if (!is_numeric($value)) { + return ExcelError::VALUE(); + } + + try { + [$fromUOM, $fromCategory, $fromMultiplier] = self::getUOMDetails($fromUOM); + [$toUOM, $toCategory, $toMultiplier] = self::getUOMDetails($toUOM); + } catch (Exception $e) { + return ExcelError::NA(); + } + + if ($fromCategory !== $toCategory) { + return ExcelError::NA(); + } + + // @var float $value + $value *= $fromMultiplier; + + if (($fromUOM === $toUOM) && ($fromMultiplier === $toMultiplier)) { + // We've already factored $fromMultiplier into the value, so we need + // to reverse it again + return $value / $fromMultiplier; + } elseif ($fromUOM === $toUOM) { + return $value / $toMultiplier; + } elseif ($fromCategory === self::CATEGORY_TEMPERATURE) { + return self::convertTemperature($fromUOM, $toUOM, $value); + } + + $baseValue = $value * (1.0 / self::$unitConversions[$fromCategory][$fromUOM]); + + return ($baseValue * self::$unitConversions[$fromCategory][$toUOM]) / $toMultiplier; + } + + private static function getUOMDetails(string $uom) + { + if (isset(self::$conversionUnits[$uom])) { + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, 1.0]; + } + + // Check 1-character standard metric multiplier prefixes + $multiplierType = substr($uom, 0, 1); + $uom = substr($uom, 1); + if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; + } + + $multiplierType .= substr($uom, 0, 1); + $uom = substr($uom, 1); + + // Check 2-character standard metric multiplier prefixes + if (isset(self::$conversionUnits[$uom], self::$conversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + + return [$uom, $unitCategory, self::$conversionMultipliers[$multiplierType]['multiplier']]; + } + + // Check 2-character binary multiplier prefixes + if (isset(self::$conversionUnits[$uom], self::$binaryConversionMultipliers[$multiplierType])) { + if (self::$conversionUnits[$uom]['AllowPrefix'] === false) { + throw new Exception('Prefix not allowed for UoM'); + } + $unitCategory = self::$conversionUnits[$uom]['Group']; + if ($unitCategory !== 'Information') { + throw new Exception('Binary Prefix is only allowed for Information UoM'); + } + + return [$uom, $unitCategory, self::$binaryConversionMultipliers[$multiplierType]['multiplier']]; + } + + throw new Exception('UoM Not Found'); + } + + /** + * @param float|int $value + * + * @return float|int + */ + protected static function convertTemperature(string $fromUOM, string $toUOM, $value) + { + $fromUOM = self::resolveTemperatureSynonyms($fromUOM); + $toUOM = self::resolveTemperatureSynonyms($toUOM); + + if ($fromUOM === $toUOM) { + return $value; + } + + // Convert to Kelvin + switch ($fromUOM) { + case 'F': + $value = ($value - 32) / 1.8 + 273.15; + + break; + case 'C': + $value += 273.15; + + break; + case 'Rank': + $value /= 1.8; + + break; + case 'Reau': + $value = $value * 1.25 + 273.15; + + break; + } + + // Convert from Kelvin + switch ($toUOM) { + case 'F': + $value = ($value - 273.15) * 1.8 + 32.00; + + break; + case 'C': + $value -= 273.15; + + break; + case 'Rank': + $value *= 1.8; + + break; + case 'Reau': + $value = ($value - 273.15) * 0.80000; + + break; + } + + return $value; + } + + private static function resolveTemperatureSynonyms(string $uom) + { + switch ($uom) { + case 'fah': + return 'F'; + case 'cel': + return 'C'; + case 'kel': + return 'K'; + } + + return $uom; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php new file mode 100644 index 00000000..c0202ea2 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/EngineeringValidations.php @@ -0,0 +1,33 @@ + 2.2) { + return 1 - ErfC::ERFC($value); + } + $sum = $term = $value; + $xsqr = ($value * $value); + $j = 1; + do { + $term *= $xsqr / $j; + $sum -= $term / (2 * $j + 1); + ++$j; + $term *= $xsqr / $j; + $sum += $term / (2 * $j + 1); + ++$j; + if ($sum == 0.0) { + break; + } + } while (abs($term / $sum) > Functions::PRECISION); + + return self::$twoSqrtPi * $sum; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php new file mode 100644 index 00000000..7b023bee --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Engineering/ErfC.php @@ -0,0 +1,77 @@ + Functions::PRECISION); + + return self::$oneSqrtPi * exp(-$value * $value) * $q2; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Exception.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Exception.php index fccf0af7..87c7d222 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Exception.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Exception.php @@ -15,7 +15,7 @@ class Exception extends PhpSpreadsheetException * @param mixed $line * @param mixed $context */ - public static function errorHandlerCallback($code, $string, $file, $line, $context) + public static function errorHandlerCallback($code, $string, $file, $line, $context): void { $e = new self($string, $code); $e->line = $line; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php index 412b7a62..4215a516 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial.php @@ -2,177 +2,81 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Date; - +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Amortization; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Coupons; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Depreciation; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Dollar; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\InterestRate; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities; +use PhpOffice\PhpSpreadsheet\Calculation\Financial\TreasuryBill; + +/** + * @deprecated 1.18.0 + */ class Financial { - const FINANCIAL_MAX_ITERATIONS = 32; + const FINANCIAL_MAX_ITERATIONS = 128; const FINANCIAL_PRECISION = 1.0e-08; - /** - * isLastDayOfMonth. - * - * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month - * - * @param \DateTime $testDate The date for testing - * - * @return bool - */ - private static function isLastDayOfMonth(\DateTime $testDate) - { - return $testDate->format('d') == $testDate->format('t'); - } - - private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next) - { - $months = 12 / $frequency; - - $result = Date::excelToDateTimeObject($maturity); - $eom = self::isLastDayOfMonth($result); - - while ($settlement < Date::PHPToExcel($result)) { - $result->modify('-' . $months . ' months'); - } - if ($next) { - $result->modify('+' . $months . ' months'); - } - - if ($eom) { - $result->modify('-1 day'); - } - - return Date::PHPToExcel($result); - } - - private static function isValidFrequency($frequency) - { - if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) { - return true; - } - if ((Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) && - (($frequency == 6) || ($frequency == 12))) { - return true; - } - - return false; - } - - /** - * daysPerYear. - * - * Returns the number of days in a specified year, as defined by the "basis" value - * - * @param int|string $year The year against which we're testing - * @param int|string $basis The type of day count: - * 0 or omitted US (NASD) 360 - * 1 Actual (365 or 366 in a leap year) - * 2 360 - * 3 365 - * 4 European 360 - * - * @return int|string Result, or a string containing an error - */ - private static function daysPerYear($year, $basis = 0) - { - switch ($basis) { - case 0: - case 2: - case 4: - $daysPerYear = 360; - - break; - case 3: - $daysPerYear = 365; - - break; - case 1: - $daysPerYear = (DateTime::isLeapYear($year)) ? 366 : 365; - - break; - default: - return Functions::NAN(); - } - - return $daysPerYear; - } - - private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) - { - $pmt = self::PMT($rate, $nper, $pv, $fv, $type); - $capital = $pv; - for ($i = 1; $i <= $per; ++$i) { - $interest = ($type && $i == 1) ? 0 : -$capital * $rate; - $principal = $pmt - $interest; - $capital += $principal; - } - - return [$interest, $principal]; - } - /** * ACCRINT. * * Returns the accrued interest for a security that pays periodic interest. * * Excel Function: - * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis]) + * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis][,calc_method]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Securities\AccruedInterest::periodic() + * Use the periodic() method in the Financial\Securities\AccruedInterest class instead * * @param mixed $issue the security's issue date - * @param mixed $firstinterest the security's first interest date + * @param mixed $firstInterest the security's first interest date * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date - * when the security is traded to the buyer. - * @param float $rate the security's annual coupon rate - * @param float $par The security's par value. - * If you omit par, ACCRINT uses $1,000. - * @param int $frequency the number of coupon payments per year. - * Valid frequency values are: - * 1 Annual - * 2 Semi-Annual - * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * The security settlement date is the date after the issue date + * when the security is traded to the buyer. + * @param mixed $rate the security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @param mixed $calcMethod + * If true, use Issue to Settlement + * If false, use FirstInterest to Settlement * * @return float|string Result, or a string containing an error */ - public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0) - { - $issue = Functions::flattenSingleValue($issue); - $firstinterest = Functions::flattenSingleValue($firstinterest); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par); - $frequency = ($frequency === null) ? 1 : Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; - if (($rate <= 0) || ($par <= 0)) { - return Functions::NAN(); - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - - return $par * $rate * $daysBetweenIssueAndSettlement; - } - - return Functions::VALUE(); + public static function ACCRINT( + $issue, + $firstInterest, + $settlement, + $rate, + $parValue = 1000, + $frequency = 1, + $basis = 0, + $calcMethod = true + ) { + return Securities\AccruedInterest::periodic( + $issue, + $firstInterest, + $settlement, + $rate, + $parValue, + $frequency, + $basis, + $calcMethod + ); } /** @@ -183,47 +87,28 @@ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par * Excel Function: * ACCRINTM(issue,settlement,rate[,par[,basis]]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Securities\AccruedInterest::atMaturity() + * Use the atMaturity() method in the Financial\Securities\AccruedInterest class instead * * @param mixed $issue The security's issue date * @param mixed $settlement The security's settlement (or maturity) date - * @param float $rate The security's annual coupon rate - * @param float $par The security's par value. - * If you omit par, ACCRINT uses $1,000. - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * @param mixed $rate The security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ - public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0) + public static function ACCRINTM($issue, $settlement, $rate, $parValue = 1000, $basis = 0) { - $issue = Functions::flattenSingleValue($issue); - $settlement = Functions::flattenSingleValue($settlement); - $rate = Functions::flattenSingleValue($rate); - $par = ($par === null) ? 1000 : Functions::flattenSingleValue($par); - $basis = ($basis === null) ? 0 : Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($rate)) && (is_numeric($par))) { - $rate = (float) $rate; - $par = (float) $par; - if (($rate <= 0) || ($par <= 0)) { - return Functions::NAN(); - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - - return $par * $rate * $daysBetweenIssueAndSettlement; - } - - return Functions::VALUE(); + return Securities\AccruedInterest::atMaturity($issue, $settlement, $rate, $parValue, $basis); } /** @@ -241,7 +126,10 @@ public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis * Excel Function: * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Amortization::AMORDEGRC() + * Use the AMORDEGRC() method in the Financial\Amortization class instead * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset @@ -250,63 +138,17 @@ public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * - * @return float + * @return float|string (string containing the error type if there is an error) */ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); - $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = floor(Functions::flattenSingleValue($period)); - $rate = Functions::flattenSingleValue($rate); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - // The depreciation coefficients are: - // Life of assets (1/rate) Depreciation coefficient - // Less than 3 years 1 - // Between 3 and 4 years 1.5 - // Between 5 and 6 years 2 - // More than 6 years 2.5 - $fUsePer = 1.0 / $rate; - if ($fUsePer < 3.0) { - $amortiseCoeff = 1.0; - } elseif ($fUsePer < 5.0) { - $amortiseCoeff = 1.5; - } elseif ($fUsePer <= 6.0) { - $amortiseCoeff = 2.0; - } else { - $amortiseCoeff = 2.5; - } - - $rate *= $amortiseCoeff; - $fNRate = round(DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost, 0); - $cost -= $fNRate; - $fRest = $cost - $salvage; - - for ($n = 0; $n < $period; ++$n) { - $fNRate = round($rate * $cost, 0); - $fRest -= $fNRate; - - if ($fRest < 0.0) { - switch ($period - $n) { - case 0: - case 1: - return round($cost * 0.5, 0); - default: - return 0.0; - } - } - $cost -= $fNRate; - } - - return $fNRate; + return Amortization::AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** @@ -319,7 +161,10 @@ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $per * Excel Function: * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Amortization::AMORLINC() + * Use the AMORLINC() method in the Financial\Amortization class instead * * @param float $cost The cost of the asset * @param mixed $purchased Date of the purchase of the asset @@ -328,46 +173,17 @@ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $per * @param float $period The period * @param float $rate Rate of depreciation * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * - * @return float + * @return float|string (string containing the error type if there is an error) */ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) { - $cost = Functions::flattenSingleValue($cost); - $purchased = Functions::flattenSingleValue($purchased); - $firstPeriod = Functions::flattenSingleValue($firstPeriod); - $salvage = Functions::flattenSingleValue($salvage); - $period = Functions::flattenSingleValue($period); - $rate = Functions::flattenSingleValue($rate); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - $fOneRate = $cost * $rate; - $fCostDelta = $cost - $salvage; - // Note, quirky variation for leap years on the YEARFRAC for this function - $purchasedYear = DateTime::YEAR($purchased); - $yearFrac = DateTime::YEARFRAC($purchased, $firstPeriod, $basis); - - if (($basis == 1) && ($yearFrac < 1) && (DateTime::isLeapYear($purchasedYear))) { - $yearFrac *= 365 / 366; - } - - $f0Rate = $yearFrac * $rate * $cost; - $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); - - if ($period == 0) { - return $f0Rate; - } elseif ($period <= $nNumOfFullPeriods) { - return $fOneRate; - } elseif ($period == ($nNumOfFullPeriods + 1)) { - return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; - } - - return 0.0; + return Amortization::AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis); } /** @@ -378,7 +194,10 @@ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $peri * Excel Function: * COUPDAYBS(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYBS() + * Use the COUPDAYBS() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -390,10 +209,6 @@ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $peri * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -405,28 +220,7 @@ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $peri */ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); - - return DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear; + return Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); } /** @@ -437,7 +231,10 @@ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) * Excel Function: * COUPDAYS(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYS() + * Use the COUPDAYS() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -449,10 +246,6 @@ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -464,43 +257,7 @@ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) */ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - switch ($basis) { - case 3: - // Actual/365 - return 365 / $frequency; - case 1: - // Actual/actual - if ($frequency == 1) { - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - - return $daysPerYear / $frequency; - } - $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); - $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); - - return $next - $prev; - default: - // US (NASD) 30/360, Actual/360 or European 30/360 - return 360 / $frequency; - } + return Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); } /** @@ -511,7 +268,10 @@ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) * Excel Function: * COUPDAYSNC(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPDAYSNC() + * Use the COUPDAYSNC() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -523,10 +283,6 @@ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -538,28 +294,7 @@ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) */ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); - - return DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear; + return Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); } /** @@ -570,7 +305,10 @@ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0 * Excel Function: * COUPNCD(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPNCD() + * Use the COUPNCD() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -582,10 +320,6 @@ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0 * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -598,25 +332,7 @@ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0 */ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + return Coupons::COUPNCD($settlement, $maturity, $frequency, $basis); } /** @@ -628,7 +344,10 @@ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) * Excel Function: * COUPNUM(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPNUM() + * Use the COUPNUM() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -640,10 +359,6 @@ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -655,37 +370,7 @@ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) */ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis) * $daysPerYear; - - switch ($frequency) { - case 1: // annual payments - case 2: // half-yearly - case 4: // quarterly - case 6: // bimonthly - case 12: // monthly - return ceil($daysBetweenSettlementAndMaturity / $daysPerYear * $frequency); - } - - return Functions::VALUE(); + return Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); } /** @@ -696,7 +381,10 @@ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) * Excel Function: * COUPPCD(settlement,maturity,frequency[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Coupons::COUPPCD() + * Use the COUPPCD() method in the Financial\Coupons class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -708,10 +396,6 @@ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) * 1 Annual * 2 Semi-Annual * 4 Quarterly - * If working in Gnumeric Mode, the following frequency options are - * also available - * 6 Bimonthly - * 12 Monthly * @param int $basis The type of day count to use. * 0 or omitted US (NASD) 30/360 * 1 Actual/actual @@ -724,25 +408,7 @@ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) */ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement >= $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); + return Coupons::COUPPCD($settlement, $maturity, $frequency, $basis); } /** @@ -753,44 +419,26 @@ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) * Excel Function: * CUMIPMT(rate,nper,pv,start,end[,type]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Cumulative::interest() + * Use the interest() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. - * Payment periods are numbered beginning with 1. + * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: - * 0 or omitted At the end of the period. - * 1 At the beginning of the period. + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. * * @return float|string */ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($start < 1 || $start > $end) { - return Functions::VALUE(); - } - - // Calculate - $interest = 0; - for ($per = $start; $per <= $end; ++$per) { - $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type); - } - - return $interest; + return Financial\CashFlow\Constant\Periodic\Cumulative::interest($rate, $nper, $pv, $start, $end, $type); } /** @@ -801,44 +449,26 @@ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) * Excel Function: * CUMPRINC(rate,nper,pv,start,end[,type]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Cumulative::principal() + * Use the principal() method in the Financial\CashFlow\Constant\Periodic\Cumulative class instead * * @param float $rate The Interest rate * @param int $nper The total number of payment periods * @param float $pv Present Value * @param int $start The first period in the calculation. - * Payment periods are numbered beginning with 1. + * Payment periods are numbered beginning with 1. * @param int $end the last period in the calculation * @param int $type A number 0 or 1 and indicates when payments are due: - * 0 or omitted At the end of the period. - * 1 At the beginning of the period. + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. * * @return float|string */ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $start = (int) Functions::flattenSingleValue($start); - $end = (int) Functions::flattenSingleValue($end); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($start < 1 || $start > $end) { - return Functions::VALUE(); - } - - // Calculate - $principal = 0; - for ($per = $start; $per <= $end; ++$per) { - $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type); - } - - return $principal; + return Financial\CashFlow\Constant\Periodic\Cumulative::principal($rate, $nper, $pv, $start, $end, $type); } /** @@ -854,7 +484,10 @@ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) * Excel Function: * DB(cost,salvage,life,period[,month]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::DB() + * Use the DB() method in the Financial\Depreciation class instead * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. @@ -870,48 +503,7 @@ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) */ public static function DB($cost, $salvage, $life, $period, $month = 12) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $month = Functions::flattenSingleValue($month); - - // Validate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) { - $cost = (float) $cost; - $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $month = (int) $month; - if ($cost == 0) { - return 0.0; - } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) { - return Functions::NAN(); - } - // Set Fixed Depreciation Rate - $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); - $fixedDepreciationRate = round($fixedDepreciationRate, 3); - - // Loop through each period calculating the depreciation - $previousDepreciation = 0; - for ($per = 1; $per <= $period; ++$per) { - if ($per == 1) { - $depreciation = $cost * $fixedDepreciationRate * $month / 12; - } elseif ($per == ($life + 1)) { - $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; - } else { - $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; - } - $previousDepreciation += $depreciation; - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $depreciation = round($depreciation, 2); - } - - return $depreciation; - } - - return Functions::VALUE(); + return Depreciation::DB($cost, $salvage, $life, $period, $month); } /** @@ -923,7 +515,10 @@ public static function DB($cost, $salvage, $life, $period, $month = 12) * Excel Function: * DDB(cost,salvage,life,period[,factor]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::DDB() + * Use the DDB() method in the Financial\Depreciation class instead * * @param float $cost Initial cost of the asset * @param float $salvage Value at the end of the depreciation. @@ -940,40 +535,7 @@ public static function DB($cost, $salvage, $life, $period, $month = 12) */ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - $factor = Functions::flattenSingleValue($factor); - - // Validate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) { - $cost = (float) $cost; - $salvage = (float) $salvage; - $life = (int) $life; - $period = (int) $period; - $factor = (float) $factor; - if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) { - return Functions::NAN(); - } - // Set Fixed Depreciation Rate - $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); - $fixedDepreciationRate = round($fixedDepreciationRate, 3); - - // Loop through each period calculating the depreciation - $previousDepreciation = 0; - for ($per = 1; $per <= $period; ++$per) { - $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation)); - $previousDepreciation += $depreciation; - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - $depreciation = round($depreciation, 2); - } - - return $depreciation; - } - - return Functions::VALUE(); + return Depreciation::DDB($cost, $salvage, $life, $period, $factor); } /** @@ -984,7 +546,10 @@ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) * Excel Function: * DISC(settlement,maturity,price,redemption[,basis]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Rates::discount() + * Use the discount() method in the Financial\Securities\Rates class instead * * @param mixed $settlement The security's settlement date. * The security settlement date is the date after the issue @@ -1004,30 +569,7 @@ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) */ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $price = (float) $price; - $redemption = (float) $redemption; - $basis = (int) $basis; - if (($price <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; - } - - return Functions::VALUE(); + return Financial\Securities\Rates::discount($settlement, $maturity, $price, $redemption, $basis); } /** @@ -1040,32 +582,19 @@ public static function DISC($settlement, $maturity, $price, $redemption, $basis * Excel Function: * DOLLARDE(fractional_dollar,fraction) * - * @category Financial Functions + * @Deprecated 1.18.0 * - * @param float $fractional_dollar Fractional Dollar - * @param int $fraction Fraction + * @see Financial\Dollar::decimal() + * Use the decimal() method in the Financial\Dollar class instead * - * @return float|string + * @param array|float $fractional_dollar Fractional Dollar + * @param array|int $fraction Fraction + * + * @return array|float|string */ public static function DOLLARDE($fractional_dollar = null, $fraction = 0) { - $fractional_dollar = Functions::flattenSingleValue($fractional_dollar); - $fraction = (int) Functions::flattenSingleValue($fraction); - - // Validate parameters - if ($fractional_dollar === null || $fraction < 0) { - return Functions::NAN(); - } - if ($fraction == 0) { - return Functions::DIV0(); - } - - $dollars = floor($fractional_dollar); - $cents = fmod($fractional_dollar, 1); - $cents /= $fraction; - $cents *= pow(10, ceil(log10($fraction))); - - return $dollars + $cents; + return Dollar::decimal($fractional_dollar, $fraction); } /** @@ -1078,32 +607,19 @@ public static function DOLLARDE($fractional_dollar = null, $fraction = 0) * Excel Function: * DOLLARFR(decimal_dollar,fraction) * - * @category Financial Functions + * @Deprecated 1.18.0 * - * @param float $decimal_dollar Decimal Dollar - * @param int $fraction Fraction + * @see Financial\Dollar::fractional() + * Use the fractional() method in the Financial\Dollar class instead * - * @return float|string + * @param array|float $decimal_dollar Decimal Dollar + * @param array|int $fraction Fraction + * + * @return array|float|string */ public static function DOLLARFR($decimal_dollar = null, $fraction = 0) { - $decimal_dollar = Functions::flattenSingleValue($decimal_dollar); - $fraction = (int) Functions::flattenSingleValue($fraction); - - // Validate parameters - if ($decimal_dollar === null || $fraction < 0) { - return Functions::NAN(); - } - if ($fraction == 0) { - return Functions::DIV0(); - } - - $dollars = floor($decimal_dollar); - $cents = fmod($decimal_dollar, 1); - $cents *= $fraction; - $cents *= pow(10, -ceil(log10($fraction))); - - return $dollars + $cents; + return Dollar::fractional($decimal_dollar, $fraction); } /** @@ -1115,24 +631,19 @@ public static function DOLLARFR($decimal_dollar = null, $fraction = 0) * Excel Function: * EFFECT(nominal_rate,npery) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\InterestRate::effective() + * Use the effective() method in the Financial\InterestRate class instead * - * @param float $nominal_rate Nominal interest rate - * @param int $npery Number of compounding payments per year + * @param float $nominalRate Nominal interest rate + * @param int $periodsPerYear Number of compounding payments per year * * @return float|string */ - public static function EFFECT($nominal_rate = 0, $npery = 0) + public static function EFFECT($nominalRate = 0, $periodsPerYear = 0) { - $nominal_rate = Functions::flattenSingleValue($nominal_rate); - $npery = (int) Functions::flattenSingleValue($npery); - - // Validate parameters - if ($nominal_rate <= 0 || $npery < 1) { - return Functions::NAN(); - } - - return pow((1 + $nominal_rate / $npery), $npery) - 1; + return Financial\InterestRate::effective($nominalRate, $periodsPerYear); } /** @@ -1143,7 +654,10 @@ public static function EFFECT($nominal_rate = 0, $npery = 0) * Excel Function: * FV(rate,nper,pmt[,pv[,type]]) * - * @category Financial Functions + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic::futureValue() + * Use the futureValue() method in the Financial\CashFlow\Constant\Periodic class instead * * @param float $rate The interest rate per period * @param int $nper Total number of payment periods in an annuity @@ -1160,23 +674,7 @@ public static function EFFECT($nominal_rate = 0, $npery = 0) */ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate; - } - - return -$pv - $pmt * $nper; + return Financial\CashFlow\Constant\Periodic::futureValue($rate, $nper, $pmt, $pv, $type); } /** @@ -1188,21 +686,19 @@ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) * Excel Function: * FVSCHEDULE(principal,schedule) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::futureValue() + * Use the futureValue() method in the Financial\CashFlow\Single class instead + * * @param float $principal the present value * @param float[] $schedule an array of interest rates to apply * - * @return float + * @return float|string */ public static function FVSCHEDULE($principal, $schedule) { - $principal = Functions::flattenSingleValue($principal); - $schedule = Functions::flattenArray($schedule); - - foreach ($schedule as $rate) { - $principal *= 1 + $rate; - } - - return $principal; + return Financial\CashFlow\Single::futureValue($principal, $schedule); } /** @@ -1213,57 +709,46 @@ public static function FVSCHEDULE($principal, $schedule) * Excel Function: * INTRATE(settlement,maturity,investment,redemption[,basis]) * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Rates::interest() + * Use the interest() method in the Financial\Securities\Rates class instead + * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $investment the amount invested in the security * @param int $redemption the amount to be received at maturity * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string */ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = Functions::flattenSingleValue($investment); - $redemption = Functions::flattenSingleValue($redemption); - $basis = Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) { - $investment = (float) $investment; - $redemption = (float) $redemption; - $basis = (int) $basis; - if (($investment <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Financial\Securities\Rates::interest($settlement, $maturity, $investment, $redemption, $basis); } /** * IPMT. * - * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. * * Excel Function: * IPMT(rate,per,nper,pv[,fv][,type]) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Interest::payment() + * Use the payment() method in the Financial\CashFlow\Constant\Periodic class instead + * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest * @param int $nper Number of periods @@ -1275,25 +760,7 @@ public static function INTRATE($settlement, $maturity, $investment, $redemption, */ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($per <= 0 || $per > $nper) { - return Functions::VALUE(); - } - - // Calculate - $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); - - return $interestAndPrincipal[0]; + return Financial\CashFlow\Constant\Periodic\Interest::payment($rate, $per, $nper, $pv, $fv, $type); } /** @@ -1308,63 +775,22 @@ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) * Excel Function: * IRR(values[,guess]) * - * @param float[] $values An array or a reference to cells that contain numbers for which you want + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::rate() + * Use the rate() method in the Financial\CashFlow\Variable\Periodic class instead + * + * @param mixed $values An array or a reference to cells that contain numbers for which you want * to calculate the internal rate of return. * Values must contain at least one positive value and one negative value to * calculate the internal rate of return. - * @param float $guess A number that you guess is close to the result of IRR + * @param mixed $guess A number that you guess is close to the result of IRR * * @return float|string */ public static function IRR($values, $guess = 0.1) { - if (!is_array($values)) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $guess = Functions::flattenSingleValue($guess); - - // create an initial range, with a root somewhere between 0 and guess - $x1 = 0.0; - $x2 = $guess; - $f1 = self::NPV($x1, $values); - $f2 = self::NPV($x2, $values); - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - if (($f1 * $f2) < 0.0) { - break; - } - if (abs($f1) < abs($f2)) { - $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values); - } else { - $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values); - } - } - if (($f1 * $f2) > 0.0) { - return Functions::VALUE(); - } - - $f = self::NPV($x1, $values); - if ($f < 0.0) { - $rtb = $x1; - $dx = $x2 - $x1; - } else { - $rtb = $x2; - $dx = $x1 - $x2; - } - - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - $dx *= 0.5; - $x_mid = $rtb + $dx; - $f_mid = self::NPV($x_mid, $values); - if ($f_mid <= 0.0) { - $rtb = $x_mid; - } - if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { - return $x_mid; - } - } - - return Functions::VALUE(); + return Financial\CashFlow\Variable\Periodic::rate($values, $guess); } /** @@ -1373,7 +799,12 @@ public static function IRR($values, $guess = 0.1) * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. * * Excel Function: - * =ISPMT(interest_rate, period, number_payments, PV) + * =ISPMT(interest_rate, period, number_payments, pv) + * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Interest::schedulePayment() + * Use the schedulePayment() method in the Financial\CashFlow\Constant\Periodic class instead * * interest_rate is the interest rate for the investment * @@ -1381,32 +812,11 @@ public static function IRR($values, $guess = 0.1) * * number_payments is the number of payments for the annuity * - * PV is the loan amount or present value of the payments + * pv is the loan amount or present value of the payments */ public static function ISPMT(...$args) { - // Return value - $returnValue = 0; - - // Get the parameters - $aArgs = Functions::flattenArray($args); - $interestRate = array_shift($aArgs); - $period = array_shift($aArgs); - $numberPeriods = array_shift($aArgs); - $principleRemaining = array_shift($aArgs); - - // Calculate - $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0); - for ($i = 0; $i <= $period; ++$i) { - $returnValue = $interestRate * $principleRemaining * -1; - $principleRemaining -= $principlePayment; - // principle needs to be 0 after the last payment, don't let floating point screw it up - if ($i == $numberPeriods) { - $returnValue = 0; - } - } - - return $returnValue; + return Financial\CashFlow\Constant\Periodic\Interest::schedulePayment(...$args); } /** @@ -1418,44 +828,22 @@ public static function ISPMT(...$args) * Excel Function: * MIRR(values,finance_rate, reinvestment_rate) * - * @param float[] $values An array or a reference to cells that contain a series of payments and - * income occurring at regular intervals. - * Payments are negative value, income is positive values. - * @param float $finance_rate The interest rate you pay on the money used in the cash flows - * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::modifiedRate() + * Use the modifiedRate() method in the Financial\CashFlow\Variable\Periodic class instead + * + * @param mixed $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param mixed $finance_rate The interest rate you pay on the money used in the cash flows + * @param mixed $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them * * @return float|string Result, or a string containing an error */ public static function MIRR($values, $finance_rate, $reinvestment_rate) { - if (!is_array($values)) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $finance_rate = Functions::flattenSingleValue($finance_rate); - $reinvestment_rate = Functions::flattenSingleValue($reinvestment_rate); - $n = count($values); - - $rr = 1.0 + $reinvestment_rate; - $fr = 1.0 + $finance_rate; - - $npv_pos = $npv_neg = 0.0; - foreach ($values as $i => $v) { - if ($v >= 0) { - $npv_pos += $v / pow($rr, $i); - } else { - $npv_neg += $v / pow($fr, $i); - } - } - - if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) { - return Functions::VALUE(); - } - - $mirr = pow((-$npv_pos * pow($rr, $n)) - / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0; - - return is_finite($mirr) ? $mirr : Functions::VALUE(); + return Financial\CashFlow\Variable\Periodic::modifiedRate($values, $finance_rate, $reinvestment_rate); } /** @@ -1463,23 +851,22 @@ public static function MIRR($values, $finance_rate, $reinvestment_rate) * * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. * - * @param float $effect_rate Effective interest rate - * @param int $npery Number of compounding payments per year + * Excel Function: + * NOMINAL(effect_rate, npery) + * + * @Deprecated 1.18.0 + * + * @see Financial\InterestRate::nominal() + * Use the nominal() method in the Financial\InterestRate class instead + * + * @param float $effectiveRate Effective interest rate + * @param int $periodsPerYear Number of compounding payments per year * * @return float|string Result, or a string containing an error */ - public static function NOMINAL($effect_rate = 0, $npery = 0) + public static function NOMINAL($effectiveRate = 0, $periodsPerYear = 0) { - $effect_rate = Functions::flattenSingleValue($effect_rate); - $npery = (int) Functions::flattenSingleValue($npery); - - // Validate parameters - if ($effect_rate <= 0 || $npery < 1) { - return Functions::NAN(); - } - - // Calculate - return $npery * (pow($effect_rate + 1, 1 / $npery) - 1); + return InterestRate::nominal($effectiveRate, $periodsPerYear); } /** @@ -1487,6 +874,8 @@ public static function NOMINAL($effect_rate = 0, $npery = 0) * * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. * + * @Deprecated 1.18.0 + * * @param float $rate Interest rate per period * @param int $pmt Periodic payment (annuity) * @param float $pv Present Value @@ -1494,33 +883,13 @@ public static function NOMINAL($effect_rate = 0, $npery = 0) * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period * * @return float|string Result, or a string containing an error + * + *@see Financial\CashFlow\Constant\Periodic::periods() + * Use the periods() method in the Financial\CashFlow\Constant\Periodic class instead */ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - if ($pmt == 0 && $pv == 0) { - return Functions::NAN(); - } - - return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate); - } - if ($pmt == 0) { - return Functions::NAN(); - } - - return (-$pv - $fv) / $pmt; + return Financial\CashFlow\Constant\Periodic::periods($rate, $pmt, $pv, $fv, $type); } /** @@ -1528,28 +897,16 @@ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) * * Returns the Net Present Value of a cash flow series given a discount rate. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\Periodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Variable\Periodic class instead + * * @return float */ public static function NPV(...$args) { - // Return value - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - // Calculate - $rate = array_shift($aArgs); - $countArgs = count($aArgs); - for ($i = 1; $i <= $countArgs; ++$i) { - // Is it a numeric value? - if (is_numeric($aArgs[$i - 1])) { - $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i); - } - } - - // Return - return $returnValue; + return Financial\CashFlow\Variable\Periodic::presentValue(...$args); } /** @@ -1557,6 +914,11 @@ public static function NPV(...$args) * * Calculates the number of periods required for an investment to reach a specified value. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::periods() + * Use the periods() method in the Financial\CashFlow\Single class instead + * * @param float $rate Interest rate per period * @param float $pv Present Value * @param float $fv Future Value @@ -1565,18 +927,7 @@ public static function NPV(...$args) */ public static function PDURATION($rate = 0, $pv = 0, $fv = 0) { - $rate = Functions::flattenSingleValue($rate); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - - // Validate parameters - if (!is_numeric($rate) || !is_numeric($pv) || !is_numeric($fv)) { - return Functions::VALUE(); - } elseif ($rate <= 0.0 || $pv <= 0.0 || $fv <= 0.0) { - return Functions::NAN(); - } - - return (log($fv) - log($pv)) / log(1 + $rate); + return Financial\CashFlow\Single::periods($rate, $pv, $fv); } /** @@ -1584,6 +935,11 @@ public static function PDURATION($rate = 0, $pv = 0, $fv = 0) * * Returns the constant payment (annuity) for a cash flow with a constant interest rate. * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Payments::annuity() + * Use the annuity() method in the Financial\CashFlow\Constant\Periodic\Payments class instead + * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pv Present Value @@ -1594,29 +950,19 @@ public static function PDURATION($rate = 0, $pv = 0, $fv = 0) */ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate); - } - - return (-$pv - $fv) / $nper; + return Financial\CashFlow\Constant\Periodic\Payments::annuity($rate, $nper, $pv, $fv, $type); } /** * PPMT. * - * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. + * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic\Payments::interestPayment() + * Use the interestPayment() method in the Financial\CashFlow\Constant\Periodic\Payments class instead * * @param float $rate Interest rate per period * @param int $per Period for which we want to find the interest @@ -1629,66 +975,43 @@ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) */ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $per = (int) Functions::flattenSingleValue($per); - $nper = (int) Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - $type = (int) Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - if ($per <= 0 || $per > $nper) { - return Functions::VALUE(); - } - - // Calculate - $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); - - return $interestAndPrincipal[1]; + return Financial\CashFlow\Constant\Periodic\Payments::interestPayment($rate, $per, $nper, $pv, $fv, $type); } + /** + * PRICE. + * + * Returns the price per $100 face value of a security that pays periodic interest. + * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::price() + * Use the price() method in the Financial\Securities\Price class instead + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param float $rate the security's annual coupon rate + * @param float $yield the security's annual yield + * @param float $redemption The number of coupon payments per year. + * For annual payments, frequency = 1; + * for semiannual, frequency = 2; + * for quarterly, frequency = 4. + * @param int $frequency + * @param int $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $rate = (float) Functions::flattenSingleValue($rate); - $yield = (float) Functions::flattenSingleValue($yield); - $redemption = (float) Functions::flattenSingleValue($redemption); - $frequency = (int) Functions::flattenSingleValue($frequency); - $basis = ($basis === null) ? 0 : (int) Functions::flattenSingleValue($basis); - - if (is_string($settlement = DateTime::getDateValue($settlement))) { - return Functions::VALUE(); - } - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (($settlement > $maturity) || - (!self::isValidFrequency($frequency)) || - (($basis < 0) || ($basis > 4))) { - return Functions::NAN(); - } - - $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis); - $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis); - $n = self::COUPNUM($settlement, $maturity, $frequency, $basis); - $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis); - - $baseYF = 1.0 + ($yield / $frequency); - $rfp = 100 * ($rate / $frequency); - $de = $dsc / $e; - - $result = $redemption / pow($baseYF, (--$n + $de)); - for ($k = 0; $k <= $n; ++$k) { - $result += $rfp / (pow($baseYF, ($k + $de))); - } - $result -= $rfp * ($a / $e); - - return $result; + return Securities\Price::price($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis); } /** @@ -1696,10 +1019,16 @@ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, * * Returns the price per $100 face value of a discounted security. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::priceDiscounted() + * Use the priceDiscounted() method in the Financial\Securities\Price class instead + * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $discount The security's discount rate * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. @@ -1713,27 +1042,7 @@ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, */ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = (float) Functions::flattenSingleValue($discount); - $redemption = (float) Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) { - if (($discount <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Price::priceDiscounted($settlement, $maturity, $discount, $redemption, $basis); } /** @@ -1741,10 +1050,16 @@ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, * * Returns the price per $100 face value of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::priceAtMaturity() + * Use the priceAtMaturity() method in the Financial\Securities\Price class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param int $rate The security's interest rate at date of issue * @param int $yield The security's annual yield @@ -1759,47 +1074,7 @@ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, */ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $yield = Functions::flattenSingleValue($yield); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($rate) && is_numeric($yield)) { - if (($rate <= 0) || ($yield <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - $daysBetweenIssueAndSettlement *= $daysPerYear; - $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis); - if (!is_numeric($daysBetweenIssueAndMaturity)) { - // return date error - return $daysBetweenIssueAndMaturity; - } - $daysBetweenIssueAndMaturity *= $daysPerYear; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / - (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - - (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); - } - - return Functions::VALUE(); + return Securities\Price::priceAtMaturity($settlement, $maturity, $issue, $rate, $yield, $basis); } /** @@ -1807,6 +1082,11 @@ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $ * * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Constant\Periodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Constant\Periodic class instead + * * @param float $rate Interest rate per period * @param int $nper Number of periods * @param float $pmt Periodic payment (annuity) @@ -1817,23 +1097,7 @@ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $ */ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) { - $rate = Functions::flattenSingleValue($rate); - $nper = Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $fv = Functions::flattenSingleValue($fv); - $type = Functions::flattenSingleValue($type); - - // Validate parameters - if ($type != 0 && $type != 1) { - return Functions::NAN(); - } - - // Calculate - if ($rate !== null && $rate != 0) { - return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper); - } - - return -$fv - $pmt * $nper; + return Financial\CashFlow\Constant\Periodic::presentValue($rate, $nper, $pmt, $fv, $type); } /** @@ -1847,113 +1111,63 @@ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) * Excel Function: * RATE(nper,pmt,pv[,fv[,type[,guess]]]) * - * @category Financial Functions + * @Deprecated 1.18.0 * - * @param float $nper The total number of payment periods in an annuity - * @param float $pmt The payment made each period and cannot change over the life + * @see Financial\CashFlow\Constant\Periodic\Interest::rate() + * Use the rate() method in the Financial\CashFlow\Constant\Periodic class instead + * + * @param mixed $nper The total number of payment periods in an annuity + * @param mixed $pmt The payment made each period and cannot change over the life * of the annuity. * Typically, pmt includes principal and interest but no other * fees or taxes. - * @param float $pv The present value - the total amount that a series of future + * @param mixed $pv The present value - the total amount that a series of future * payments is worth now - * @param float $fv The future value, or a cash balance you want to attain after + * @param mixed $fv The future value, or a cash balance you want to attain after * the last payment is made. If fv is omitted, it is assumed * to be 0 (the future value of a loan, for example, is 0). - * @param int $type A number 0 or 1 and indicates when payments are due: + * @param mixed $type A number 0 or 1 and indicates when payments are due: * 0 or omitted At the end of the period. * 1 At the beginning of the period. - * @param float $guess Your guess for what the rate will be. + * @param mixed $guess Your guess for what the rate will be. * If you omit guess, it is assumed to be 10 percent. * - * @return float + * @return float|string */ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) { - $nper = (int) Functions::flattenSingleValue($nper); - $pmt = Functions::flattenSingleValue($pmt); - $pv = Functions::flattenSingleValue($pv); - $fv = ($fv === null) ? 0.0 : Functions::flattenSingleValue($fv); - $type = ($type === null) ? 0 : (int) Functions::flattenSingleValue($type); - $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); - - $rate = $guess; - if (abs($rate) < self::FINANCIAL_PRECISION) { - $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; - } else { - $f = exp($nper * log(1 + $rate)); - $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; - } - $y0 = $pv + $pmt * $nper + $fv; - $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; - - // find root by secant method - $i = $x0 = 0.0; - $x1 = $rate; - while ((abs($y0 - $y1) > self::FINANCIAL_PRECISION) && ($i < self::FINANCIAL_MAX_ITERATIONS)) { - $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0); - $x0 = $x1; - $x1 = $rate; - if (($nper * abs($pmt)) > ($pv - $fv)) { - $x1 = abs($x1); - } - if (abs($rate) < self::FINANCIAL_PRECISION) { - $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; - } else { - $f = exp($nper * log(1 + $rate)); - $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; - } - - $y0 = $y1; - $y1 = $y; - ++$i; - } - - return $rate; + return Financial\CashFlow\Constant\Periodic\Interest::rate($nper, $pmt, $pv, $fv, $type, $guess); } /** * RECEIVED. * - * Returns the price per $100 face value of a discounted security. + * Returns the amount received at maturity for a fully invested Security. + * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Price::received() + * Use the received() method in the Financial\Securities\Price class instead * * @param mixed $settlement The security's settlement date. - * The security settlement date is the date after the issue date when the security is traded to the buyer. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. - * @param int $investment The amount invested in the security - * @param int $discount The security's discount rate - * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * The maturity date is the date when the security expires. + * @param mixed $investment The amount invested in the security + * @param mixed $discount The security's discount rate + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $investment = (float) Functions::flattenSingleValue($investment); - $discount = (float) Functions::flattenSingleValue($discount); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) { - if (($investment <= 0) || ($discount <= 0)) { - return Functions::NAN(); - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - - return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); - } - - return Functions::VALUE(); + return Financial\Securities\Price::received($settlement, $maturity, $investment, $discount, $basis); } /** @@ -1961,6 +1175,11 @@ public static function RECEIVED($settlement, $maturity, $investment, $discount, * * Calculates the interest rate required for an investment to grow to a specified future value . * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Single::interestRate() + * Use the interestRate() method in the Financial\CashFlow\Single class instead + * * @param float $nper The number of periods over which the investment is made * @param float $pv Present Value * @param float $fv Future Value @@ -1969,18 +1188,7 @@ public static function RECEIVED($settlement, $maturity, $investment, $discount, */ public static function RRI($nper = 0, $pv = 0, $fv = 0) { - $nper = Functions::flattenSingleValue($nper); - $pv = Functions::flattenSingleValue($pv); - $fv = Functions::flattenSingleValue($fv); - - // Validate parameters - if (!is_numeric($nper) || !is_numeric($pv) || !is_numeric($fv)) { - return Functions::VALUE(); - } elseif ($nper <= 0.0 || $pv <= 0.0 || $fv < 0.0) { - return Functions::NAN(); - } - - return pow($fv / $pv, 1 / $nper) - 1; + return Financial\CashFlow\Single::interestRate($nper, $pv, $fv); } /** @@ -1988,6 +1196,11 @@ public static function RRI($nper = 0, $pv = 0, $fv = 0) * * Returns the straight-line depreciation of an asset for one period * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::SLN() + * Use the SLN() method in the Financial\Depreciation class instead + * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated @@ -1996,20 +1209,7 @@ public static function RRI($nper = 0, $pv = 0, $fv = 0) */ public static function SLN($cost, $salvage, $life) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - - // Calculate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) { - if ($life < 0) { - return Functions::NAN(); - } - - return ($cost - $salvage) / $life; - } - - return Functions::VALUE(); + return Depreciation::SLN($cost, $salvage, $life); } /** @@ -2017,6 +1217,11 @@ public static function SLN($cost, $salvage, $life) * * Returns the sum-of-years' digits depreciation of an asset for a specified period. * + * @Deprecated 1.18.0 + * + * @see Financial\Depreciation::SYD() + * Use the SYD() method in the Financial\Depreciation class instead + * * @param mixed $cost Initial cost of the asset * @param mixed $salvage Value at the end of the depreciation * @param mixed $life Number of periods over which the asset is depreciated @@ -2026,21 +1231,7 @@ public static function SLN($cost, $salvage, $life) */ public static function SYD($cost, $salvage, $life, $period) { - $cost = Functions::flattenSingleValue($cost); - $salvage = Functions::flattenSingleValue($salvage); - $life = Functions::flattenSingleValue($life); - $period = Functions::flattenSingleValue($period); - - // Calculate - if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) { - if (($life < 1) || ($period > $life)) { - return Functions::NAN(); - } - - return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); - } - - return Functions::VALUE(); + return Depreciation::SYD($cost, $salvage, $life, $period); } /** @@ -2048,8 +1239,14 @@ public static function SYD($cost, $salvage, $life, $period) * * Returns the bond-equivalent yield for a Treasury bill. * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::bondEquivalentYield() + * Use the bondEquivalentYield() method in the Financial\TreasuryBill class instead + * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date when the + * Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $discount The Treasury bill's discount rate @@ -2058,37 +1255,22 @@ public static function SYD($cost, $salvage, $life, $period) */ public static function TBILLEQ($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); - - // Use TBILLPRICE for validation - $testValue = self::TBILLPRICE($settlement, $maturity, $discount); - if (is_string($testValue)) { - return $testValue; - } - - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + return TreasuryBill::bondEquivalentYield($settlement, $maturity, $discount); } /** * TBILLPRICE. * - * Returns the yield for a Treasury bill. + * Returns the price per $100 face value for a Treasury bill. + * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::price() + * Use the price() method in the Financial\TreasuryBill class instead * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $discount The Treasury bill's discount rate @@ -2097,44 +1279,7 @@ public static function TBILLEQ($settlement, $maturity, $discount) */ public static function TBILLPRICE($settlement, $maturity, $discount) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $discount = Functions::flattenSingleValue($discount); - - if (is_string($maturity = DateTime::getDateValue($maturity))) { - return Functions::VALUE(); - } - - // Validate - if (is_numeric($discount)) { - if ($discount <= 0) { - return Functions::NAN(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - if ($daysBetweenSettlementAndMaturity > 360) { - return Functions::NAN(); - } - - $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); - if ($price <= 0) { - return Functions::NAN(); - } - - return $price; - } - - return Functions::VALUE(); + return TreasuryBill::price($settlement, $maturity, $discount); } /** @@ -2142,8 +1287,14 @@ public static function TBILLPRICE($settlement, $maturity, $discount) * * Returns the yield for a Treasury bill. * + * @Deprecated 1.18.0 + * + * @see Financial\TreasuryBill::yield() + * Use the yield() method in the Financial\TreasuryBill class instead + * * @param mixed $settlement The Treasury bill's settlement date. - * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. * @param mixed $maturity The Treasury bill's maturity date. * The maturity date is the date when the Treasury bill expires. * @param int $price The Treasury bill's price per $100 face value @@ -2152,35 +1303,7 @@ public static function TBILLPRICE($settlement, $maturity, $discount) */ public static function TBILLYIELD($settlement, $maturity, $price) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - - // Validate - if (is_numeric($price)) { - if ($price <= 0) { - return Functions::NAN(); - } - - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - ++$maturity; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity) * 360; - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - } else { - $daysBetweenSettlementAndMaturity = (DateTime::getDateValue($maturity) - DateTime::getDateValue($settlement)); - } - - if ($daysBetweenSettlementAndMaturity > 360) { - return Functions::NAN(); - } - - return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return TreasuryBill::yield($settlement, $maturity, $price); } /** @@ -2191,6 +1314,11 @@ public static function TBILLYIELD($settlement, $maturity, $price) * Excel Function: * =XIRR(values,dates,guess) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\NonPeriodic::rate() + * Use the rate() method in the Financial\CashFlow\Variable\NonPeriodic class instead + * * @param float[] $values A series of cash flow payments * The series of values must contain at least one positive value & one negative value * @param mixed[] $dates A series of payment dates @@ -2202,73 +1330,7 @@ public static function TBILLYIELD($settlement, $maturity, $price) */ public static function XIRR($values, $dates, $guess = 0.1) { - if ((!is_array($values)) && (!is_array($dates))) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $dates = Functions::flattenArray($dates); - $guess = Functions::flattenSingleValue($guess); - if (count($values) != count($dates)) { - return Functions::NAN(); - } - - $datesCount = count($dates); - for ($i = 0; $i < $datesCount; ++$i) { - $dates[$i] = DateTime::getDateValue($dates[$i]); - if (!is_numeric($dates[$i])) { - return Functions::VALUE(); - } - } - if (min($dates) != $dates[0]) { - return Functions::NAN(); - } - - // create an initial range, with a root somewhere between 0 and guess - $x1 = 0.0; - $x2 = $guess; - $f1 = self::XNPV($x1, $values, $dates); - if (!is_numeric($f1)) { - return $f1; - } - $f2 = self::XNPV($x2, $values, $dates); - if (!is_numeric($f2)) { - return $f2; - } - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - if (($f1 * $f2) < 0.0) { - break; - } elseif (abs($f1) < abs($f2)) { - $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates); - } else { - $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates); - } - } - if (($f1 * $f2) > 0.0) { - return Functions::NAN(); - } - - $f = self::XNPV($x1, $values, $dates); - if ($f < 0.0) { - $rtb = $x1; - $dx = $x2 - $x1; - } else { - $rtb = $x2; - $dx = $x1 - $x2; - } - - for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { - $dx *= 0.5; - $x_mid = $rtb + $dx; - $f_mid = self::XNPV($x_mid, $values, $dates); - if ($f_mid <= 0.0) { - $rtb = $x_mid; - } - if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { - return $x_mid; - } - } - - return Functions::VALUE(); + return Financial\CashFlow\Variable\NonPeriodic::rate($values, $dates, $guess); } /** @@ -2280,45 +1342,27 @@ public static function XIRR($values, $dates, $guess = 0.1) * Excel Function: * =XNPV(rate,values,dates) * + * @Deprecated 1.18.0 + * + * @see Financial\CashFlow\Variable\NonPeriodic::presentValue() + * Use the presentValue() method in the Financial\CashFlow\Variable\NonPeriodic class instead + * * @param float $rate the discount rate to apply to the cash flows - * @param 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. - * @param 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. + * @param 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. + * @param 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. * * @return float|mixed|string */ public static function XNPV($rate, $values, $dates) { - $rate = Functions::flattenSingleValue($rate); - if (!is_numeric($rate)) { - return Functions::VALUE(); - } - if ((!is_array($values)) || (!is_array($dates))) { - return Functions::VALUE(); - } - $values = Functions::flattenArray($values); - $dates = Functions::flattenArray($dates); - $valCount = count($values); - if ($valCount != count($dates)) { - return Functions::NAN(); - } - if ((min($values) > 0) || (max($values) < 0)) { - return Functions::NAN(); - } - - $xnpv = 0.0; - for ($i = 0; $i < $valCount; ++$i) { - if (!is_numeric($values[$i])) { - return Functions::VALUE(); - } - $xnpv += $values[$i] / pow(1 + $rate, DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365); - } - - return (is_finite($xnpv)) ? $xnpv : Functions::VALUE(); + return Financial\CashFlow\Variable\NonPeriodic::presentValue($rate, $values, $dates); } /** @@ -2326,10 +1370,16 @@ public static function XNPV($rate, $values, $dates) * * Returns the annual yield of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Yields::yieldDiscounted() + * Use the yieldDiscounted() method in the Financial\Securities\Yields class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param int $price The security's price per $100 face value * @param int $redemption The security's redemption value per $100 face value * @param int $basis The type of day count to use. @@ -2343,32 +1393,7 @@ public static function XNPV($rate, $values, $dates) */ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $price = Functions::flattenSingleValue($price); - $redemption = Functions::flattenSingleValue($redemption); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($price) && is_numeric($redemption)) { - if (($price <= 0) || ($redemption <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Yields::yieldDiscounted($settlement, $maturity, $price, $redemption, $basis); } /** @@ -2376,64 +1401,30 @@ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $b * * Returns the annual yield of a security that pays interest at maturity. * + * @Deprecated 1.18.0 + * + * @see Financial\Securities\Yields::yieldAtMaturity() + * Use the yieldAtMaturity() method in the Financial\Securities\Yields class instead + * * @param mixed $settlement The security's settlement date. - * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. * @param mixed $maturity The security's maturity date. - * The maturity date is the date when the security expires. + * The maturity date is the date when the security expires. * @param mixed $issue The security's issue date * @param int $rate The security's interest rate at date of issue * @param int $price The security's price per $100 face value * @param int $basis The type of day count to use. - * 0 or omitted US (NASD) 30/360 - * 1 Actual/actual - * 2 Actual/360 - * 3 Actual/365 - * 4 European 30/360 + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 * * @return float|string Result, or a string containing an error */ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0) { - $settlement = Functions::flattenSingleValue($settlement); - $maturity = Functions::flattenSingleValue($maturity); - $issue = Functions::flattenSingleValue($issue); - $rate = Functions::flattenSingleValue($rate); - $price = Functions::flattenSingleValue($price); - $basis = (int) Functions::flattenSingleValue($basis); - - // Validate - if (is_numeric($rate) && is_numeric($price)) { - if (($rate <= 0) || ($price <= 0)) { - return Functions::NAN(); - } - $daysPerYear = self::daysPerYear(DateTime::YEAR($settlement), $basis); - if (!is_numeric($daysPerYear)) { - return $daysPerYear; - } - $daysBetweenIssueAndSettlement = DateTime::YEARFRAC($issue, $settlement, $basis); - if (!is_numeric($daysBetweenIssueAndSettlement)) { - // return date error - return $daysBetweenIssueAndSettlement; - } - $daysBetweenIssueAndSettlement *= $daysPerYear; - $daysBetweenIssueAndMaturity = DateTime::YEARFRAC($issue, $maturity, $basis); - if (!is_numeric($daysBetweenIssueAndMaturity)) { - // return date error - return $daysBetweenIssueAndMaturity; - } - $daysBetweenIssueAndMaturity *= $daysPerYear; - $daysBetweenSettlementAndMaturity = DateTime::YEARFRAC($settlement, $maturity, $basis); - if (!is_numeric($daysBetweenSettlementAndMaturity)) { - // return date error - return $daysBetweenSettlementAndMaturity; - } - $daysBetweenSettlementAndMaturity *= $daysPerYear; - - return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * - ($daysPerYear / $daysBetweenSettlementAndMaturity); - } - - return Functions::VALUE(); + return Securities\Yields::yieldAtMaturity($settlement, $maturity, $issue, $rate, $price, $basis); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php new file mode 100644 index 00000000..691ba40c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Amortization.php @@ -0,0 +1,214 @@ +getMessage(); + } + + $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); + if (is_string($yearFracx)) { + return $yearFracx; + } + /** @var float */ + $yearFrac = $yearFracx; + + $amortiseCoeff = self::getAmortizationCoefficient($rate); + + $rate *= $amortiseCoeff; + $fNRate = round($yearFrac * $rate * $cost, 0); + $cost -= $fNRate; + $fRest = $cost - $salvage; + + for ($n = 0; $n < $period; ++$n) { + $fNRate = round($rate * $cost, 0); + $fRest -= $fNRate; + + if ($fRest < 0.0) { + switch ($period - $n) { + case 0: + case 1: + return round($cost * 0.5, 0); + default: + return 0.0; + } + } + $cost -= $fNRate; + } + + return $fNRate; + } + + /** + * AMORLINC. + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * + * Excel Function: + * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @param mixed $cost The cost of the asset as a float + * @param mixed $purchased Date of the purchase of the asset + * @param mixed $firstPeriod Date of the end of the first period + * @param mixed $salvage The salvage value at the end of the life of the asset + * @param mixed $period The period as a float + * @param mixed $rate Rate of depreciation as float + * @param mixed $basis Integer indicating the type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string (string containing the error type if there is an error) + */ + public static function AMORLINC( + $cost, + $purchased, + $firstPeriod, + $salvage, + $period, + $rate, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $cost = Functions::flattenSingleValue($cost); + $purchased = Functions::flattenSingleValue($purchased); + $firstPeriod = Functions::flattenSingleValue($firstPeriod); + $salvage = Functions::flattenSingleValue($salvage); + $period = Functions::flattenSingleValue($period); + $rate = Functions::flattenSingleValue($rate); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $cost = FinancialValidations::validateFloat($cost); + $purchased = FinancialValidations::validateDate($purchased); + $firstPeriod = FinancialValidations::validateDate($firstPeriod); + $salvage = FinancialValidations::validateFloat($salvage); + $period = FinancialValidations::validateFloat($period); + $rate = FinancialValidations::validateFloat($rate); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $fOneRate = $cost * $rate; + $fCostDelta = $cost - $salvage; + // Note, quirky variation for leap years on the YEARFRAC for this function + $purchasedYear = DateTimeExcel\DateParts::year($purchased); + $yearFracx = DateTimeExcel\YearFrac::fraction($purchased, $firstPeriod, $basis); + if (is_string($yearFracx)) { + return $yearFracx; + } + /** @var float */ + $yearFrac = $yearFracx; + + if ( + ($basis == FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) && + ($yearFrac < 1) && (Functions::scalar(DateTimeExcel\Helpers::isLeapYear($purchasedYear))) + ) { + $yearFrac *= 365 / 366; + } + + $f0Rate = $yearFrac * $rate * $cost; + $nNumOfFullPeriods = (int) (($cost - $salvage - $f0Rate) / $fOneRate); + + if ($period == 0) { + return $f0Rate; + } elseif ($period <= $nNumOfFullPeriods) { + return $fOneRate; + } elseif ($period == ($nNumOfFullPeriods + 1)) { + return $fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate; + } + + return 0.0; + } + + private static function getAmortizationCoefficient(float $rate): float + { + // The depreciation coefficients are: + // Life of assets (1/rate) Depreciation coefficient + // Less than 3 years 1 + // Between 3 and 4 years 1.5 + // Between 5 and 6 years 2 + // More than 6 years 2.5 + $fUsePer = 1.0 / $rate; + + if ($fUsePer < 3.0) { + return 1.0; + } elseif ($fUsePer < 4.0) { + return 1.5; + } elseif ($fUsePer <= 6.0) { + return 2.0; + } + + return 2.5; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php new file mode 100644 index 00000000..8ebe9ed7 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/CashFlowValidations.php @@ -0,0 +1,53 @@ +getMessage(); + } + + return self::calculateFutureValue($rate, $numberOfPeriods, $payment, $presentValue, $type); + } + + /** + * PV. + * + * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). + * + * @param mixed $rate Interest rate per period + * @param mixed $numberOfPeriods Number of periods as an integer + * @param mixed $payment Periodic payment (annuity) + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function presentValue( + $rate, + $numberOfPeriods, + $payment = 0.0, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $payment = ($payment === null) ? 0.0 : Functions::flattenSingleValue($payment); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $payment = CashFlowValidations::validateFloat($payment); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($numberOfPeriods < 0) { + return ExcelError::NAN(); + } + + return self::calculatePresentValue($rate, $numberOfPeriods, $payment, $futureValue, $type); + } + + /** + * NPER. + * + * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. + * + * @param mixed $rate Interest rate per period + * @param mixed $payment Periodic payment (annuity) + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function periods( + $rate, + $payment, + $presentValue, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $payment = Functions::flattenSingleValue($payment); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $payment = CashFlowValidations::validateFloat($payment); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($payment == 0.0) { + return ExcelError::NAN(); + } + + return self::calculatePeriods($rate, $payment, $presentValue, $futureValue, $type); + } + + private static function calculateFutureValue( + float $rate, + int $numberOfPeriods, + float $payment, + float $presentValue, + int $type + ): float { + if ($rate !== null && $rate != 0) { + return -$presentValue * + (1 + $rate) ** $numberOfPeriods - $payment * (1 + $rate * $type) * ((1 + $rate) ** $numberOfPeriods - 1) + / $rate; + } + + return -$presentValue - $payment * $numberOfPeriods; + } + + private static function calculatePresentValue( + float $rate, + int $numberOfPeriods, + float $payment, + float $futureValue, + int $type + ): float { + if ($rate != 0.0) { + return (-$payment * (1 + $rate * $type) + * (((1 + $rate) ** $numberOfPeriods - 1) / $rate) - $futureValue) / (1 + $rate) ** $numberOfPeriods; + } + + return -$futureValue - $payment * $numberOfPeriods; + } + + /** + * @return float|string + */ + private static function calculatePeriods( + float $rate, + float $payment, + float $presentValue, + float $futureValue, + int $type + ) { + if ($rate != 0.0) { + if ($presentValue == 0.0) { + return ExcelError::NAN(); + } + + return log(($payment * (1 + $rate * $type) / $rate - $futureValue) / + ($presentValue + $payment * (1 + $rate * $type) / $rate)) / log(1 + $rate); + } + + return (-$presentValue - $futureValue) / $payment; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php new file mode 100644 index 00000000..b7aaffd8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Cumulative.php @@ -0,0 +1,142 @@ +getMessage(); + } + + // Validate parameters + if ($start < 1 || $start > $end) { + return ExcelError::NAN(); + } + + // Calculate + $interest = 0; + for ($per = $start; $per <= $end; ++$per) { + $ipmt = Interest::payment($rate, $per, $periods, $presentValue, 0, $type); + if (is_string($ipmt)) { + return $ipmt; + } + + $interest += $ipmt; + } + + return $interest; + } + + /** + * CUMPRINC. + * + * Returns the cumulative principal paid on a loan between the start and end periods. + * + * Excel Function: + * CUMPRINC(rate,nper,pv,start,end[,type]) + * + * @param mixed $rate The Interest rate + * @param mixed $periods The total number of payment periods as an integer + * @param mixed $presentValue Present Value + * @param mixed $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param mixed $end the last period in the calculation + * @param mixed $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * + * @return float|string + */ + public static function principal( + $rate, + $periods, + $presentValue, + $start, + $end, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $rate = Functions::flattenSingleValue($rate); + $periods = Functions::flattenSingleValue($periods); + $presentValue = Functions::flattenSingleValue($presentValue); + $start = Functions::flattenSingleValue($start); + $end = Functions::flattenSingleValue($end); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $rate = CashFlowValidations::validateRate($rate); + $periods = CashFlowValidations::validateInt($periods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $start = CashFlowValidations::validateInt($start); + $end = CashFlowValidations::validateInt($end); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($start < 1 || $start > $end) { + return ExcelError::VALUE(); + } + + // Calculate + $principal = 0; + for ($per = $start; $per <= $end; ++$per) { + $ppmt = Payments::interestPayment($rate, $per, $periods, $presentValue, 0, $type); + if (is_string($ppmt)) { + return $ppmt; + } + + $principal += $ppmt; + } + + return $principal; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php new file mode 100644 index 00000000..80412082 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Interest.php @@ -0,0 +1,217 @@ +getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return ExcelError::NAN(); + } + + // Calculate + $interestAndPrincipal = new InterestAndPrincipal( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue, + $type + ); + + return $interestAndPrincipal->interest(); + } + + /** + * ISPMT. + * + * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. + * + * Excel Function: + * =ISPMT(interest_rate, period, number_payments, pv) + * + * @param mixed $interestRate is the interest rate for the investment + * @param mixed $period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. + * @param mixed $numberOfPeriods is the number of payments for the annuity + * @param mixed $principleRemaining is the loan amount or present value of the payments + */ + public static function schedulePayment($interestRate, $period, $numberOfPeriods, $principleRemaining) + { + $interestRate = Functions::flattenSingleValue($interestRate); + $period = Functions::flattenSingleValue($period); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $principleRemaining = Functions::flattenSingleValue($principleRemaining); + + try { + $interestRate = CashFlowValidations::validateRate($interestRate); + $period = CashFlowValidations::validateInt($period); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $principleRemaining = CashFlowValidations::validateFloat($principleRemaining); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return ExcelError::NAN(); + } + + // Return value + $returnValue = 0; + + // Calculate + $principlePayment = ($principleRemaining * 1.0) / ($numberOfPeriods * 1.0); + for ($i = 0; $i <= $period; ++$i) { + $returnValue = $interestRate * $principleRemaining * -1; + $principleRemaining -= $principlePayment; + // principle needs to be 0 after the last payment, don't let floating point screw it up + if ($i == $numberOfPeriods) { + $returnValue = 0.0; + } + } + + return $returnValue; + } + + /** + * RATE. + * + * Returns the interest rate per period of an annuity. + * RATE is calculated by iteration and can have zero or more solutions. + * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, + * RATE returns the #NUM! error value. + * + * Excel Function: + * RATE(nper,pmt,pv[,fv[,type[,guess]]]) + * + * @param mixed $numberOfPeriods The total number of payment periods in an annuity + * @param mixed $payment The payment made each period and cannot change over the life of the annuity. + * Typically, pmt includes principal and interest but no other fees or taxes. + * @param mixed $presentValue The present value - the total amount that a series of future payments is worth now + * @param mixed $futureValue The future value, or a cash balance you want to attain after the last payment is made. + * If fv is omitted, it is assumed to be 0 (the future value of a loan, + * for example, is 0). + * @param mixed $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @param mixed $guess Your guess for what the rate will be. + * If you omit guess, it is assumed to be 10 percent. + * + * @return float|string + */ + public static function rate( + $numberOfPeriods, + $payment, + $presentValue, + $futureValue = 0.0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD, + $guess = 0.1 + ) { + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $payment = Functions::flattenSingleValue($payment); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + $guess = ($guess === null) ? 0.1 : Functions::flattenSingleValue($guess); + + try { + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $payment = CashFlowValidations::validateFloat($payment); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + $guess = CashFlowValidations::validateFloat($guess); + } catch (Exception $e) { + return $e->getMessage(); + } + + $rate = $guess; + // rest of code adapted from python/numpy + $close = false; + $iter = 0; + while (!$close && $iter < self::FINANCIAL_MAX_ITERATIONS) { + $nextdiff = self::rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type); + if (!is_numeric($nextdiff)) { + break; + } + $rate1 = $rate - $nextdiff; + $close = abs($rate1 - $rate) < self::FINANCIAL_PRECISION; + ++$iter; + $rate = $rate1; + } + + return $close ? $rate : ExcelError::NAN(); + } + + private static function rateNextGuess($rate, $numberOfPeriods, $payment, $presentValue, $futureValue, $type) + { + if ($rate == 0.0) { + return ExcelError::NAN(); + } + $tt1 = ($rate + 1) ** $numberOfPeriods; + $tt2 = ($rate + 1) ** ($numberOfPeriods - 1); + $numerator = $futureValue + $tt1 * $presentValue + $payment * ($tt1 - 1) * ($rate * $type + 1) / $rate; + $denominator = $numberOfPeriods * $tt2 * $presentValue - $payment * ($tt1 - 1) + * ($rate * $type + 1) / ($rate * $rate) + $numberOfPeriods + * $payment * $tt2 * ($rate * $type + 1) / $rate + $payment * ($tt1 - 1) * $type / $rate; + if ($denominator == 0) { + return ExcelError::NAN(); + } + + return $numerator / $denominator; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php new file mode 100644 index 00000000..ca989e00 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/InterestAndPrincipal.php @@ -0,0 +1,44 @@ +interest = $interest; + $this->principal = $principal; + } + + public function interest(): float + { + return $this->interest; + } + + public function principal(): float + { + return $this->principal; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php new file mode 100644 index 00000000..83965f9d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Constant/Periodic/Payments.php @@ -0,0 +1,116 @@ +getMessage(); + } + + // Calculate + if ($interestRate != 0.0) { + return (-$futureValue - $presentValue * (1 + $interestRate) ** $numberOfPeriods) / + (1 + $interestRate * $type) / (((1 + $interestRate) ** $numberOfPeriods - 1) / $interestRate); + } + + return (-$presentValue - $futureValue) / $numberOfPeriods; + } + + /** + * PPMT. + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments + * and a constant interest rate. + * + * @param mixed $interestRate Interest rate per period + * @param mixed $period Period for which we want to find the interest + * @param mixed $numberOfPeriods Number of periods + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * @param mixed $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * + * @return float|string Result, or a string containing an error + */ + public static function interestPayment( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue = 0, + $type = FinancialConstants::PAYMENT_END_OF_PERIOD + ) { + $interestRate = Functions::flattenSingleValue($interestRate); + $period = Functions::flattenSingleValue($period); + $numberOfPeriods = Functions::flattenSingleValue($numberOfPeriods); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = ($futureValue === null) ? 0.0 : Functions::flattenSingleValue($futureValue); + $type = ($type === null) ? FinancialConstants::PAYMENT_END_OF_PERIOD : Functions::flattenSingleValue($type); + + try { + $interestRate = CashFlowValidations::validateRate($interestRate); + $period = CashFlowValidations::validateInt($period); + $numberOfPeriods = CashFlowValidations::validateInt($numberOfPeriods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + $type = CashFlowValidations::validatePeriodType($type); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($period <= 0 || $period > $numberOfPeriods) { + return ExcelError::NAN(); + } + + // Calculate + $interestAndPrincipal = new InterestAndPrincipal( + $interestRate, + $period, + $numberOfPeriods, + $presentValue, + $futureValue, + $type + ); + + return $interestAndPrincipal->principal(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php new file mode 100644 index 00000000..058e89c6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Single.php @@ -0,0 +1,109 @@ +getMessage(); + } + + return $principal; + } + + /** + * PDURATION. + * + * Calculates the number of periods required for an investment to reach a specified value. + * + * @param mixed $rate Interest rate per period + * @param mixed $presentValue Present Value + * @param mixed $futureValue Future Value + * + * @return float|string Result, or a string containing an error + */ + public static function periods($rate, $presentValue, $futureValue) + { + $rate = Functions::flattenSingleValue($rate); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = Functions::flattenSingleValue($futureValue); + + try { + $rate = CashFlowValidations::validateRate($rate); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($rate <= 0.0 || $presentValue <= 0.0 || $futureValue <= 0.0) { + return ExcelError::NAN(); + } + + return (log($futureValue) - log($presentValue)) / log(1 + $rate); + } + + /** + * RRI. + * + * Calculates the interest rate required for an investment to grow to a specified future value . + * + * @param float $periods The number of periods over which the investment is made + * @param float $presentValue Present Value + * @param float $futureValue Future Value + * + * @return float|string Result, or a string containing an error + */ + public static function interestRate($periods = 0.0, $presentValue = 0.0, $futureValue = 0.0) + { + $periods = Functions::flattenSingleValue($periods); + $presentValue = Functions::flattenSingleValue($presentValue); + $futureValue = Functions::flattenSingleValue($futureValue); + + try { + $periods = CashFlowValidations::validateFloat($periods); + $presentValue = CashFlowValidations::validatePresentValue($presentValue); + $futureValue = CashFlowValidations::validateFutureValue($futureValue); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if ($periods <= 0.0 || $presentValue <= 0.0 || $futureValue < 0.0) { + return ExcelError::NAN(); + } + + return ($futureValue / $presentValue) ** (1 / $periods) - 1; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php new file mode 100644 index 00000000..b8126135 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/NonPeriodic.php @@ -0,0 +1,259 @@ + 1; + $datesIsArray = count($dates) > 1; + if (!$valuesIsArray && !$datesIsArray) { + return ExcelError::NA(); + } + if (count($values) != count($dates)) { + return ExcelError::NAN(); + } + + $datesCount = count($dates); + for ($i = 0; $i < $datesCount; ++$i) { + try { + $dates[$i] = DateTimeExcel\Helpers::getDateValue($dates[$i]); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + return self::xirrPart2($values); + } + + private static function xirrPart2(array &$values): string + { + $valCount = count($values); + $foundpos = false; + $foundneg = false; + for ($i = 0; $i < $valCount; ++$i) { + $fld = $values[$i]; + if (!is_numeric($fld)) { + return ExcelError::VALUE(); + } elseif ($fld > 0) { + $foundpos = true; + } elseif ($fld < 0) { + $foundneg = true; + } + } + if (!self::bothNegAndPos($foundneg, $foundpos)) { + return ExcelError::NAN(); + } + + return ''; + } + + /** + * @return float|string + */ + private static function xirrPart3(array $values, array $dates, float $x1, float $x2) + { + $f = self::xnpvOrdered($x1, $values, $dates, false); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + $rslt = ExcelError::VALUE(); + for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = (float) self::xnpvOrdered($x_mid, $values, $dates, false); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { + $rslt = $x_mid; + + break; + } + } + + return $rslt; + } + + /** + * @param mixed $rate + * @param mixed $values + * @param mixed $dates + * + * @return float|string + */ + private static function xnpvOrdered($rate, $values, $dates, bool $ordered = true) + { + $rate = Functions::flattenSingleValue($rate); + $values = Functions::flattenArray($values); + $dates = Functions::flattenArray($dates); + $valCount = count($values); + + try { + self::validateXnpv($rate, $values, $dates); + $date0 = DateTimeExcel\Helpers::getDateValue($dates[0]); + } catch (Exception $e) { + return $e->getMessage(); + } + + $xnpv = 0.0; + for ($i = 0; $i < $valCount; ++$i) { + if (!is_numeric($values[$i])) { + return ExcelError::VALUE(); + } + + try { + $datei = DateTimeExcel\Helpers::getDateValue($dates[$i]); + } catch (Exception $e) { + return $e->getMessage(); + } + if ($date0 > $datei) { + $dif = $ordered ? ExcelError::NAN() : -((int) DateTimeExcel\Difference::interval($datei, $date0, 'd')); + } else { + $dif = DateTimeExcel\Difference::interval($date0, $datei, 'd'); + } + if (!is_numeric($dif)) { + return $dif; + } + if ($rate <= -1.0) { + $xnpv += -abs($values[$i]) / (-1 - $rate) ** ($dif / 365); + } else { + $xnpv += $values[$i] / (1 + $rate) ** ($dif / 365); + } + } + + return is_finite($xnpv) ? $xnpv : ExcelError::VALUE(); + } + + /** + * @param mixed $rate + */ + private static function validateXnpv($rate, array $values, array $dates): void + { + if (!is_numeric($rate)) { + throw new Exception(ExcelError::VALUE()); + } + $valCount = count($values); + if ($valCount != count($dates)) { + throw new Exception(ExcelError::NAN()); + } + if ($valCount > 1 && ((min($values) > 0) || (max($values) < 0))) { + throw new Exception(ExcelError::NAN()); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php new file mode 100644 index 00000000..49d063c9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/CashFlow/Variable/Periodic.php @@ -0,0 +1,161 @@ + 0.0) { + return ExcelError::VALUE(); + } + + $f = self::presentValue($x1, $values); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < self::FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::presentValue($x_mid, $values); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < self::FINANCIAL_PRECISION) || (abs($dx) < self::FINANCIAL_PRECISION)) { + return $x_mid; + } + } + + return ExcelError::VALUE(); + } + + /** + * MIRR. + * + * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both + * the cost of the investment and the interest received on reinvestment of cash. + * + * Excel Function: + * MIRR(values,finance_rate, reinvestment_rate) + * + * @param mixed $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param mixed $financeRate The interest rate you pay on the money used in the cash flows + * @param mixed $reinvestmentRate The interest rate you receive on the cash flows as you reinvest them + * + * @return float|string Result, or a string containing an error + */ + public static function modifiedRate($values, $financeRate, $reinvestmentRate) + { + if (!is_array($values)) { + return ExcelError::VALUE(); + } + $values = Functions::flattenArray($values); + $financeRate = Functions::flattenSingleValue($financeRate); + $reinvestmentRate = Functions::flattenSingleValue($reinvestmentRate); + $n = count($values); + + $rr = 1.0 + $reinvestmentRate; + $fr = 1.0 + $financeRate; + + $npvPos = $npvNeg = 0.0; + foreach ($values as $i => $v) { + if ($v >= 0) { + $npvPos += $v / $rr ** $i; + } else { + $npvNeg += $v / $fr ** $i; + } + } + + if (($npvNeg === 0.0) || ($npvPos === 0.0) || ($reinvestmentRate <= -1.0)) { + return ExcelError::VALUE(); + } + + $mirr = ((-$npvPos * $rr ** $n) + / ($npvNeg * ($rr))) ** (1.0 / ($n - 1)) - 1.0; + + return is_finite($mirr) ? $mirr : ExcelError::VALUE(); + } + + /** + * NPV. + * + * Returns the Net Present Value of a cash flow series given a discount rate. + * + * @param mixed $rate + * + * @return float + */ + public static function presentValue($rate, ...$args) + { + $returnValue = 0; + + $rate = Functions::flattenSingleValue($rate); + $aArgs = Functions::flattenArray($args); + + // Calculate + $countArgs = count($aArgs); + for ($i = 1; $i <= $countArgs; ++$i) { + // Is it a numeric value? + if (is_numeric($aArgs[$i - 1])) { + $returnValue += $aArgs[$i - 1] / (1 + $rate) ** $i; + } + } + + return $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php new file mode 100644 index 00000000..17740b0a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Constants.php @@ -0,0 +1,19 @@ +getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); + if (is_string($daysPerYear)) { + return ExcelError::VALUE(); + } + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + + if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL) { + return abs((float) DateTimeExcel\Days::between($prev, $settlement)); + } + + return (float) DateTimeExcel\YearFrac::fraction($prev, $settlement, $basis) * $daysPerYear; + } + + /** + * COUPDAYS. + * + * Returns the number of days in the coupon period that contains the settlement date. + * + * Excel Function: + * COUPDAYS(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function COUPDAYS( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + switch ($basis) { + case FinancialConstants::BASIS_DAYS_PER_YEAR_365: + // Actual/365 + return 365 / $frequency; + case FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL: + // Actual/actual + if ($frequency == FinancialConstants::FREQUENCY_ANNUAL) { + $daysPerYear = (int) Helpers::daysPerYear(Functions::scalar(DateTimeExcel\DateParts::year($settlement)), $basis); + + return $daysPerYear / $frequency; + } + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + + return $next - $prev; + default: + // US (NASD) 30/360, Actual/360 or European 30/360 + return 360 / $frequency; + } + } + + /** + * COUPDAYSNC. + * + * Returns the number of days from the settlement date to the next coupon date. + * + * Excel Function: + * COUPDAYSNC(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int) . + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function COUPDAYSNC( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + /** @var int */ + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + + if ($basis === FinancialConstants::BASIS_DAYS_PER_YEAR_NASD) { + $settlementDate = Date::excelToDateTimeObject($settlement); + $settlementEoM = Helpers::isLastDayOfMonth($settlementDate); + if ($settlementEoM) { + ++$settlement; + } + } + + return (float) DateTimeExcel\YearFrac::fraction($settlement, $next, $basis) * $daysPerYear; + } + + /** + * COUPNCD. + * + * Returns the next coupon date after the settlement date. + * + * Excel Function: + * COUPNCD(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPNCD( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_NEXT); + } + + /** + * COUPNUM. + * + * Returns the number of coupons payable between the settlement date and maturity date, + * rounded up to the nearest whole coupon. + * + * Excel Function: + * COUPNUM(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return int|string + */ + public static function COUPNUM( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $yearsBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction( + $settlement, + $maturity, + FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ); + + return (int) ceil((float) $yearsBetweenSettlementAndMaturity * $frequency); + } + + /** + * COUPPCD. + * + * Returns the previous coupon date before the settlement date. + * + * Excel Function: + * COUPPCD(settlement,maturity,frequency[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $frequency The number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * @param mixed $basis The type of day count to use (int). + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPPCD( + $settlement, + $maturity, + $frequency, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $frequency = Functions::flattenSingleValue($frequency); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + self::validateCouponPeriod($settlement, $maturity); + $frequency = FinancialValidations::validateFrequency($frequency); + $basis = FinancialValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, self::PERIOD_DATE_PREVIOUS); + } + + private static function monthsDiff(DateTime $result, int $months, string $plusOrMinus, int $day, bool $lastDayFlag): void + { + $result->setDate((int) $result->format('Y'), (int) $result->format('m'), 1); + $result->modify("$plusOrMinus $months months"); + $daysInMonth = (int) $result->format('t'); + $result->setDate((int) $result->format('Y'), (int) $result->format('m'), $lastDayFlag ? $daysInMonth : min($day, $daysInMonth)); + } + + private static function couponFirstPeriodDate(float $settlement, float $maturity, int $frequency, bool $next): float + { + $months = 12 / $frequency; + + $result = Date::excelToDateTimeObject($maturity); + $day = (int) $result->format('d'); + $lastDayFlag = Helpers::isLastDayOfMonth($result); + + while ($settlement < Date::PHPToExcel($result)) { + self::monthsDiff($result, $months, '-', $day, $lastDayFlag); + } + if ($next === true) { + self::monthsDiff($result, $months, '+', $day, $lastDayFlag); + } + + return (float) Date::PHPToExcel($result); + } + + private static function validateCouponPeriod(float $settlement, float $maturity): void + { + if ($settlement >= $maturity) { + throw new Exception(ExcelError::NAN()); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php new file mode 100644 index 00000000..3d72757a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Depreciation.php @@ -0,0 +1,267 @@ +getMessage(); + } + + if ($cost === 0.0) { + return 0.0; + } + + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - ($salvage / $cost) ** (1 / $life); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + // TODO Handle period value between 0 and 1 (e.g. 0.5) + $previousDepreciation = 0; + $depreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + if ($per == 1) { + $depreciation = $cost * $fixedDepreciationRate * $month / 12; + } elseif ($per == ($life + 1)) { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; + } else { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; + } + $previousDepreciation += $depreciation; + } + + return $depreciation; + } + + /** + * DDB. + * + * Returns the depreciation of an asset for a specified period using the + * double-declining balance method or some other method you specify. + * + * Excel Function: + * DDB(cost,salvage,life,period[,factor]) + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param mixed $life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param mixed $period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param mixed $factor The rate at which the balance declines. + * If factor is omitted, it is assumed to be 2 (the + * double-declining balance method). + * + * @return float|string + */ + public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + $factor = Functions::flattenSingleValue($factor); + + try { + $cost = self::validateCost($cost); + $salvage = self::validateSalvage($salvage); + $life = self::validateLife($life); + $period = self::validatePeriod($period); + $factor = self::validateFactor($factor); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($period > $life) { + return ExcelError::NAN(); + } + + // Loop through each period calculating the depreciation + // TODO Handling for fractional $period values + $previousDepreciation = 0; + $depreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + $depreciation = min( + ($cost - $previousDepreciation) * ($factor / $life), + ($cost - $salvage - $previousDepreciation) + ); + $previousDepreciation += $depreciation; + } + + return $depreciation; + } + + /** + * SLN. + * + * Returns the straight-line depreciation of an asset for one period + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation + * @param mixed $life Number of periods over which the asset is depreciated + * + * @return float|string Result, or a string containing an error + */ + public static function SLN($cost, $salvage, $life) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + + try { + $cost = self::validateCost($cost, true); + $salvage = self::validateSalvage($salvage, true); + $life = self::validateLife($life, true); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($life === 0.0) { + return ExcelError::DIV0(); + } + + return ($cost - $salvage) / $life; + } + + /** + * SYD. + * + * Returns the sum-of-years' digits depreciation of an asset for a specified period. + * + * @param mixed $cost Initial cost of the asset + * @param mixed $salvage Value at the end of the depreciation + * @param mixed $life Number of periods over which the asset is depreciated + * @param mixed $period Period + * + * @return float|string Result, or a string containing an error + */ + public static function SYD($cost, $salvage, $life, $period) + { + $cost = Functions::flattenSingleValue($cost); + $salvage = Functions::flattenSingleValue($salvage); + $life = Functions::flattenSingleValue($life); + $period = Functions::flattenSingleValue($period); + + try { + $cost = self::validateCost($cost, true); + $salvage = self::validateSalvage($salvage); + $life = self::validateLife($life); + $period = self::validatePeriod($period); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($period > $life) { + return ExcelError::NAN(); + } + + $syd = (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); + + return $syd; + } + + private static function validateCost($cost, bool $negativeValueAllowed = false): float + { + $cost = FinancialValidations::validateFloat($cost); + if ($cost < 0.0 && $negativeValueAllowed === false) { + throw new Exception(ExcelError::NAN()); + } + + return $cost; + } + + private static function validateSalvage($salvage, bool $negativeValueAllowed = false): float + { + $salvage = FinancialValidations::validateFloat($salvage); + if ($salvage < 0.0 && $negativeValueAllowed === false) { + throw new Exception(ExcelError::NAN()); + } + + return $salvage; + } + + private static function validateLife($life, bool $negativeValueAllowed = false): float + { + $life = FinancialValidations::validateFloat($life); + if ($life < 0.0 && $negativeValueAllowed === false) { + throw new Exception(ExcelError::NAN()); + } + + return $life; + } + + private static function validatePeriod($period, bool $negativeValueAllowed = false): float + { + $period = FinancialValidations::validateFloat($period); + if ($period <= 0.0 && $negativeValueAllowed === false) { + throw new Exception(ExcelError::NAN()); + } + + return $period; + } + + private static function validateMonth($month): int + { + $month = FinancialValidations::validateInt($month); + if ($month < 1) { + throw new Exception(ExcelError::NAN()); + } + + return $month; + } + + private static function validateFactor($factor): float + { + $factor = FinancialValidations::validateFloat($factor); + if ($factor <= 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $factor; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php new file mode 100644 index 00000000..b1f0d25c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Dollar.php @@ -0,0 +1,132 @@ +getMessage(); + } + + // Additional parameter validations + if ($fraction < 0) { + return ExcelError::NAN(); + } + if ($fraction == 0) { + return ExcelError::DIV0(); + } + + $dollars = ($fractionalDollar < 0) ? ceil($fractionalDollar) : floor($fractionalDollar); + $cents = fmod($fractionalDollar, 1.0); + $cents /= $fraction; + $cents *= 10 ** ceil(log10($fraction)); + + return $dollars + $cents; + } + + /** + * DOLLARFR. + * + * Converts a dollar price expressed as a decimal number into a dollar price + * expressed as a fraction. + * Fractional dollar numbers are sometimes used for security prices. + * + * Excel Function: + * DOLLARFR(decimal_dollar,fraction) + * + * @param mixed $decimalDollar Decimal Dollar + * Or can be an array of values + * @param mixed $fraction Fraction + * Or can be an array of values + * + * @return array|float|string + */ + public static function fractional($decimalDollar = null, $fraction = 0) + { + if (is_array($decimalDollar) || is_array($fraction)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $decimalDollar, $fraction); + } + + try { + $decimalDollar = FinancialValidations::validateFloat( + Functions::flattenSingleValue($decimalDollar) ?? 0.0 + ); + $fraction = FinancialValidations::validateInt(Functions::flattenSingleValue($fraction)); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Additional parameter validations + if ($fraction < 0) { + return ExcelError::NAN(); + } + if ($fraction == 0) { + return ExcelError::DIV0(); + } + + $dollars = ($decimalDollar < 0.0) ? ceil($decimalDollar) : floor($decimalDollar); + $cents = fmod($decimalDollar, 1); + $cents *= $fraction; + $cents *= 10 ** (-ceil(log10($fraction))); + + return $dollars + $cents; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php new file mode 100644 index 00000000..1b044197 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/FinancialValidations.php @@ -0,0 +1,158 @@ + 4)) { + throw new Exception(ExcelError::NAN()); + } + + return $basis; + } + + /** + * @param mixed $price + */ + public static function validatePrice($price): float + { + $price = self::validateFloat($price); + if ($price < 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $price; + } + + /** + * @param mixed $parValue + */ + public static function validateParValue($parValue): float + { + $parValue = self::validateFloat($parValue); + if ($parValue < 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $parValue; + } + + /** + * @param mixed $yield + */ + public static function validateYield($yield): float + { + $yield = self::validateFloat($yield); + if ($yield < 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $yield; + } + + /** + * @param mixed $discount + */ + public static function validateDiscount($discount): float + { + $discount = self::validateFloat($discount); + if ($discount <= 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $discount; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php new file mode 100644 index 00000000..c7f1f46a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Helpers.php @@ -0,0 +1,58 @@ +format('d') === $date->format('t'); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php new file mode 100644 index 00000000..1cbe2657 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/InterestRate.php @@ -0,0 +1,73 @@ +getMessage(); + } + + if ($nominalRate <= 0 || $periodsPerYear < 1) { + return ExcelError::NAN(); + } + + return ((1 + $nominalRate / $periodsPerYear) ** $periodsPerYear) - 1; + } + + /** + * NOMINAL. + * + * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. + * + * @param mixed $effectiveRate Effective interest rate as a float + * @param mixed $periodsPerYear Integer number of compounding payments per year + * + * @return float|string Result, or a string containing an error + */ + public static function nominal($effectiveRate = 0, $periodsPerYear = 0) + { + $effectiveRate = Functions::flattenSingleValue($effectiveRate); + $periodsPerYear = Functions::flattenSingleValue($periodsPerYear); + + try { + $effectiveRate = FinancialValidations::validateFloat($effectiveRate); + $periodsPerYear = FinancialValidations::validateInt($periodsPerYear); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($effectiveRate <= 0 || $periodsPerYear < 1) { + return ExcelError::NAN(); + } + + // Calculate + return $periodsPerYear * (($effectiveRate + 1) ** (1 / $periodsPerYear) - 1); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php new file mode 100644 index 00000000..95996b4e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/AccruedInterest.php @@ -0,0 +1,151 @@ +getMessage(); + } + + $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenFirstInterestAndSettlement = Functions::scalar(YearFrac::fraction($firstInterest, $settlement, $basis)); + if (!is_numeric($daysBetweenFirstInterestAndSettlement)) { + // return date error + return $daysBetweenFirstInterestAndSettlement; + } + + return $parValue * $rate * $daysBetweenIssueAndSettlement; + } + + /** + * ACCRINTM. + * + * Returns the accrued interest for a security that pays interest at maturity. + * + * Excel Function: + * ACCRINTM(issue,settlement,rate[,par[,basis]]) + * + * @param mixed $issue The security's issue date + * @param mixed $settlement The security's settlement (or maturity) date + * @param mixed $rate The security's annual coupon rate + * @param mixed $parValue The security's par value. + * If you omit parValue, ACCRINT uses $1,000. + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function atMaturity( + $issue, + $settlement, + $rate, + $parValue = 1000, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $issue = Functions::flattenSingleValue($issue); + $settlement = Functions::flattenSingleValue($settlement); + $rate = Functions::flattenSingleValue($rate); + $parValue = ($parValue === null) ? 1000 : Functions::flattenSingleValue($parValue); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $issue = SecurityValidations::validateIssueDate($issue); + $settlement = SecurityValidations::validateSettlementDate($settlement); + SecurityValidations::validateSecurityPeriod($issue, $settlement); + $rate = SecurityValidations::validateRate($rate); + $parValue = SecurityValidations::validateParValue($parValue); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenIssueAndSettlement = Functions::scalar(YearFrac::fraction($issue, $settlement, $basis)); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + + return $parValue * $rate * $daysBetweenIssueAndSettlement; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php new file mode 100644 index 00000000..de1748a1 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Price.php @@ -0,0 +1,284 @@ +getMessage(); + } + + $dsc = Coupons::COUPDAYSNC($settlement, $maturity, $frequency, $basis); + $e = Coupons::COUPDAYS($settlement, $maturity, $frequency, $basis); + $n = Coupons::COUPNUM($settlement, $maturity, $frequency, $basis); + $a = Coupons::COUPDAYBS($settlement, $maturity, $frequency, $basis); + + $baseYF = 1.0 + ($yield / $frequency); + $rfp = 100 * ($rate / $frequency); + $de = $dsc / $e; + + $result = $redemption / $baseYF ** (--$n + $de); + for ($k = 0; $k <= $n; ++$k) { + $result += $rfp / ($baseYF ** ($k + $de)); + } + $result -= $rfp * ($a / $e); + + return $result; + } + + /** + * PRICEDISC. + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $discount The security's discount rate + * @param mixed $redemption The security's redemption value per $100 face value + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function priceDiscounted( + $settlement, + $maturity, + $discount, + $redemption, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); + $redemption = Functions::flattenSingleValue($redemption); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $discount = SecurityValidations::validateDiscount($discount); + $redemption = SecurityValidations::validateRedemption($redemption); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); + } + + /** + * PRICEMAT. + * + * Returns the price per $100 face value of a security that pays interest at maturity. + * + * @param mixed $settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the + * security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $issue The security's issue date + * @param mixed $rate The security's interest rate at date of issue + * @param mixed $yield The security's annual yield + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function priceAtMaturity( + $settlement, + $maturity, + $issue, + $rate, + $yield, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $yield = Functions::flattenSingleValue($yield); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $issue = SecurityValidations::validateIssueDate($issue); + $rate = SecurityValidations::validateRate($rate); + $yield = SecurityValidations::validateYield($yield); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysPerYear = Functions::scalar(Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis)); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / + (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100); + } + + /** + * RECEIVED. + * + * Returns the amount received at maturity for a fully invested Security. + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $investment The amount invested in the security + * @param mixed $discount The security's discount rate + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function received( + $settlement, + $maturity, + $investment, + $discount, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = Functions::flattenSingleValue($investment); + $discount = Functions::flattenSingleValue($discount); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $investment = SecurityValidations::validateFloat($investment); + $discount = SecurityValidations::validateDiscount($discount); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($investment <= 0) { + return ExcelError::NAN(); + } + $daysBetweenSettlementAndMaturity = DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $investment / (1 - ($discount * $daysBetweenSettlementAndMaturity)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php new file mode 100644 index 00000000..f8d86736 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Rates.php @@ -0,0 +1,138 @@ +getMessage(); + } + + if ($price <= 0.0) { + return ExcelError::NAN(); + } + + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (1 - $price / $redemption) / $daysBetweenSettlementAndMaturity; + } + + /** + * INTRATE. + * + * Returns the interest rate for a fully invested security. + * + * Excel Function: + * INTRATE(settlement,maturity,investment,redemption[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $investment the amount invested in the security + * @param mixed $redemption the amount to be received at maturity + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string + */ + public static function interest( + $settlement, + $maturity, + $investment, + $redemption, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $investment = Functions::flattenSingleValue($investment); + $redemption = Functions::flattenSingleValue($redemption); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $investment = SecurityValidations::validateFloat($investment); + $redemption = SecurityValidations::validateRedemption($redemption); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($investment <= 0) { + return ExcelError::NAN(); + } + + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php new file mode 100644 index 00000000..d3196f0f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/SecurityValidations.php @@ -0,0 +1,42 @@ += $maturity) { + throw new Exception(ExcelError::NAN()); + } + } + + /** + * @param mixed $redemption + */ + public static function validateRedemption($redemption): float + { + $redemption = self::validateFloat($redemption); + if ($redemption <= 0.0) { + throw new Exception(ExcelError::NAN()); + } + + return $redemption; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php new file mode 100644 index 00000000..bb2e8ae2 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/Securities/Yields.php @@ -0,0 +1,153 @@ +getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + + /** + * YIELDMAT. + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed $settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security + * is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed $issue The security's issue date + * @param mixed $rate The security's interest rate at date of issue + * @param mixed $price The security's price per $100 face value + * @param mixed $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * + * @return float|string Result, or a string containing an error + */ + public static function yieldAtMaturity( + $settlement, + $maturity, + $issue, + $rate, + $price, + $basis = FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + ) { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $issue = Functions::flattenSingleValue($issue); + $rate = Functions::flattenSingleValue($rate); + $price = Functions::flattenSingleValue($price); + $basis = ($basis === null) + ? FinancialConstants::BASIS_DAYS_PER_YEAR_NASD + : Functions::flattenSingleValue($basis); + + try { + $settlement = SecurityValidations::validateSettlementDate($settlement); + $maturity = SecurityValidations::validateMaturityDate($maturity); + SecurityValidations::validateSecurityPeriod($settlement, $maturity); + $issue = SecurityValidations::validateIssueDate($issue); + $rate = SecurityValidations::validateRate($rate); + $price = SecurityValidations::validatePrice($price); + $basis = SecurityValidations::validateBasis($basis); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysPerYear = Helpers::daysPerYear(DateTimeExcel\DateParts::year($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $settlement, $basis)); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($issue, $maturity, $basis)); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = Functions::scalar(DateTimeExcel\YearFrac::fraction($settlement, $maturity, $basis)); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * + ($daysPerYear / $daysBetweenSettlementAndMaturity); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php new file mode 100644 index 00000000..7ee34f73 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Financial/TreasuryBill.php @@ -0,0 +1,148 @@ +getMessage(); + } + + if ($discount <= 0) { + return ExcelError::NAN(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + Functions::scalar(DateTimeExcel\DateParts::year($maturity)), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return ExcelError::NAN(); + } + + return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + } + + /** + * TBILLPRICE. + * + * Returns the price per $100 face value for a Treasury bill. + * + * @param mixed $settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date + * when the Treasury bill is traded to the buyer. + * @param mixed $maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param mixed $discount The Treasury bill's discount rate + * + * @return float|string Result, or a string containing an error + */ + public static function price($settlement, $maturity, $discount) + { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $discount = Functions::flattenSingleValue($discount); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + $discount = FinancialValidations::validateFloat($discount); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($discount <= 0) { + return ExcelError::NAN(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + Functions::scalar(DateTimeExcel\DateParts::year($maturity)), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return ExcelError::NAN(); + } + + $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); + if ($price < 0.0) { + return ExcelError::NAN(); + } + + return $price; + } + + /** + * TBILLYIELD. + * + * Returns the yield for a Treasury bill. + * + * @param mixed $settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when + * the Treasury bill is traded to the buyer. + * @param mixed $maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param mixed $price The Treasury bill's price per $100 face value + * + * @return float|string + */ + public static function yield($settlement, $maturity, $price) + { + $settlement = Functions::flattenSingleValue($settlement); + $maturity = Functions::flattenSingleValue($maturity); + $price = Functions::flattenSingleValue($price); + + try { + $settlement = FinancialValidations::validateSettlementDate($settlement); + $maturity = FinancialValidations::validateMaturityDate($maturity); + $price = FinancialValidations::validatePrice($price); + } catch (Exception $e) { + return $e->getMessage(); + } + + $daysBetweenSettlementAndMaturity = $maturity - $settlement; + $daysPerYear = Helpers::daysPerYear( + Functions::scalar(DateTimeExcel\DateParts::year($maturity)), + FinancialConstants::BASIS_DAYS_PER_YEAR_ACTUAL + ); + + if ($daysBetweenSettlementAndMaturity > $daysPerYear || $daysBetweenSettlementAndMaturity < 0) { + return ExcelError::NAN(); + } + + return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php index 9b3c66e9..ddf45b23 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaParser.php @@ -61,19 +61,17 @@ class FormulaParser /** * Create a new FormulaParser. * - * @param string $pFormula Formula to parse - * - * @throws Exception + * @param string $formula Formula to parse */ - public function __construct($pFormula = '') + public function __construct($formula = '') { // Check parameters - if ($pFormula === null) { + if ($formula === null) { throw new Exception('Invalid parameter passed: formula'); } // Initialise values - $this->formula = trim($pFormula); + $this->formula = trim($formula); // Parse! $this->parseToTokens(); } @@ -91,19 +89,15 @@ public function getFormula() /** * Get Token. * - * @param int $pId Token id - * - * @throws Exception - * - * @return string + * @param int $id Token id */ - public function getToken($pId = 0) + public function getToken(int $id = 0): FormulaToken { - if (isset($this->tokens[$pId])) { - return $this->tokens[$pId]; + if (isset($this->tokens[$id])) { + return $this->tokens[$id]; } - throw new Exception("Token with id $pId does not exist."); + throw new Exception("Token with id $id does not exist."); } /** @@ -129,7 +123,7 @@ public function getTokens() /** * Parse to tokens. */ - private function parseToTokens() + private function parseToTokens(): void { // No attempt is made to verify formulas; assumes formulas are derived from Excel, where // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. @@ -494,11 +488,13 @@ private function parseToTokens() continue; } - if (!( - (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || + if ( + !( + (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) - )) { + ) + ) { continue; } @@ -506,11 +502,13 @@ private function parseToTokens() continue; } - if (!( - (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || + if ( + !( + (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) - )) { + ) + ) { continue; } @@ -542,12 +540,14 @@ private function parseToTokens() if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); - } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && + } elseif ( + (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || - ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND)) { + ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) + ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); @@ -561,12 +561,14 @@ private function parseToTokens() if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; - } elseif ((($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && + } elseif ( + (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || - ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND)) { + ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) + ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { continue; @@ -577,8 +579,10 @@ private function parseToTokens() continue; } - if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && - $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if ( + $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && + $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING + ) { if (strpos('<>=', substr($token->getValue(), 0, 1)) !== false) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } elseif ($token->getValue() == '&') { @@ -592,8 +596,10 @@ private function parseToTokens() continue; } - if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && - $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if ( + $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && + $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING + ) { if (!is_numeric($token->getValue())) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue()) == 'FALSE') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php index 66618d4a..68e5eead 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/FormulaToken.php @@ -76,16 +76,16 @@ class FormulaToken /** * Create a new FormulaToken. * - * @param string $pValue - * @param string $pTokenType Token type (represented by TOKEN_TYPE_*) - * @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) + * @param string $value + * @param string $tokenType Token type (represented by TOKEN_TYPE_*) + * @param string $tokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) */ - public function __construct($pValue, $pTokenType = self::TOKEN_TYPE_UNKNOWN, $pTokenSubType = self::TOKEN_SUBTYPE_NOTHING) + public function __construct($value, $tokenType = self::TOKEN_TYPE_UNKNOWN, $tokenSubType = self::TOKEN_SUBTYPE_NOTHING) { // Initialise values - $this->value = $pValue; - $this->tokenType = $pTokenType; - $this->tokenSubType = $pTokenSubType; + $this->value = $value; + $this->tokenType = $tokenType; + $this->tokenSubType = $tokenSubType; } /** @@ -103,7 +103,7 @@ public function getValue() * * @param string $value */ - public function setValue($value) + public function setValue($value): void { $this->value = $value; } @@ -123,7 +123,7 @@ public function getTokenType() * * @param string $value */ - public function setTokenType($value) + public function setTokenType($value): void { $this->tokenType = $value; } @@ -143,7 +143,7 @@ public function getTokenSubType() * * @param string $value */ - public function setTokenSubType($value) + public function setTokenSubType($value): void { $this->tokenSubType = $value; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php index 1862b008..dc6ee82e 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Functions.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; +use PhpOffice\PhpSpreadsheet\Shared\Date; class Functions { @@ -13,12 +14,13 @@ class Functions */ const M_2DIVPI = 0.63661977236758134307553505349006; - /** constants */ const COMPATIBILITY_EXCEL = 'Excel'; const COMPATIBILITY_GNUMERIC = 'Gnumeric'; const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc'; + /** Use of RETURNDATE_PHP_NUMERIC is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_PHP_NUMERIC = 'P'; + /** Use of RETURNDATE_UNIX_TIMESTAMP is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_UNIX_TIMESTAMP = 'P'; const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_PHP_DATETIME_OBJECT = 'O'; @@ -38,38 +40,21 @@ class Functions */ protected static $returnDateType = self::RETURNDATE_EXCEL; - /** - * List of error codes. - * - * @var array - */ - protected static $errorCodes = [ - 'null' => '#NULL!', - 'divisionbyzero' => '#DIV/0!', - 'value' => '#VALUE!', - 'reference' => '#REF!', - 'name' => '#NAME?', - 'num' => '#NUM!', - 'na' => '#N/A', - 'gettingdata' => '#GETTING_DATA', - ]; - /** * Set the Compatibility Mode. * - * @category Function Configuration - * * @param string $compatibilityMode Compatibility Mode - * Permitted values are: - * Functions::COMPATIBILITY_EXCEL 'Excel' - * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' - * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + * Permitted values are: + * Functions::COMPATIBILITY_EXCEL 'Excel' + * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' * * @return bool (Success or Failure) */ public static function setCompatibilityMode($compatibilityMode) { - if (($compatibilityMode == self::COMPATIBILITY_EXCEL) || + if ( + ($compatibilityMode == self::COMPATIBILITY_EXCEL) || ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ) { @@ -84,13 +69,11 @@ public static function setCompatibilityMode($compatibilityMode) /** * Return the current Compatibility Mode. * - * @category Function Configuration - * * @return string Compatibility Mode - * Possible Return values are: - * Functions::COMPATIBILITY_EXCEL 'Excel' - * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' - * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + * Possible Return values are: + * Functions::COMPATIBILITY_EXCEL 'Excel' + * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' */ public static function getCompatibilityMode() { @@ -98,21 +81,20 @@ public static function getCompatibilityMode() } /** - * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object). - * - * @category Function Configuration + * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP DateTime Object). * * @param string $returnDateType Return Date Format - * Permitted values are: - * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' - * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' - * Functions::RETURNDATE_EXCEL 'E' + * Permitted values are: + * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' + * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' + * Functions::RETURNDATE_EXCEL 'E' * * @return bool Success or failure */ public static function setReturnDateType($returnDateType) { - if (($returnDateType == self::RETURNDATE_UNIX_TIMESTAMP) || + if ( + ($returnDateType == self::RETURNDATE_UNIX_TIMESTAMP) || ($returnDateType == self::RETURNDATE_PHP_DATETIME_OBJECT) || ($returnDateType == self::RETURNDATE_EXCEL) ) { @@ -127,13 +109,11 @@ public static function setReturnDateType($returnDateType) /** * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object). * - * @category Function Configuration - * * @return string Return Date Format - * Possible Return values are: - * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' - * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' - * Functions::RETURNDATE_EXCEL 'E' + * Possible Return values are: + * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' + * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' + * Functions::RETURNDATE_EXCEL ' 'E' */ public static function getReturnDateType() { @@ -143,8 +123,6 @@ public static function getReturnDateType() /** * DUMMY. * - * @category Error Returns - * * @return string #Not Yet Implemented */ public static function DUMMY() @@ -152,34 +130,92 @@ public static function DUMMY() return '#Not Yet Implemented'; } - /** - * DIV0. - * - * @category Error Returns - * - * @return string #Not Yet Implemented - */ - public static function DIV0() + public static function isMatrixValue($idx) + { + return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0); + } + + public static function isValue($idx) { - return self::$errorCodes['divisionbyzero']; + return substr_count($idx, '.') === 0; + } + + public static function isCellValue($idx) + { + return substr_count($idx, '.') > 1; + } + + public static function ifCondition($condition) + { + $condition = self::flattenSingleValue($condition); + + if ($condition === '') { + return '=""'; + } + if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='])) { + $condition = self::operandSpecialHandling($condition); + if (is_bool($condition)) { + return '=' . ($condition ? 'TRUE' : 'FALSE'); + } elseif (!is_numeric($condition)) { + if ($condition !== '""') { // Not an empty string + // Escape any quotes in the string value + $condition = preg_replace('/"/ui', '""', $condition); + } + $condition = Calculation::wrapResult(strtoupper($condition)); + } + + return str_replace('""""', '""', '=' . $condition); + } + preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches); + [, $operator, $operand] = $matches; + + $operand = self::operandSpecialHandling($operand); + if (is_numeric(trim($operand, '"'))) { + $operand = trim($operand, '"'); + } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { + $operand = str_replace('"', '""', $operand); + $operand = Calculation::wrapResult(strtoupper($operand)); + } + + return str_replace('""""', '""', $operator . $operand); + } + + private static function operandSpecialHandling($operand) + { + if (is_numeric($operand) || is_bool($operand)) { + return $operand; + } elseif (strtoupper($operand) === Calculation::getTRUE() || strtoupper($operand) === Calculation::getFALSE()) { + return strtoupper($operand); + } + + // Check for percentage + if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $operand)) { + return ((float) rtrim($operand, '%')) / 100; + } + + // Check for dates + if (($dateValueOperand = Date::stringToExcel($operand)) !== false) { + return $dateValueOperand; + } + + return $operand; } /** - * NA. + * NULL. * - * Excel Function: - * =NA() + * Returns the error value #NULL! * - * Returns the error value #N/A - * #N/A is the error value that means "no value is available." + * @Deprecated 1.23.0 * - * @category Logical Functions + * @return string #NULL! * - * @return string #N/A! + *@see Information\ExcelError::null() + * Use the null() method in the Information\Error class instead */ - public static function NA() + public static function null() { - return self::$errorCodes['na']; + return Information\ExcelError::null(); } /** @@ -187,27 +223,16 @@ public static function NA() * * Returns the error value #NUM! * - * @category Error Returns + * @Deprecated 1.23.0 * * @return string #NUM! - */ - public static function NAN() - { - return self::$errorCodes['num']; - } - - /** - * NAME. - * - * Returns the error value #NAME? - * - * @category Error Returns * - * @return string #NAME? + * @see Information\ExcelError::NAN() + * Use the NAN() method in the Information\Error class instead */ - public static function NAME() + public static function NAN() { - return self::$errorCodes['name']; + return Information\ExcelError::NAN(); } /** @@ -215,27 +240,37 @@ public static function NAME() * * Returns the error value #REF! * - * @category Error Returns + * @Deprecated 1.23.0 * * @return string #REF! + * + * @see Information\ExcelError::REF() + * Use the REF() method in the Information\Error class instead */ public static function REF() { - return self::$errorCodes['reference']; + return Information\ExcelError::REF(); } /** - * NULL. + * NA. * - * Returns the error value #NULL! + * Excel Function: + * =NA() + * + * Returns the error value #N/A + * #N/A is the error value that means "no value is available." * - * @category Error Returns + * @Deprecated 1.23.0 * - * @return string #NULL! + * @return string #N/A! + * + * @see Information\ExcelError::NA() + * Use the NA() method in the Information\Error class instead */ - public static function null() + public static function NA() { - return self::$errorCodes['null']; + return Information\ExcelError::NA(); } /** @@ -243,56 +278,48 @@ public static function null() * * Returns the error value #VALUE! * - * @category Error Returns + * @Deprecated 1.23.0 * * @return string #VALUE! + * + * @see Information\ExcelError::VALUE() + * Use the VALUE() method in the Information\Error class instead */ public static function VALUE() { - return self::$errorCodes['value']; + return Information\ExcelError::VALUE(); } - public static function isMatrixValue($idx) - { - return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0); - } - - public static function isValue($idx) - { - return substr_count($idx, '.') == 0; - } - - public static function isCellValue($idx) + /** + * NAME. + * + * Returns the error value #NAME? + * + * @Deprecated 1.23.0 + * + * @return string #NAME? + * + * @see Information\ExcelError::NAME() + * Use the NAME() method in the Information\Error class instead + */ + public static function NAME() { - return substr_count($idx, '.') > 1; + return Information\ExcelError::NAME(); } - public static function ifCondition($condition) + /** + * DIV0. + * + * @Deprecated 1.23.0 + * + * @return string #Not Yet Implemented + * + *@see Information\ExcelError::DIV0() + * Use the DIV0() method in the Information\Error class instead + */ + public static function DIV0() { - $condition = self::flattenSingleValue($condition); - - if ($condition === '') { - $condition = '=""'; - } - - if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='])) { - if (!is_numeric($condition)) { - $condition = Calculation::wrapResult(strtoupper($condition)); - } - - return str_replace('""""', '""', '=' . $condition); - } - preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches); - [, $operator, $operand] = $matches; - - if (is_numeric(trim($operand, '"'))) { - $operand = trim($operand, '"'); - } elseif (!is_numeric($operand)) { - $operand = str_replace('"', '""', $operand); - $operand = Calculation::wrapResult(strtoupper($operand)); - } - - return str_replace('""""', '""', $operator . $operand); + return Information\ExcelError::DIV0(); } /** @@ -300,21 +327,16 @@ public static function ifCondition($condition) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @return array|int|string + * + * @see Information\ExcelError::type() + * Use the type() method in the Information\Error class instead */ public static function errorType($value = '') { - $value = self::flattenSingleValue($value); - - $i = 1; - foreach (self::$errorCodes as $errorCode) { - if ($value === $errorCode) { - return $i; - } - ++$i; - } - - return self::NA(); + return Information\ExcelError::type($value); } /** @@ -322,15 +344,16 @@ public static function errorType($value = '') * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isBlank() + * Use the isBlank() method in the Information\Value class instead + * + * @return array|bool */ public static function isBlank($value = null) { - if ($value !== null) { - $value = self::flattenSingleValue($value); - } - - return $value === null; + return Information\Value::isBlank($value); } /** @@ -338,13 +361,16 @@ public static function isBlank($value = null) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isErr() + * Use the isErr() method in the Information\Value class instead + * + * @return array|bool */ public static function isErr($value = '') { - $value = self::flattenSingleValue($value); - - return self::isError($value) && (!self::isNa(($value))); + return Information\ErrorValue::isErr($value); } /** @@ -352,17 +378,16 @@ public static function isErr($value = '') * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isError() + * Use the isError() method in the Information\Value class instead + * + * @return array|bool */ public static function isError($value = '') { - $value = self::flattenSingleValue($value); - - if (!is_string($value)) { - return false; - } - - return in_array($value, self::$errorCodes); + return Information\ErrorValue::isError($value); } /** @@ -370,13 +395,16 @@ public static function isError($value = '') * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isNa() + * Use the isNa() method in the Information\Value class instead + * + * @return array|bool */ public static function isNa($value = '') { - $value = self::flattenSingleValue($value); - - return $value === self::NA(); + return Information\ErrorValue::isNa($value); } /** @@ -384,19 +412,16 @@ public static function isNa($value = '') * * @param mixed $value Value to check * - * @return bool|string + * @Deprecated 1.23.0 + * + * @see Information\Value::isEven() + * Use the isEven() method in the Information\Value class instead + * + * @return array|bool|string */ public static function isEven($value = null) { - $value = self::flattenSingleValue($value); - - if ($value === null) { - return self::NAME(); - } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { - return self::VALUE(); - } - - return $value % 2 == 0; + return Information\Value::isEven($value); } /** @@ -404,19 +429,16 @@ public static function isEven($value = null) * * @param mixed $value Value to check * - * @return bool|string + * @Deprecated 1.23.0 + * + * @see Information\Value::isOdd() + * Use the isOdd() method in the Information\Value class instead + * + * @return array|bool|string */ public static function isOdd($value = null) { - $value = self::flattenSingleValue($value); - - if ($value === null) { - return self::NAME(); - } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { - return self::VALUE(); - } - - return abs($value) % 2 == 1; + return Information\Value::isOdd($value); } /** @@ -424,17 +446,16 @@ public static function isOdd($value = null) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isNumber() + * Use the isNumber() method in the Information\Value class instead + * + * @return array|bool */ public static function isNumber($value = null) { - $value = self::flattenSingleValue($value); - - if (is_string($value)) { - return false; - } - - return is_numeric($value); + return Information\Value::isNumber($value); } /** @@ -442,13 +463,16 @@ public static function isNumber($value = null) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isLogical() + * Use the isLogical() method in the Information\Value class instead + * + * @return array|bool */ public static function isLogical($value = null) { - $value = self::flattenSingleValue($value); - - return is_bool($value); + return Information\Value::isLogical($value); } /** @@ -456,13 +480,16 @@ public static function isLogical($value = null) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isText() + * Use the isText() method in the Information\Value class instead + * + * @return array|bool */ public static function isText($value = null) { - $value = self::flattenSingleValue($value); - - return is_string($value) && !self::isError($value); + return Information\Value::isText($value); } /** @@ -470,11 +497,16 @@ public static function isText($value = null) * * @param mixed $value Value to check * - * @return bool + * @Deprecated 1.23.0 + * + * @see Information\Value::isNonText() + * Use the isNonText() method in the Information\Value class instead + * + * @return array|bool */ public static function isNonText($value = null) { - return !self::isText($value); + return Information\Value::isNonText($value); } /** @@ -482,9 +514,14 @@ public static function isNonText($value = null) * * Returns a value converted to a number * + * @Deprecated 1.23.0 + * + * @see Information\Value::asNumber() + * Use the asNumber() method in the Information\Value class instead + * * @param null|mixed $value The value you want converted * - * @return number N converts values listed in the following table + * @return number|string N converts values listed in the following table * If value is or refers to N returns * A number That number * A date The serial number of that date @@ -495,27 +532,7 @@ public static function isNonText($value = null) */ public static function n($value = null) { - while (is_array($value)) { - $value = array_shift($value); - } - - switch (gettype($value)) { - case 'double': - case 'float': - case 'integer': - return $value; - case 'boolean': - return (int) $value; - case 'string': - // Errors - if ((strlen($value) > 0) && ($value[0] == '#')) { - return $value; - } - - break; - } - - return 0; + return Information\Value::asNumber($value); } /** @@ -523,6 +540,11 @@ public static function n($value = null) * * Returns a number that identifies the type of a value * + * @Deprecated 1.23.0 + * + * @see Information\Value::type() + * Use the type() method in the Information\Value class instead + * * @param null|mixed $value The value you want tested * * @return number N converts values listed in the following table @@ -535,45 +557,13 @@ public static function n($value = null) */ public static function TYPE($value = null) { - $value = self::flattenArrayIndexed($value); - if (is_array($value) && (count($value) > 1)) { - end($value); - $a = key($value); - // Range of cells is an error - if (self::isCellValue($a)) { - return 16; - // Test for Matrix - } elseif (self::isMatrixValue($a)) { - return 64; - } - } elseif (empty($value)) { - // Empty Cell - return 1; - } - $value = self::flattenSingleValue($value); - - if (($value === null) || (is_float($value)) || (is_int($value))) { - return 1; - } elseif (is_bool($value)) { - return 4; - } elseif (is_array($value)) { - return 64; - } elseif (is_string($value)) { - // Errors - if ((strlen($value) > 0) && ($value[0] == '#')) { - return 16; - } - - return 2; - } - - return 0; + return Information\Value::type($value); } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * - * @param array $array Array to be flattened + * @param array|mixed $array Array to be flattened * * @return array Flattened array */ @@ -603,10 +593,28 @@ public static function flattenArray($array) return $arrayValues; } + /** + * @param mixed $value + * + * @return null|mixed + */ + public static function scalar($value) + { + if (!is_array($value)) { + return $value; + } + + do { + $value = array_pop($value); + } while (is_array($value)); + + return $value; + } + /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * - * @param array $array Array to be flattened + * @param array|mixed $array Array to be flattened * * @return array Flattened array */ @@ -655,26 +663,52 @@ public static function flattenSingleValue($value = '') /** * ISFORMULA. * + * @Deprecated 1.23.0 + * + * @see Information\Value::isFormula() + * Use the isFormula() method in the Information\Value class instead + * * @param mixed $cellReference The cell to check - * @param Cell $pCell The current cell (containing this formula) + * @param ?Cell $cell The current cell (containing this formula) * - * @return bool|string + * @return array|bool|string */ - public static function isFormula($cellReference = '', Cell $pCell = null) + public static function isFormula($cellReference = '', ?Cell $cell = null) + { + return Information\Value::isFormula($cellReference, $cell); + } + + public static function expandDefinedName(string $coordinate, Cell $cell): string { - if ($pCell === null) { - return self::REF(); + $worksheet = $cell->getWorksheet(); + $spreadsheet = $worksheet->getParent(); + // Uppercase coordinate + $pCoordinatex = strtoupper($coordinate); + // Eliminate leading equal sign + $pCoordinatex = (string) preg_replace('/^=/', '', $pCoordinatex); + $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); + if ($defined !== null) { + $worksheet2 = $defined->getWorkSheet(); + if (!$defined->isFormula() && $worksheet2 !== null) { + $coordinate = "'" . $worksheet2->getTitle() . "'!" . + (string) preg_replace('/^=/', '', $defined->getValue()); + } } - preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); + return $coordinate; + } - $cellReference = $matches[6] . $matches[7]; - $worksheetName = trim($matches[3], "'"); + public static function trimTrailingRange(string $coordinate): string + { + return (string) preg_replace('/:[\\w\$]+$/', '', $coordinate); + } - $worksheet = (!empty($worksheetName)) - ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName) - : $pCell->getWorksheet(); + public static function trimSheetFromCellReference(string $coordinate): string + { + while (strpos($coordinate, '!') !== false) { + $coordinate = substr($coordinate, strpos($coordinate, '!') + 1); + } - return $worksheet->getCell($cellReference)->isFormula(); + return $coordinate; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ErrorValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ErrorValue.php new file mode 100644 index 00000000..cffad6a6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/ErrorValue.php @@ -0,0 +1,71 @@ + '#NULL!', + 'divisionbyzero' => '#DIV/0!', + 'value' => '#VALUE!', + 'reference' => '#REF!', + 'name' => '#NAME?', + 'num' => '#NUM!', + 'na' => '#N/A', + 'gettingdata' => '#GETTING_DATA', + 'spill' => '#SPILL!', + ]; + + /** + * ERROR_TYPE. + * + * @param mixed $value Value to check + * + * @return array|int|string + */ + public static function type($value = '') + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + $i = 1; + foreach (self::$errorCodes as $errorCode) { + if ($value === $errorCode) { + return $i; + } + ++$i; + } + + if ($value === self::CALC()) { + return 14; + } + + return self::NA(); + } + + /** + * NULL. + * + * Returns the error value #NULL! + * + * @return string #NULL! + */ + public static function null() + { + return self::$errorCodes['null']; + } + + /** + * NaN. + * + * Returns the error value #NUM! + * + * @return string #NUM! + */ + public static function NAN() + { + return self::$errorCodes['num']; + } + + /** + * REF. + * + * Returns the error value #REF! + * + * @return string #REF! + */ + public static function REF() + { + return self::$errorCodes['reference']; + } + + /** + * NA. + * + * Excel Function: + * =NA() + * + * Returns the error value #N/A + * #N/A is the error value that means "no value is available." + * + * @return string #N/A! + */ + public static function NA() + { + return self::$errorCodes['na']; + } + + /** + * VALUE. + * + * Returns the error value #VALUE! + * + * @return string #VALUE! + */ + public static function VALUE() + { + return self::$errorCodes['value']; + } + + /** + * NAME. + * + * Returns the error value #NAME? + * + * @return string #NAME? + */ + public static function NAME() + { + return self::$errorCodes['name']; + } + + /** + * DIV0. + * + * @return string #DIV/0! + */ + public static function DIV0() + { + return self::$errorCodes['divisionbyzero']; + } + + /** + * CALC. + * + * @return string #Not Yet Implemented + */ + public static function CALC() + { + return '#CALC!'; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php new file mode 100644 index 00000000..0ac6b669 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Information/Value.php @@ -0,0 +1,328 @@ +getCoordinate()) { + return false; + } + + $cellValue = Functions::trimTrailingRange($value); + if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/ui', $cellValue) === 1) { + [$worksheet, $cellValue] = Worksheet::extractSheetTitle($cellValue, true); + if (!empty($worksheet) && $cell->getWorksheet()->getParent()->getSheetByName($worksheet) === null) { + return false; + } + [$column, $row] = Coordinate::indexesFromString($cellValue); + if ($column > 16384 || $row > 1048576) { + return false; + } + + return true; + } + + $namedRange = $cell->getWorksheet()->getParent()->getNamedRange($value); + + return $namedRange instanceof NamedRange; + } + + /** + * IS_EVEN. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isEven($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + if ($value === null) { + return ExcelError::NAME(); + } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { + return ExcelError::VALUE(); + } + + return ((int) fmod($value, 2)) === 0; + } + + /** + * IS_ODD. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isOdd($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + if ($value === null) { + return ExcelError::NAME(); + } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { + return ExcelError::VALUE(); + } + + return ((int) fmod($value, 2)) !== 0; + } + + /** + * IS_NUMBER. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isNumber($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + if (is_string($value)) { + return false; + } + + return is_numeric($value); + } + + /** + * IS_LOGICAL. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isLogical($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + return is_bool($value); + } + + /** + * IS_TEXT. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isText($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + return is_string($value) && !ErrorValue::isError($value); + } + + /** + * IS_NONTEXT. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|bool + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function isNonText($value = null) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + return !self::isText($value); + } + + /** + * ISFORMULA. + * + * @param mixed $cellReference The cell to check + * @param ?Cell $cell The current cell (containing this formula) + * + * @return array|bool|string + */ + public static function isFormula($cellReference = '', ?Cell $cell = null) + { + if ($cell === null) { + return ExcelError::REF(); + } + + $fullCellReference = Functions::expandDefinedName((string) $cellReference, $cell); + + if (strpos($cellReference, '!') !== false) { + $cellReference = Functions::trimSheetFromCellReference($cellReference); + $cellReferences = Coordinate::extractAllCellReferencesInRange($cellReference); + if (count($cellReferences) > 1) { + return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $cellReferences, $cell); + } + } + + $fullCellReference = Functions::trimTrailingRange($fullCellReference); + + preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $fullCellReference, $matches); + + $fullCellReference = $matches[6] . $matches[7]; + $worksheetName = str_replace("''", "'", trim($matches[2], "'")); + + $worksheet = (!empty($worksheetName)) + ? $cell->getWorksheet()->getParent()->getSheetByName($worksheetName) + : $cell->getWorksheet(); + + return ($worksheet !== null) ? $worksheet->getCell($fullCellReference)->isFormula() : ExcelError::REF(); + } + + /** + * N. + * + * Returns a value converted to a number + * + * @param null|mixed $value The value you want converted + * + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number That number value + * A date The Excel serialized number of that date + * TRUE 1 + * FALSE 0 + * An error value The error value + * Anything else 0 + */ + public static function asNumber($value = null) + { + while (is_array($value)) { + $value = array_shift($value); + } + + switch (gettype($value)) { + case 'double': + case 'float': + case 'integer': + return $value; + case 'boolean': + return (int) $value; + case 'string': + // Errors + if ((strlen($value) > 0) && ($value[0] == '#')) { + return $value; + } + + break; + } + + return 0; + } + + /** + * TYPE. + * + * Returns a number that identifies the type of a value + * + * @param null|mixed $value The value you want tested + * + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number 1 + * Text 2 + * Logical Value 4 + * An error value 16 + * Array or Matrix 64 + */ + public static function type($value = null) + { + $value = Functions::flattenArrayIndexed($value); + if (is_array($value) && (count($value) > 1)) { + end($value); + $a = key($value); + // Range of cells is an error + if (Functions::isCellValue($a)) { + return 16; + // Test for Matrix + } elseif (Functions::isMatrixValue($a)) { + return 64; + } + } elseif (empty($value)) { + // Empty Cell + return 1; + } + + $value = Functions::flattenSingleValue($value); + if (($value === null) || (is_float($value)) || (is_int($value))) { + return 1; + } elseif (is_bool($value)) { + return 4; + } elseif (is_array($value)) { + return 64; + } elseif (is_string($value)) { + // Errors + if ((strlen($value) > 0) && ($value[0] == '#')) { + return 16; + } + + return 2; + } + + return 0; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php new file mode 100644 index 00000000..8b53464f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Internal/MakeMatrix.php @@ -0,0 +1,11 @@ + 0) && ($returnValue == $argCount); + return Logical\Operations::logicalAnd(...$args); } /** @@ -120,10 +92,13 @@ public static function logicalAnd(...$args) * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value * - * @category Logical Functions + * @Deprecated 1.17.0 + * + * @see Logical\Operations::logicalOr() + * Use the logicalOr() method in the Logical\Operations class instead * * @param mixed $args Data values * @@ -131,29 +106,15 @@ public static function logicalAnd(...$args) */ public static function logicalOr(...$args) { - $args = Functions::flattenArray($args); - - if (count($args) == 0) { - return Functions::VALUE(); - } - - $args = array_filter($args, function ($value) { - return $value !== null || (is_string($value) && trim($value) == ''); - }); - - $returnValue = self::countTrueValues($args); - if (is_string($returnValue)) { - return $returnValue; - } - - return $returnValue > 0; + return Logical\Operations::logicalOr(...$args); } /** * LOGICAL_XOR. * * Returns the Exclusive Or logical operation for one or more supplied conditions. - * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, and FALSE otherwise. + * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, + * and FALSE otherwise. * * Excel Function: * =XOR(logical1[,logical2[, ...]]) @@ -163,10 +124,13 @@ public static function logicalOr(...$args) * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @Deprecated 1.17.0 * - * @category Logical Functions + * @see Logical\Operations::logicalXor() + * Use the logicalXor() method in the Logical\Operations class instead * * @param mixed $args Data values * @@ -174,22 +138,7 @@ public static function logicalOr(...$args) */ public static function logicalXor(...$args) { - $args = Functions::flattenArray($args); - - if (count($args) == 0) { - return Functions::VALUE(); - } - - $args = array_filter($args, function ($value) { - return $value !== null || (is_string($value) && trim($value) == ''); - }); - - $returnValue = self::countTrueValues($args); - if (is_string($returnValue)) { - return $returnValue; - } - - return $returnValue % 2 == 1; + return Logical\Operations::logicalXor(...$args); } /** @@ -204,31 +153,21 @@ public static function logicalXor(...$args) * * Boolean arguments are treated as True or False as appropriate * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False - * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds - * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @Deprecated 1.17.0 * - * @category Logical Functions + * @see Logical\Operations::NOT() + * Use the NOT() method in the Logical\Operations class instead * * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE * - * @return bool|string the boolean inverse of the argument + * @return array|bool|string the boolean inverse of the argument */ public static function NOT($logical = false) { - $logical = Functions::flattenSingleValue($logical); - - if (is_string($logical)) { - $logical = strtoupper($logical); - if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { - return false; - } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { - return true; - } - - return Functions::VALUE(); - } - - return !$logical; + return Logical\Operations::NOT($logical); } /** @@ -244,19 +183,22 @@ public static function NOT($logical = false) * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. * This argument can use any comparison calculation operator. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. - * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE, - * then the IF function returns the text "Within budget" - * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use - * the logical value TRUE for this argument. + * For example, if this argument is the text string "Within budget" and the condition argument + * evaluates to TRUE, then the IF function returns the text "Within budget" + * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). + * To display the word TRUE, use the logical value TRUE for this argument. * ReturnIfTrue can be another formula. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. - * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE, - * then the IF function returns the text "Over budget". + * For example, if this argument is the text string "Over budget" and the condition argument + * evaluates to FALSE, then the IF function returns the text "Over budget". * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. * ReturnIfFalse can be another formula. * - * @category Logical Functions + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::statementIf() + * Use the statementIf() method in the Logical\Conditional class instead * * @param mixed $condition Condition to evaluate * @param mixed $returnIfTrue Value to return when condition is true @@ -266,15 +208,7 @@ public static function NOT($logical = false) */ public static function statementIf($condition = true, $returnIfTrue = 0, $returnIfFalse = false) { - if (Functions::isError($condition)) { - return $condition; - } - - $condition = ($condition === null) ? true : (bool) Functions::flattenSingleValue($condition); - $returnIfTrue = ($returnIfTrue === null) ? 0 : Functions::flattenSingleValue($returnIfTrue); - $returnIfFalse = ($returnIfFalse === null) ? false : Functions::flattenSingleValue($returnIfFalse); - - return ($condition) ? $returnIfTrue : $returnIfFalse; + return Logical\Conditional::statementIf($condition, $returnIfTrue, $returnIfFalse); } /** @@ -288,13 +222,19 @@ public static function statementIf($condition = true, $returnIfTrue = 0, $return * Expression * The expression to compare to a list of values. * value1, value2, ... value_n - * A list of values that are compared to expression. The SWITCH function is looking for the first value that matches the expression. + * A list of values that are compared to expression. + * The SWITCH function is looking for the first value that matches the expression. * result1, result2, ... result_n - * A list of results. The SWITCH function returns the corresponding result when a value matches expression. + * A list of results. The SWITCH function returns the corresponding result when a value + * matches expression. * default - * Optional. It is the default to return if expression does not match any of the values (value1, value2, ... value_n). + * Optional. It is the default to return if expression does not match any of the values + * (value1, value2, ... value_n). + * + * @Deprecated 1.17.0 * - * @category Logical Functions + * @see Logical\Conditional::statementSwitch() + * Use the statementSwitch() method in the Logical\Conditional class instead * * @param mixed $arguments Statement arguments * @@ -302,33 +242,7 @@ public static function statementIf($condition = true, $returnIfTrue = 0, $return */ public static function statementSwitch(...$arguments) { - $result = Functions::VALUE(); - - if (count($arguments) > 0) { - $targetValue = Functions::flattenSingleValue($arguments[0]); - $argc = count($arguments) - 1; - $switchCount = floor($argc / 2); - $switchSatisfied = false; - $hasDefaultClause = $argc % 2 !== 0; - $defaultClause = $argc % 2 === 0 ? null : $arguments[count($arguments) - 1]; - - if ($switchCount) { - for ($index = 0; $index < $switchCount; ++$index) { - if ($targetValue == $arguments[$index * 2 + 1]) { - $result = $arguments[$index * 2 + 2]; - $switchSatisfied = true; - - break; - } - } - } - - if (!$switchSatisfied) { - $result = $hasDefaultClause ? $defaultClause : Functions::NA(); - } - } - - return $result; + return Logical\Conditional::statementSwitch(...$arguments); } /** @@ -337,7 +251,10 @@ public static function statementSwitch(...$arguments) * Excel Function: * =IFERROR(testValue,errorpart) * - * @category Logical Functions + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFERROR() + * Use the IFERROR() method in the Logical\Conditional class instead * * @param mixed $testValue Value to check, is also the value returned when no error * @param mixed $errorpart Value to return when testValue is an error condition @@ -346,10 +263,7 @@ public static function statementSwitch(...$arguments) */ public static function IFERROR($testValue = '', $errorpart = '') { - $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); - $errorpart = ($errorpart === null) ? '' : Functions::flattenSingleValue($errorpart); - - return self::statementIf(Functions::isError($testValue), $errorpart, $testValue); + return Logical\Conditional::IFERROR($testValue, $errorpart); } /** @@ -358,7 +272,10 @@ public static function IFERROR($testValue = '', $errorpart = '') * Excel Function: * =IFNA(testValue,napart) * - * @category Logical Functions + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFNA() + * Use the IFNA() method in the Logical\Conditional class instead * * @param mixed $testValue Value to check, is also the value returned when not an NA * @param mixed $napart Value to return when testValue is an NA condition @@ -367,9 +284,31 @@ public static function IFERROR($testValue = '', $errorpart = '') */ public static function IFNA($testValue = '', $napart = '') { - $testValue = ($testValue === null) ? '' : Functions::flattenSingleValue($testValue); - $napart = ($napart === null) ? '' : Functions::flattenSingleValue($napart); + return Logical\Conditional::IFNA($testValue, $napart); + } - return self::statementIf(Functions::isNa($testValue), $napart, $testValue); + /** + * IFS. + * + * Excel Function: + * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) + * + * testValue1 ... testValue_n + * Conditions to Evaluate + * returnIfTrue1 ... returnIfTrue_n + * Value returned if corresponding testValue (nth) was true + * + * @Deprecated 1.17.0 + * + * @see Logical\Conditional::IFS() + * Use the IFS() method in the Logical\Conditional class instead + * + * @param mixed ...$arguments Statement arguments + * + * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true + */ + public static function IFS(...$arguments) + { + return Logical\Conditional::IFS(...$arguments); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php new file mode 100644 index 00000000..8f1e9354 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Boolean.php @@ -0,0 +1,36 @@ + 0) { + $targetValue = Functions::flattenSingleValue($arguments[0]); + $argc = count($arguments) - 1; + $switchCount = floor($argc / 2); + $hasDefaultClause = $argc % 2 !== 0; + $defaultClause = $argc % 2 === 0 ? null : $arguments[$argc]; + + $switchSatisfied = false; + if ($switchCount > 0) { + for ($index = 0; $index < $switchCount; ++$index) { + if ($targetValue == $arguments[$index * 2 + 1]) { + $result = $arguments[$index * 2 + 2]; + $switchSatisfied = true; + + break; + } + } + } + + if ($switchSatisfied !== true) { + $result = $hasDefaultClause ? $defaultClause : ExcelError::NA(); + } + } + + return $result; + } + + /** + * IFERROR. + * + * Excel Function: + * =IFERROR(testValue,errorpart) + * + * @param mixed $testValue Value to check, is also the value returned when no error + * Or can be an array of values + * @param mixed $errorpart Value to return when testValue is an error condition + * Note that this can be an array value to be returned + * + * @return mixed The value of errorpart or testValue determined by error condition + * If an array of values is passed as the $testValue argument, then the returned result will also be + * an array with the same dimensions + */ + public static function IFERROR($testValue = '', $errorpart = '') + { + if (is_array($testValue)) { + return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $errorpart); + } + + $errorpart = $errorpart ?? ''; + + return self::statementIf(ErrorValue::isError($testValue), $errorpart, $testValue); + } + + /** + * IFNA. + * + * Excel Function: + * =IFNA(testValue,napart) + * + * @param mixed $testValue Value to check, is also the value returned when not an NA + * Or can be an array of values + * @param mixed $napart Value to return when testValue is an NA condition + * Note that this can be an array value to be returned + * + * @return mixed The value of errorpart or testValue determined by error condition + * If an array of values is passed as the $testValue argument, then the returned result will also be + * an array with the same dimensions + */ + public static function IFNA($testValue = '', $napart = '') + { + if (is_array($testValue)) { + return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $testValue, $napart); + } + + $napart = $napart ?? ''; + + return self::statementIf(ErrorValue::isNa($testValue), $napart, $testValue); + } + + /** + * IFS. + * + * Excel Function: + * =IFS(testValue1;returnIfTrue1;testValue2;returnIfTrue2;...;testValue_n;returnIfTrue_n) + * + * testValue1 ... testValue_n + * Conditions to Evaluate + * returnIfTrue1 ... returnIfTrue_n + * Value returned if corresponding testValue (nth) was true + * + * @param mixed ...$arguments Statement arguments + * Note that this can be an array value to be returned + * + * @return mixed|string The value of returnIfTrue_n, if testValue_n was true. #N/A if none of testValues was true + */ + public static function IFS(...$arguments) + { + $argumentCount = count($arguments); + + if ($argumentCount % 2 != 0) { + return ExcelError::NA(); + } + // We use instance of Exception as a falseValue in order to prevent string collision with value in cell + $falseValueException = new Exception(); + for ($i = 0; $i < $argumentCount; $i += 2) { + $testValue = ($arguments[$i] === null) ? '' : Functions::flattenSingleValue($arguments[$i]); + $returnIfTrue = ($arguments[$i + 1] === null) ? '' : $arguments[$i + 1]; + $result = self::statementIf($testValue, $returnIfTrue, $falseValueException); + + if ($result !== $falseValueException) { + return $result; + } + } + + return ExcelError::NA(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php new file mode 100644 index 00000000..2e2faa13 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Logical/Operations.php @@ -0,0 +1,207 @@ + 0) && ($returnValue == $argCount); + } + + /** + * LOGICAL_OR. + * + * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. + * + * Excel Function: + * =OR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $args Data values + * + * @return bool|string the logical OR of the arguments + */ + public static function logicalOr(...$args) + { + $args = Functions::flattenArray($args); + + if (count($args) == 0) { + return ExcelError::VALUE(); + } + + $args = array_filter($args, function ($value) { + return $value !== null || (is_string($value) && trim($value) == ''); + }); + + $returnValue = self::countTrueValues($args); + if (is_string($returnValue)) { + return $returnValue; + } + + return $returnValue > 0; + } + + /** + * LOGICAL_XOR. + * + * Returns the Exclusive Or logical operation for one or more supplied conditions. + * i.e. the Xor function returns TRUE if an odd number of the supplied conditions evaluate to TRUE, + * and FALSE otherwise. + * + * Excel Function: + * =XOR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $args Data values + * + * @return bool|string the logical XOR of the arguments + */ + public static function logicalXor(...$args) + { + $args = Functions::flattenArray($args); + + if (count($args) == 0) { + return ExcelError::VALUE(); + } + + $args = array_filter($args, function ($value) { + return $value !== null || (is_string($value) && trim($value) == ''); + }); + + $returnValue = self::countTrueValues($args); + if (is_string($returnValue)) { + return $returnValue; + } + + return $returnValue % 2 == 1; + } + + /** + * NOT. + * + * Returns the boolean inverse of the argument. + * + * Excel Function: + * =NOT(logical) + * + * The argument must evaluate to a logical value such as TRUE or FALSE + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string + * holds the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE + * Or can be an array of values + * + * @return array|bool|string the boolean inverse of the argument + * If an array of values is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function NOT($logical = false) + { + if (is_array($logical)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $logical); + } + + if (is_string($logical)) { + $logical = mb_strtoupper($logical, 'UTF-8'); + if (($logical == 'TRUE') || ($logical == Calculation::getTRUE())) { + return false; + } elseif (($logical == 'FALSE') || ($logical == Calculation::getFALSE())) { + return true; + } + + return ExcelError::VALUE(); + } + + return !$logical; + } + + /** + * @return int|string + */ + private static function countTrueValues(array $args) + { + $trueValueCount = 0; + + foreach ($args as $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $trueValueCount += $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $trueValueCount += ((int) $arg != 0); + } elseif (is_string($arg)) { + $arg = mb_strtoupper($arg, 'UTF-8'); + if (($arg == 'TRUE') || ($arg == Calculation::getTRUE())) { + $arg = true; + } elseif (($arg == 'FALSE') || ($arg == Calculation::getFALSE())) { + $arg = false; + } else { + return ExcelError::VALUE(); + } + $trueValueCount += ($arg != 0); + } + } + + return $trueValueCount; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php index 48434300..758c4ef0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef.php @@ -2,11 +2,20 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Address; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\HLookup; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Indirect; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Lookup; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Offset; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\RowColumnInformation; +use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\VLookup; use PhpOffice\PhpSpreadsheet\Cell\Cell; -use PhpOffice\PhpSpreadsheet\Cell\Coordinate; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +/** + * @deprecated 1.18.0 + */ class LookupRef { /** @@ -17,103 +26,55 @@ class LookupRef * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\Address::cell() + * Use the cell() method in the LookupRef\Address class instead + * * @param mixed $row Row number to use in the cell reference * @param mixed $column Column number to use in the cell reference * @param int $relativity Flag indicating the type of reference to return * 1 or omitted Absolute - * 2 Absolute row; relative column - * 3 Relative row; absolute column - * 4 Relative + * 2 Absolute row; relative column + * 3 Relative row; absolute column + * 4 Relative * @param bool $referenceStyle A logical value that specifies the A1 or R1C1 reference style. - * TRUE or omitted CELL_ADDRESS returns an A1-style reference + * TRUE or omitted CELL_ADDRESS returns an A1-style reference * FALSE CELL_ADDRESS returns an R1C1-style reference - * @param string $sheetText Optional Name of worksheet to use + * @param array|string $sheetText Optional Name of worksheet to use * - * @return string + * @return array|string */ public static function cellAddress($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') { - $row = Functions::flattenSingleValue($row); - $column = Functions::flattenSingleValue($column); - $relativity = Functions::flattenSingleValue($relativity); - $sheetText = Functions::flattenSingleValue($sheetText); - - if (($row < 1) || ($column < 1)) { - return Functions::VALUE(); - } - - if ($sheetText > '') { - if (strpos($sheetText, ' ') !== false) { - $sheetText = "'" . $sheetText . "'"; - } - $sheetText .= '!'; - } - if ((!is_bool($referenceStyle)) || $referenceStyle) { - $rowRelative = $columnRelative = '$'; - $column = Coordinate::stringFromColumnIndex($column); - if (($relativity == 2) || ($relativity == 4)) { - $columnRelative = ''; - } - if (($relativity == 3) || ($relativity == 4)) { - $rowRelative = ''; - } - - return $sheetText . $columnRelative . $column . $rowRelative . $row; - } - if (($relativity == 2) || ($relativity == 4)) { - $column = '[' . $column . ']'; - } - if (($relativity == 3) || ($relativity == 4)) { - $row = '[' . $row . ']'; - } - - return $sheetText . 'R' . $row . 'C' . $column; + return Address::cell($row, $column, $relativity, $referenceStyle, $sheetText); } /** * COLUMN. * * Returns the column number of the given cell reference - * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array. - * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the - * reference of the cell in which the COLUMN function appears; otherwise this function returns 0. + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column + * in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the COLUMN function appears; + * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::COLUMN() + * Use the COLUMN() method in the LookupRef\RowColumnInformation class instead + * * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers * - * @return int|int[] + * @return int|int[]|string */ - public static function COLUMN($cellAddress = null) + public static function COLUMN($cellAddress = null, ?Cell $cell = null) { - if ($cellAddress === null || trim($cellAddress) === '') { - return 0; - } - - if (is_array($cellAddress)) { - foreach ($cellAddress as $columnKey => $value) { - $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); - - return (int) Coordinate::columnIndexFromString($columnKey); - } - } else { - [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - if (strpos($cellAddress, ':') !== false) { - [$startAddress, $endAddress] = explode(':', $cellAddress); - $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); - $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); - $returnValue = []; - do { - $returnValue[] = (int) Coordinate::columnIndexFromString($startAddress); - } while ($startAddress++ != $endAddress); - - return $returnValue; - } - $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); - - return (int) Coordinate::columnIndexFromString($cellAddress); - } + return RowColumnInformation::COLUMN($cellAddress, $cell); } /** @@ -124,73 +85,46 @@ public static function COLUMN($cellAddress = null) * Excel Function: * =COLUMNS(cellAddress) * - * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::COLUMNS() + * Use the COLUMNS() method in the LookupRef\RowColumnInformation class instead * - * @return int The number of columns in cellAddress + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of columns + * + * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { - if ($cellAddress === null || $cellAddress === '') { - return 1; - } elseif (!is_array($cellAddress)) { - return Functions::VALUE(); - } - - reset($cellAddress); - $isMatrix = (is_numeric(key($cellAddress))); - [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); - - if ($isMatrix) { - return $rows; - } - - return $columns; + return RowColumnInformation::COLUMNS($cellAddress); } /** * ROW. * * Returns the row number of the given cell reference - * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array. - * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the - * reference of the cell in which the ROW function appears; otherwise this function returns 0. + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference + * as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the ROW function appears; + * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::ROW() + * Use the ROW() method in the LookupRef\RowColumnInformation class instead + * * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers * - * @return int or array of integer + * @return int|mixed[]|string */ - public static function ROW($cellAddress = null) + public static function ROW($cellAddress = null, ?Cell $cell = null) { - if ($cellAddress === null || trim($cellAddress) === '') { - return 0; - } - - if (is_array($cellAddress)) { - foreach ($cellAddress as $columnKey => $rowValue) { - foreach ($rowValue as $rowKey => $cellValue) { - return (int) preg_replace('/\D/', '', $rowKey); - } - } - } else { - [$sheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - if (strpos($cellAddress, ':') !== false) { - [$startAddress, $endAddress] = explode(':', $cellAddress); - $startAddress = preg_replace('/\D/', '', $startAddress); - $endAddress = preg_replace('/\D/', '', $endAddress); - $returnValue = []; - do { - $returnValue[][] = (int) $startAddress; - } while ($startAddress++ != $endAddress); - - return $returnValue; - } - [$cellAddress] = explode(':', $cellAddress); - - return (int) preg_replace('/\D/', '', $cellAddress); - } + return RowColumnInformation::ROW($cellAddress, $cell); } /** @@ -201,27 +135,19 @@ public static function ROW($cellAddress = null) * Excel Function: * =ROWS(cellAddress) * - * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows + * @Deprecated 1.18.0 + * + * @see LookupRef\RowColumnInformation::ROWS() + * Use the ROWS() method in the LookupRef\RowColumnInformation class instead * - * @return int The number of rows in cellAddress + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of rows + * + * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { - if ($cellAddress === null || $cellAddress === '') { - return 1; - } elseif (!is_array($cellAddress)) { - return Functions::VALUE(); - } - - reset($cellAddress); - $isMatrix = (is_numeric(key($cellAddress))); - [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); - - if ($isMatrix) { - return $columns; - } - - return $rows; + return RowColumnInformation::ROWS($cellAddress); } /** @@ -230,31 +156,20 @@ public static function ROWS($cellAddress = null) * Excel Function: * =HYPERLINK(linkURL,displayName) * - * @category Logical Functions + * @Deprecated 1.18.0 * - * @param string $linkURL Value to check, is also the value returned when no error - * @param string $displayName Value to return when testValue is an error condition - * @param Cell $pCell The cell to set the hyperlink in + * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error + * @param mixed $displayName Expect string. Value to return when testValue is an error condition + * @param Cell $cell The cell to set the hyperlink in * - * @return mixed The value of $displayName (or $linkURL if $displayName was blank) + * @return string The value of $displayName (or $linkURL if $displayName was blank) + * + *@see LookupRef\Hyperlink::set() + * Use the set() method in the LookupRef\Hyperlink class instead */ - public static function HYPERLINK($linkURL = '', $displayName = null, Cell $pCell = null) + public static function HYPERLINK($linkURL = '', $displayName = null, ?Cell $cell = null) { - $linkURL = ($linkURL === null) ? '' : Functions::flattenSingleValue($linkURL); - $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); - - if ((!is_object($pCell)) || (trim($linkURL) == '')) { - return Functions::REF(); - } - - if ((is_object($displayName)) || trim($displayName) == '') { - $displayName = $linkURL; - } - - $pCell->getHyperlink()->setUrl($linkURL); - $pCell->getHyperlink()->setTooltip($displayName); - - return $displayName; + return LookupRef\Hyperlink::set($linkURL, $displayName, $cell); } /** @@ -266,54 +181,21 @@ public static function HYPERLINK($linkURL = '', $displayName = null, Cell $pCell * Excel Function: * =INDIRECT(cellAddress) * - * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 + * @Deprecated 1.18.0 * - * @param null|array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) - * @param Cell $pCell The current cell (containing this formula) + * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) + * @param Cell $cell The current cell (containing this formula) * - * @return mixed The cells referenced by cellAddress + * @return array|string An array containing a cell or range of cells, or a string on error * - * @todo Support for the optional a1 parameter introduced in Excel 2010 + *@see LookupRef\Indirect::INDIRECT() + * Use the INDIRECT() method in the LookupRef\Indirect class instead + * + * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 */ - public static function INDIRECT($cellAddress = null, Cell $pCell = null) + public static function INDIRECT($cellAddress, Cell $cell) { - $cellAddress = Functions::flattenSingleValue($cellAddress); - if ($cellAddress === null || $cellAddress === '') { - return Functions::REF(); - } - - $cellAddress1 = $cellAddress; - $cellAddress2 = null; - if (strpos($cellAddress, ':') !== false) { - [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); - } - - if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress1, $matches)) || - (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellAddress2, $matches)))) { - if (!preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $cellAddress1, $matches)) { - return Functions::REF(); - } - - if (strpos($cellAddress, '!') !== false) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false); - } - - if (strpos($cellAddress, '!') !== false) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + return Indirect::INDIRECT($cellAddress, true, $cell); } /** @@ -326,88 +208,34 @@ public static function INDIRECT($cellAddress = null, Cell $pCell = null) * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * - * @param null|string $cellAddress The reference from which you want to base the offset. Reference must refer to a cell or - * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value. + * @Deprecated 1.18.0 + * + * @see LookupRef\Offset::OFFSET() + * Use the OFFSET() method in the LookupRef\Offset class instead + * + * @param null|string $cellAddress The reference from which you want to base the offset. + * Reference must refer to a cell or range of adjacent cells; + * otherwise, OFFSET returns the #VALUE! error value. * @param mixed $rows The number of rows, up or down, that you want the upper-left cell to refer to. - * Using 5 as the rows argument specifies that the upper-left cell in the reference is - * five rows below reference. Rows can be positive (which means below the starting reference) - * or negative (which means above the starting reference). - * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell of the result - * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the - * reference is five columns to the right of reference. Cols can be positive (which means - * to the right of the starting reference) or negative (which means to the left of the - * starting reference). - * @param mixed $height The height, in number of rows, that you want the returned reference to be. Height must be a positive number. - * @param mixed $width The width, in number of columns, that you want the returned reference to be. Width must be a positive number. - * @param null|Cell $pCell - * - * @return string A reference to a cell or range of cells + * Using 5 as the rows argument specifies that the upper-left cell in the + * reference is five rows below reference. Rows can be positive (which means + * below the starting reference) or negative (which means above the starting + * reference). + * @param mixed $columns The number of columns, to the left or right, that you want the upper-left cell + * of the result to refer to. Using 5 as the cols argument specifies that the + * upper-left cell in the reference is five columns to the right of reference. + * Cols can be positive (which means to the right of the starting reference) + * or negative (which means to the left of the starting reference). + * @param mixed $height The height, in number of rows, that you want the returned reference to be. + * Height must be a positive number. + * @param mixed $width The width, in number of columns, that you want the returned reference to be. + * Width must be a positive number. + * + * @return array|string An array containing a cell or range of cells, or a string on error */ - public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, Cell $pCell = null) + public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $cell = null) { - $rows = Functions::flattenSingleValue($rows); - $columns = Functions::flattenSingleValue($columns); - $height = Functions::flattenSingleValue($height); - $width = Functions::flattenSingleValue($width); - if ($cellAddress === null) { - return 0; - } - - if (!is_object($pCell)) { - return Functions::REF(); - } - - $sheetName = null; - if (strpos($cellAddress, '!')) { - [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); - $sheetName = trim($sheetName, "'"); - } - if (strpos($cellAddress, ':')) { - [$startCell, $endCell] = explode(':', $cellAddress); - } else { - $startCell = $endCell = $cellAddress; - } - [$startCellColumn, $startCellRow] = Coordinate::coordinateFromString($startCell); - [$endCellColumn, $endCellRow] = Coordinate::coordinateFromString($endCell); - - $startCellRow += $rows; - $startCellColumn = Coordinate::columnIndexFromString($startCellColumn) - 1; - $startCellColumn += $columns; - - if (($startCellRow <= 0) || ($startCellColumn < 0)) { - return Functions::REF(); - } - $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; - if (($width != null) && (!is_object($width))) { - $endCellColumn = $startCellColumn + $width - 1; - } else { - $endCellColumn += $columns; - } - $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); - - if (($height != null) && (!is_object($height))) { - $endCellRow = $startCellRow + $height - 1; - } else { - $endCellRow += $rows; - } - - if (($endCellRow <= 0) || ($endCellColumn < 0)) { - return Functions::REF(); - } - $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); - - $cellAddress = $startCellColumn . $startCellRow; - if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { - $cellAddress .= ':' . $endCellColumn . $endCellRow; - } - - if ($sheetName !== null) { - $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); - } else { - $pSheet = $pCell->getWorksheet(); - } - - return Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + return Offset::OFFSET($cellAddress, $rows, $columns, $height, $width, $cell); } /** @@ -419,39 +247,16 @@ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $hei * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * - * @param mixed $index_num Specifies which value argument is selected. - * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number - * between 1 and 254. - * @param mixed $value1 ... Value1 is required, subsequent values are optional. - * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on - * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or - * text. + * @Deprecated 1.18.0 + * + * @see LookupRef\Selection::choose() + * Use the choose() method in the LookupRef\Selection class instead * * @return mixed The selected value */ public static function CHOOSE(...$chooseArgs) { - $chosenEntry = Functions::flattenArray(array_shift($chooseArgs)); - $entryCount = count($chooseArgs) - 1; - - if (is_array($chosenEntry)) { - $chosenEntry = array_shift($chosenEntry); - } - if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) { - --$chosenEntry; - } else { - return Functions::VALUE(); - } - $chosenEntry = floor($chosenEntry); - if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { - return Functions::VALUE(); - } - - if (is_array($chooseArgs[$chosenEntry])) { - return Functions::flattenArray($chooseArgs[$chosenEntry]); - } - - return $chooseArgs[$chosenEntry]; + return LookupRef\Selection::choose(...$chooseArgs); } /** @@ -462,153 +267,21 @@ public static function CHOOSE(...$chooseArgs) * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * + * @Deprecated 1.18.0 + * + * @see LookupRef\ExcelMatch::MATCH() + * Use the MATCH() method in the LookupRef\ExcelMatch class instead + * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType 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. * - * @return int|string The relative position of the found item + * @return array|int|string The relative position of the found item */ public static function MATCH($lookupValue, $lookupArray, $matchType = 1) { - $lookupArray = Functions::flattenArray($lookupArray); - $lookupValue = Functions::flattenSingleValue($lookupValue); - $matchType = ($matchType === null) ? 1 : (int) Functions::flattenSingleValue($matchType); - - // MATCH is not case sensitive, so we convert lookup value to be lower cased in case it's string type. - if (is_string($lookupValue)) { - $lookupValue = StringHelper::strToLower($lookupValue); - } - - // Lookup_value type has to be number, text, or logical values - if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { - return Functions::NA(); - } - - // Match_type is 0, 1 or -1 - if (($matchType !== 0) && ($matchType !== -1) && ($matchType !== 1)) { - return Functions::NA(); - } - - // Lookup_array should not be empty - $lookupArraySize = count($lookupArray); - if ($lookupArraySize <= 0) { - return Functions::NA(); - } - - // Lookup_array should contain only number, text, or logical values, or empty (null) cells - foreach ($lookupArray as $i => $lookupArrayValue) { - // check the type of the value - if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) && - (!is_bool($lookupArrayValue)) && ($lookupArrayValue !== null) - ) { - return Functions::NA(); - } - // Convert strings to lowercase for case-insensitive testing - if (is_string($lookupArrayValue)) { - $lookupArray[$i] = StringHelper::strToLower($lookupArrayValue); - } - if (($lookupArrayValue === null) && (($matchType == 1) || ($matchType == -1))) { - $lookupArray = array_slice($lookupArray, 0, $i - 1); - } - } - - if ($matchType == 1) { - // If match_type is 1 the list has to be processed from last to first - - $lookupArray = array_reverse($lookupArray); - $keySet = array_reverse(array_keys($lookupArray)); - } - - // ** - // find the match - // ** - - if ($matchType === 0 || $matchType === 1) { - foreach ($lookupArray as $i => $lookupArrayValue) { - $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); - $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue; - $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue; - $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch; - - if ($matchType === 0) { - if ($typeMatch && is_string($lookupValue) && (bool) preg_match('/([\?\*])/', $lookupValue)) { - $splitString = $lookupValue; - $chars = array_map(function ($i) use ($splitString) { - return mb_substr($splitString, $i, 1); - }, range(0, mb_strlen($splitString) - 1)); - - $length = count($chars); - $pattern = '/^'; - for ($j = 0; $j < $length; ++$j) { - if ($chars[$j] === '~') { - if (isset($chars[$j + 1])) { - if ($chars[$j + 1] === '*') { - $pattern .= preg_quote($chars[$j + 1], '/'); - ++$j; - } elseif ($chars[$j + 1] === '?') { - $pattern .= preg_quote($chars[$j + 1], '/'); - ++$j; - } - } else { - $pattern .= preg_quote($chars[$j], '/'); - } - } elseif ($chars[$j] === '*') { - $pattern .= '.*'; - } elseif ($chars[$j] === '?') { - $pattern .= '.{1}'; - } else { - $pattern .= preg_quote($chars[$j], '/'); - } - } - - $pattern .= '$/'; - if ((bool) preg_match($pattern, $lookupArrayValue)) { - // exact match - return $i + 1; - } - } elseif ($exactMatch) { - // exact match - return $i + 1; - } - } elseif (($matchType === 1) && $typeMatch && ($lookupArrayValue <= $lookupValue)) { - $i = array_search($i, $keySet); - - // The current value is the (first) match - return $i + 1; - } - } - } else { - $maxValueKey = null; - - // The basic algorithm is: - // Iterate and keep the highest match until the next element is smaller than the searched value. - // Return immediately if perfect match is found - foreach ($lookupArray as $i => $lookupArrayValue) { - $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); - $exactTypeMatch = $typeMatch && $lookupArrayValue === $lookupValue; - $nonOnlyNumericExactMatch = !$typeMatch && $lookupArrayValue === $lookupValue; - $exactMatch = $exactTypeMatch || $nonOnlyNumericExactMatch; - - if ($exactMatch) { - // Another "special" case. If a perfect match is found, - // the algorithm gives up immediately - return $i + 1; - } elseif ($typeMatch & $lookupArrayValue >= $lookupValue) { - $maxValueKey = $i + 1; - } elseif ($typeMatch & $lookupArrayValue < $lookupValue) { - //Excel algorithm gives up immediately if the first element is smaller than the searched value - break; - } - } - - if ($maxValueKey !== null) { - return $maxValueKey; - } - } - - // Unsuccessful in finding a match, return #N/A error value - return Functions::NA(); + return LookupRef\ExcelMatch::MATCH($lookupValue, $lookupArray, $matchType); } /** @@ -619,254 +292,99 @@ public static function MATCH($lookupValue, $lookupArray, $matchType = 1) * Excel Function: * =INDEX(range_array, row_num, [column_num]) * - * @param mixed $arrayValues A range of cells or an array constant - * @param mixed $rowNum The row in array from which to return a value. If row_num is omitted, column_num is required. - * @param mixed $columnNum The column in array from which to return a value. If column_num is omitted, row_num is required. + * @Deprecated 1.18.0 + * + * @see LookupRef\Matrix::index() + * Use the index() method in the LookupRef\Matrix class instead + * + * @param mixed $rowNum The row in the array or range from which to return a value. + * If row_num is omitted, column_num is required. + * @param mixed $columnNum The column in the array or range from which to return a value. + * If column_num is omitted, row_num is required. + * @param mixed $matrix * * @return mixed the value of a specified cell or array of cells */ - public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0) + public static function INDEX($matrix, $rowNum = 0, $columnNum = 0) { - $rowNum = Functions::flattenSingleValue($rowNum); - $columnNum = Functions::flattenSingleValue($columnNum); - - if (($rowNum < 0) || ($columnNum < 0)) { - return Functions::VALUE(); - } - - if (!is_array($arrayValues) || ($rowNum > count($arrayValues))) { - return Functions::REF(); - } - - $rowKeys = array_keys($arrayValues); - $columnKeys = @array_keys($arrayValues[$rowKeys[0]]); - - if ($columnNum > count($columnKeys)) { - return Functions::VALUE(); - } elseif ($columnNum == 0) { - if ($rowNum == 0) { - return $arrayValues; - } - $rowNum = $rowKeys[--$rowNum]; - $returnArray = []; - foreach ($arrayValues as $arrayColumn) { - if (is_array($arrayColumn)) { - if (isset($arrayColumn[$rowNum])) { - $returnArray[] = $arrayColumn[$rowNum]; - } else { - return [$rowNum => $arrayValues[$rowNum]]; - } - } else { - return $arrayValues[$rowNum]; - } - } - - return $returnArray; - } - $columnNum = $columnKeys[--$columnNum]; - if ($rowNum > count($rowKeys)) { - return Functions::VALUE(); - } elseif ($rowNum == 0) { - return $arrayValues[$columnNum]; - } - $rowNum = $rowKeys[--$rowNum]; - - return $arrayValues[$rowNum][$columnNum]; + return Matrix::index($matrix, $rowNum, $columnNum); } /** * TRANSPOSE. * + * @Deprecated 1.18.0 + * + * @see LookupRef\Matrix::transpose() + * Use the transpose() method in the LookupRef\Matrix class instead + * * @param array $matrixData A matrix of values * * @return array * - * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix + * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, + * this function will transpose a full matrix */ public static function TRANSPOSE($matrixData) { - $returnMatrix = []; - if (!is_array($matrixData)) { - $matrixData = [[$matrixData]]; - } - - $column = 0; - foreach ($matrixData as $matrixRow) { - $row = 0; - foreach ($matrixRow as $matrixCell) { - $returnMatrix[$row][$column] = $matrixCell; - ++$row; - } - ++$column; - } - - return $returnMatrix; - } - - private static function vlookupSort($a, $b) - { - reset($a); - $firstColumn = key($a); - $aLower = StringHelper::strToLower($a[$firstColumn]); - $bLower = StringHelper::strToLower($b[$firstColumn]); - if ($aLower == $bLower) { - return 0; - } - - return ($aLower < $bLower) ? -1 : 1; + return Matrix::transpose($matrixData); } /** * VLOOKUP - * 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. + * 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. + * + * @Deprecated 1.18.0 + * + * @see LookupRef\VLookup::lookup() + * Use the lookup() method in the LookupRef\VLookup class instead * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched - * @param mixed $index_number The column number in table_array from which the matching value must be returned. The first column is 1. + * @param mixed $index_number The column number in table_array from which the matching value must be returned. + * The first column is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); - $not_exact_match = Functions::flattenSingleValue($not_exact_match); - - // index_number must be greater than or equal to 1 - if ($index_number < 1) { - return Functions::VALUE(); - } - - // index_number must be less than or equal to the number of columns in lookup_array - if ((!is_array($lookup_array)) || (empty($lookup_array))) { - return Functions::REF(); - } - $f = array_keys($lookup_array); - $firstRow = array_pop($f); - if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { - return Functions::REF(); - } - $columnKeys = array_keys($lookup_array[$firstRow]); - $returnColumn = $columnKeys[--$index_number]; - $firstColumn = array_shift($columnKeys); - - if (!$not_exact_match) { - uasort($lookup_array, ['self', 'vlookupSort']); - } - - $lookupLower = StringHelper::strToLower($lookup_value); - $rowNumber = $rowValue = false; - foreach ($lookup_array as $rowKey => $rowData) { - $firstLower = StringHelper::strToLower($rowData[$firstColumn]); - - // break if we have passed possible keys - if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) || - (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && ($firstLower > $lookupLower))) { - break; - } - // remember the last key, but only if datatypes match - if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn])) || - (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]))) { - if ($not_exact_match) { - $rowNumber = $rowKey; - - continue; - } elseif (($firstLower == $lookupLower) - // Spreadsheets software returns first exact match, - // we have sorted and we might have broken key orders - // we want the first one (by its initial index) - && (($rowNumber == false) || ($rowKey < $rowNumber)) - ) { - $rowNumber = $rowKey; - } - } - } - - if ($rowNumber !== false) { - // return the appropriate value - return $lookup_array[$rowNumber][$returnColumn]; - } - - return Functions::NA(); + return VLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * HLOOKUP - * 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. + * 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. + * + * @Deprecated 1.18.0 + * + * @see LookupRef\HLookup::lookup() + * Use the lookup() method in the LookupRef\HLookup class instead * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_array The range of cells being searched - * @param mixed $index_number The row number in table_array from which the matching value must be returned. The first row is 1. + * @param mixed $index_number The row number in table_array from which the matching value must be returned. + * The first row is 1. * @param mixed $not_exact_match determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - $index_number = Functions::flattenSingleValue($index_number); - $not_exact_match = Functions::flattenSingleValue($not_exact_match); - - // index_number must be greater than or equal to 1 - if ($index_number < 1) { - return Functions::VALUE(); - } - - // index_number must be less than or equal to the number of columns in lookup_array - if ((!is_array($lookup_array)) || (empty($lookup_array))) { - return Functions::REF(); - } - $f = array_keys($lookup_array); - $firstRow = array_pop($f); - if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array))) { - return Functions::REF(); - } - - $firstkey = $f[0] - 1; - $returnColumn = $firstkey + $index_number; - $firstColumn = array_shift($f); - $rowNumber = null; - foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) { - // break if we have passed possible keys - $bothNumeric = is_numeric($lookup_value) && is_numeric($rowData); - $bothNotNumeric = !is_numeric($lookup_value) && !is_numeric($rowData); - $lookupLower = StringHelper::strToLower($lookup_value); - $rowDataLower = StringHelper::strToLower($rowData); - - if ($not_exact_match && ( - ($bothNumeric && $rowData > $lookup_value) || - ($bothNotNumeric && $rowDataLower > $lookupLower) - )) { - break; - } - - // Remember the last key, but only if datatypes match (as in VLOOKUP) - if ($bothNumeric || $bothNotNumeric) { - if ($not_exact_match) { - $rowNumber = $rowKey; - - continue; - } elseif ($rowDataLower === $lookupLower - && ($rowNumber === null || $rowKey < $rowNumber) - ) { - $rowNumber = $rowKey; - } - } - } - - if ($rowNumber !== null) { - // otherwise return the appropriate value - return $lookup_array[$returnColumn][$rowNumber]; - } - - return Functions::NA(); + return HLookup::lookup($lookup_value, $lookup_array, $index_number, $not_exact_match); } /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * + * @Deprecated 1.18.0 + * + * @see LookupRef\Lookup::lookup() + * Use the lookup() method in the LookupRef\Lookup class instead + * * @param mixed $lookup_value The value that you want to match in lookup_array * @param mixed $lookup_vector The range of cells being searched * @param null|mixed $result_vector The column from which the matching value must be returned @@ -875,94 +393,24 @@ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not */ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null) { - $lookup_value = Functions::flattenSingleValue($lookup_value); - - if (!is_array($lookup_vector)) { - return Functions::NA(); - } - $hasResultVector = isset($result_vector); - $lookupRows = count($lookup_vector); - $l = array_keys($lookup_vector); - $l = array_shift($l); - $lookupColumns = count($lookup_vector[$l]); - // we correctly orient our results - if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { - $lookup_vector = self::TRANSPOSE($lookup_vector); - $lookupRows = count($lookup_vector); - $l = array_keys($lookup_vector); - $lookupColumns = count($lookup_vector[array_shift($l)]); - } - - if ($result_vector === null) { - $result_vector = $lookup_vector; - } - $resultRows = count($result_vector); - $l = array_keys($result_vector); - $l = array_shift($l); - $resultColumns = count($result_vector[$l]); - // we correctly orient our results - if ($resultRows === 1 && $resultColumns > 1) { - $result_vector = self::TRANSPOSE($result_vector); - $resultRows = count($result_vector); - $r = array_keys($result_vector); - $resultColumns = count($result_vector[array_shift($r)]); - } - - if ($lookupRows === 2 && !$hasResultVector) { - $result_vector = array_pop($lookup_vector); - $lookup_vector = array_shift($lookup_vector); - } - - if ($lookupColumns !== 2) { - foreach ($lookup_vector as &$value) { - if (is_array($value)) { - $k = array_keys($value); - $key1 = $key2 = array_shift($k); - ++$key2; - $dataValue1 = $value[$key1]; - } else { - $key1 = 0; - $key2 = 1; - $dataValue1 = $value; - } - $dataValue2 = array_shift($result_vector); - if (is_array($dataValue2)) { - $dataValue2 = array_shift($dataValue2); - } - $value = [$key1 => $dataValue1, $key2 => $dataValue2]; - } - unset($value); - } - - return self::VLOOKUP($lookup_value, $lookup_vector, 2); + return Lookup::lookup($lookup_value, $lookup_vector, $result_vector); } /** * FORMULATEXT. * + * @Deprecated 1.18.0 + * * @param mixed $cellReference The cell to check - * @param Cell $pCell The current cell (containing this formula) + * @param Cell $cell The current cell (containing this formula) * * @return string + * + *@see LookupRef\Formula::text() + * Use the text() method in the LookupRef\Formula class instead */ - public static function FORMULATEXT($cellReference = '', Cell $pCell = null) + public static function FORMULATEXT($cellReference = '', ?Cell $cell = null) { - if ($pCell === null) { - return Functions::REF(); - } - - preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches); - - $cellReference = $matches[6] . $matches[7]; - $worksheetName = trim($matches[3], "'"); - $worksheet = (!empty($worksheetName)) - ? $pCell->getWorksheet()->getParent()->getSheetByName($worksheetName) - : $pCell->getWorksheet(); - - if (!$worksheet->getCell($cellReference)->isFormula()) { - return Functions::NA(); - } - - return $worksheet->getCell($cellReference)->getValue(); + return LookupRef\Formula::text($cellReference, $cell); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php new file mode 100644 index 00000000..c8cdf2dd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Address.php @@ -0,0 +1,119 @@ + '') { + if (strpos($sheetName, ' ') !== false || strpos($sheetName, '[') !== false) { + $sheetName = "'{$sheetName}'"; + } + $sheetName .= '!'; + } + + return $sheetName; + } + + private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string + { + $rowRelative = $columnRelative = '$'; + if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $columnRelative = ''; + } + if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $rowRelative = ''; + } + $column = Coordinate::stringFromColumnIndex($column); + + return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; + } + + private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string + { + if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $column = "[{$column}]"; + } + if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { + $row = "[{$row}]"; + } + + return "{$sheetName}R{$row}C{$column}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php new file mode 100644 index 00000000..2f691bee --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php @@ -0,0 +1,203 @@ +getMessage(); + } + + // MATCH() is not case sensitive, so we convert lookup value to be lower cased if it's a string type. + if (is_string($lookupValue)) { + $lookupValue = StringHelper::strToLower($lookupValue); + } + + $valueKey = null; + switch ($matchType) { + case self::MATCHTYPE_LARGEST_VALUE: + $valueKey = self::matchLargestValue($lookupArray, $lookupValue, $keySet); + + break; + case self::MATCHTYPE_FIRST_VALUE: + $valueKey = self::matchFirstValue($lookupArray, $lookupValue); + + break; + case self::MATCHTYPE_SMALLEST_VALUE: + default: + $valueKey = self::matchSmallestValue($lookupArray, $lookupValue); + } + + if ($valueKey !== null) { + return ++$valueKey; + } + + // Unsuccessful in finding a match, return #N/A error value + return ExcelError::NA(); + } + + private static function matchFirstValue($lookupArray, $lookupValue) + { + $wildcardLookup = ((bool) preg_match('/([\?\*])/', $lookupValue)); + $wildcard = WildcardMatch::wildcard($lookupValue); + + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || + (is_numeric($lookupValue) && is_numeric($lookupArrayValue))); + + if ( + $typeMatch && is_string($lookupValue) && + $wildcardLookup && WildcardMatch::compare($lookupArrayValue, $wildcard) + ) { + // wildcard match + return $i; + } elseif ($lookupArrayValue === $lookupValue) { + // exact match + return $i; + } + } + + return null; + } + + private static function matchLargestValue($lookupArray, $lookupValue, $keySet) + { + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = ((gettype($lookupValue) === gettype($lookupArrayValue)) || + (is_numeric($lookupValue) && is_numeric($lookupArrayValue))); + + if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { + return array_search($i, $keySet); + } + } + + return null; + } + + private static function matchSmallestValue($lookupArray, $lookupValue) + { + $valueKey = null; + + // The basic algorithm is: + // Iterate and keep the highest match until the next element is smaller than the searched value. + // Return immediately if perfect match is found + foreach ($lookupArray as $i => $lookupArrayValue) { + $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); + + if ($lookupArrayValue === $lookupValue) { + // Another "special" case. If a perfect match is found, + // the algorithm gives up immediately + return $i; + } elseif ($typeMatch && $lookupArrayValue >= $lookupValue) { + $valueKey = $i; + } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { + //Excel algorithm gives up immediately if the first element is smaller than the searched value + break; + } + } + + return $valueKey; + } + + private static function validateLookupValue($lookupValue): void + { + // Lookup_value type has to be number, text, or logical values + if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { + throw new Exception(ExcelError::NA()); + } + } + + private static function validateMatchType($matchType): void + { + // Match_type is 0, 1 or -1 + if ( + ($matchType !== self::MATCHTYPE_FIRST_VALUE) && + ($matchType !== self::MATCHTYPE_LARGEST_VALUE) && ($matchType !== self::MATCHTYPE_SMALLEST_VALUE) + ) { + throw new Exception(ExcelError::NA()); + } + } + + private static function validateLookupArray($lookupArray): void + { + // Lookup_array should not be empty + $lookupArraySize = count($lookupArray); + if ($lookupArraySize <= 0) { + throw new Exception(ExcelError::NA()); + } + } + + private static function prepareLookupArray($lookupArray, $matchType) + { + // Lookup_array should contain only number, text, or logical values, or empty (null) cells + foreach ($lookupArray as $i => $value) { + // check the type of the value + if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { + throw new Exception(ExcelError::NA()); + } + // Convert strings to lowercase for case-insensitive testing + if (is_string($value)) { + $lookupArray[$i] = StringHelper::strToLower($value); + } + if ( + ($value === null) && + (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) + ) { + unset($lookupArray[$i]); + } + } + + return $lookupArray; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php new file mode 100644 index 00000000..74fa8321 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php @@ -0,0 +1,81 @@ +getWorksheet()->getParent()->getSheetByName($worksheetName) + : $cell->getWorksheet(); + + if ( + $worksheet === null || + !$worksheet->cellExists($cellReference) || + !$worksheet->getCell($cellReference)->isFormula() + ) { + return ExcelError::NA(); + } + + return $worksheet->getCell($cellReference)->getValue(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php new file mode 100644 index 00000000..c7e87315 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php @@ -0,0 +1,121 @@ +getMessage(); + } + + $f = array_keys($lookupArray); + $firstRow = reset($f); + if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { + return ExcelError::REF(); + } + + $firstkey = $f[0] - 1; + $returnColumn = $firstkey + $indexNumber; + $firstColumn = array_shift($f) ?? 1; + $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); + + if ($rowNumber !== null) { + // otherwise return the appropriate value + return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; + } + + return ExcelError::NA(); + } + + /** + * @param mixed $lookupValue The value that you want to match in lookup_array + * @param int|string $column + */ + private static function hLookupSearch($lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int + { + $lookupLower = StringHelper::strToLower($lookupValue); + + $rowNumber = null; + foreach ($lookupArray[$column] as $rowKey => $rowData) { + // break if we have passed possible keys + $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); + $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); + $cellDataLower = StringHelper::strToLower($rowData); + + if ( + $notExactMatch && + (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) + ) { + break; + } + + $rowNumber = self::checkMatch( + $bothNumeric, + $bothNotNumeric, + $notExactMatch, + Coordinate::columnIndexFromString($rowKey), + $cellDataLower, + $lookupLower, + $rowNumber + ); + } + + return $rowNumber; + } + + private static function convertLiteralArray(array $lookupArray): array + { + if (array_key_exists(0, $lookupArray)) { + $lookupArray2 = []; + $row = 0; + foreach ($lookupArray as $arrayVal) { + ++$row; + if (!is_array($arrayVal)) { + $arrayVal = [$arrayVal]; + } + $arrayVal2 = []; + foreach ($arrayVal as $key2 => $val2) { + $index = Coordinate::stringFromColumnIndex($key2 + 1); + $arrayVal2[$index] = $val2; + } + $lookupArray2[$row] = $arrayVal2; + } + $lookupArray = $lookupArray2; + } + + return $lookupArray; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php new file mode 100644 index 00000000..28e8df89 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php @@ -0,0 +1,74 @@ +getWorkSheet(); + $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); + $value = preg_replace('/^=/', '', $namedRange->getValue()); + self::adjustSheetTitle($sheetTitle, $value); + $cellAddress1 = $sheetTitle . $value; + $cellAddress = $cellAddress1; + $a1 = self::CELLADDRESS_USE_A1; + } + if (strpos($cellAddress, ':') !== false) { + [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); + } + $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1); + + return [$cellAddress1, $cellAddress2, $cellAddress]; + } + + public static function extractWorksheet(string $cellAddress, Cell $cell): array + { + $sheetName = ''; + if (strpos($cellAddress, '!') !== false) { + [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + $sheetName = trim($sheetName, "'"); + } + + $worksheet = ($sheetName !== '') + ? $cell->getWorksheet()->getParent()->getSheetByName($sheetName) + : $cell->getWorksheet(); + + return [$cellAddress, $worksheet, $sheetName]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php new file mode 100644 index 00000000..5387833f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php @@ -0,0 +1,41 @@ +getHyperlink()->setUrl($linkURL); + $cell->getHyperlink()->setTooltip($displayName); + + return $displayName; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php new file mode 100644 index 00000000..417a1f79 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php @@ -0,0 +1,122 @@ +getMessage(); + } + + [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); + + if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { + $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { + $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); + } + + [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName); + + if ( + (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches)) || + (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches))) + ) { + return ExcelError::REF(); + } + + return self::extractRequiredCells($worksheet, $cellAddress); + } + + /** + * Extract range values. + * + * @return mixed Array of values in range if range contains more than one element. + * Otherwise, a single value is returned. + */ + private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress) + { + return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); + } + + private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string + { + // Being lazy, we're only checking a single row/column to get the max + if (ctype_digit($start) && $start <= 1048576) { + // Max 16,384 columns for Excel2007 + $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : 'XFD'; + + return "A{$start}:{$endColRef}{$end}"; + } elseif (ctype_alpha($start) && strlen($start) <= 3) { + // Max 1,048,576 rows for Excel2007 + $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : 1048576; + + return "{$start}1:{$end}{$endRowRef}"; + } + + return "{$start}:{$end}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php new file mode 100644 index 00000000..76a360b4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php @@ -0,0 +1,110 @@ + 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { + $lookupVector = LookupRef\Matrix::transpose($lookupVector); + $lookupRows = self::rowCount($lookupVector); + $lookupColumns = self::columnCount($lookupVector); + } + + $resultVector = self::verifyResultVector($lookupVector, $resultVector); + + if ($lookupRows === 2 && !$hasResultVector) { + $resultVector = array_pop($lookupVector); + $lookupVector = array_shift($lookupVector); + } + + if ($lookupColumns !== 2) { + $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); + } + + return VLookup::lookup($lookupValue, $lookupVector, 2); + } + + private static function verifyLookupValues(array $lookupVector, array $resultVector): array + { + foreach ($lookupVector as &$value) { + if (is_array($value)) { + $k = array_keys($value); + $key1 = $key2 = array_shift($k); + ++$key2; + $dataValue1 = $value[$key1]; + } else { + $key1 = 0; + $key2 = 1; + $dataValue1 = $value; + } + + $dataValue2 = array_shift($resultVector); + if (is_array($dataValue2)) { + $dataValue2 = array_shift($dataValue2); + } + $value = [$key1 => $dataValue1, $key2 => $dataValue2]; + } + unset($value); + + return $lookupVector; + } + + private static function verifyResultVector(array $lookupVector, $resultVector) + { + if ($resultVector === null) { + $resultVector = $lookupVector; + } + + $resultRows = self::rowCount($resultVector); + $resultColumns = self::columnCount($resultVector); + + // we correctly orient our results + if ($resultRows === 1 && $resultColumns > 1) { + $resultVector = LookupRef\Matrix::transpose($resultVector); + } + + return $resultVector; + } + + private static function rowCount(array $dataArray): int + { + return count($dataArray); + } + + private static function columnCount(array $dataArray): int + { + $rowKeys = array_keys($dataArray); + $row = array_shift($rowKeys); + + return count($dataArray[$row]); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php new file mode 100644 index 00000000..8e451fe4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php @@ -0,0 +1,58 @@ + 1 && + (count($values, COUNT_NORMAL) === 1 || count($values, COUNT_RECURSIVE) === count($values, COUNT_NORMAL)); + } + + /** + * TRANSPOSE. + * + * @param array|mixed $matrixData A matrix of values + * + * @return array + */ + public static function transpose($matrixData) + { + $returnMatrix = []; + if (!is_array($matrixData)) { + $matrixData = [[$matrixData]]; + } + + $column = 0; + foreach ($matrixData as $matrixRow) { + $row = 0; + foreach ($matrixRow as $matrixCell) { + $returnMatrix[$row][$column] = $matrixCell; + ++$row; + } + ++$column; + } + + return $returnMatrix; + } + + /** + * INDEX. + * + * Uses an index to choose a value from a reference or array + * + * Excel Function: + * =INDEX(range_array, row_num, [column_num], [area_num]) + * + * @param mixed $matrix A range of cells or an array constant + * @param mixed $rowNum The row in the array or range from which to return a value. + * If row_num is omitted, column_num is required. + * Or can be an array of values + * @param mixed $columnNum The column in the array or range from which to return a value. + * If column_num is omitted, row_num is required. + * Or can be an array of values + * + * TODO Provide support for area_num, currently not supported + * + * @return mixed the value of a specified cell or array of cells + * If an array of values is passed as the $rowNum and/or $columnNum arguments, then the returned result + * will also be an array with the same dimensions + */ + public static function index($matrix, $rowNum = 0, $columnNum = 0) + { + if (is_array($rowNum) || is_array($columnNum)) { + return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $matrix, $rowNum, $columnNum); + } + + $rowNum = $rowNum ?? 0; + $columnNum = $columnNum ?? 0; + + try { + $rowNum = LookupRefValidations::validatePositiveInt($rowNum); + $columnNum = LookupRefValidations::validatePositiveInt($columnNum); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (!is_array($matrix) || ($rowNum > count($matrix))) { + return ExcelError::REF(); + } + + $rowKeys = array_keys($matrix); + $columnKeys = @array_keys($matrix[$rowKeys[0]]); + + if ($columnNum > count($columnKeys)) { + return ExcelError::REF(); + } + + if ($columnNum === 0) { + return self::extractRowValue($matrix, $rowKeys, $rowNum); + } + + $columnNum = $columnKeys[--$columnNum]; + if ($rowNum === 0) { + return array_map( + function ($value) { + return [$value]; + }, + array_column($matrix, $columnNum) + ); + } + $rowNum = $rowKeys[--$rowNum]; + + return $matrix[$rowNum][$columnNum]; + } + + private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum) + { + if ($rowNum === 0) { + return $matrix; + } + + $rowNum = $rowKeys[--$rowNum]; + $row = $matrix[$rowNum]; + if (is_array($row)) { + return [$rowNum => $row]; + } + + return $row; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php new file mode 100644 index 00000000..9f3377f6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php @@ -0,0 +1,137 @@ +getParent() : null) + ->extractCellRange($cellAddress, $worksheet, false); + } + + private static function extractWorksheet($cellAddress, Cell $cell): array + { + $sheetName = ''; + if (strpos($cellAddress, '!') !== false) { + [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + $sheetName = trim($sheetName, "'"); + } + + $worksheet = ($sheetName !== '') + ? $cell->getWorksheet()->getParent()->getSheetByName($sheetName) + : $cell->getWorksheet(); + + return [$cellAddress, $worksheet]; + } + + private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns) + { + $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; + if (($width !== null) && (!is_object($width))) { + $endCellColumn = $startCellColumn + (int) $width - 1; + } else { + $endCellColumn += (int) $columns; + } + + return $endCellColumn; + } + + private static function adustEndCellRowForHeight($height, int $startCellRow, $rows, $endCellRow): int + { + if (($height !== null) && (!is_object($height))) { + $endCellRow = $startCellRow + (int) $height - 1; + } else { + $endCellRow += (int) $rows; + } + + return $endCellRow; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php new file mode 100644 index 00000000..1f848045 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php @@ -0,0 +1,210 @@ +getColumn()) : 1; + } + + /** + * COLUMN. + * + * Returns the column number of the given cell reference + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column + * in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the COLUMN function appears; + * otherwise this function returns 1. + * + * Excel Function: + * =COLUMN([cellAddress]) + * + * @param null|array|string $cellAddress A reference to a range of cells for which you want the column numbers + * + * @return int|int[] + */ + public static function COLUMN($cellAddress = null, ?Cell $cell = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return self::cellColumn($cell); + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $columnKey => $value) { + $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); + + return (int) Coordinate::columnIndexFromString($columnKey); + } + + return self::cellColumn($cell); + } + + $cellAddress = $cellAddress ?? ''; + if ($cell != null) { + [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); + [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); + } + [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + if (strpos($cellAddress, ':') !== false) { + [$startAddress, $endAddress] = explode(':', $cellAddress); + $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); + $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); + + return range( + (int) Coordinate::columnIndexFromString($startAddress), + (int) Coordinate::columnIndexFromString($endAddress) + ); + } + + $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); + + return (int) Coordinate::columnIndexFromString($cellAddress); + } + + /** + * COLUMNS. + * + * Returns the number of columns in an array or reference. + * + * Excel Function: + * =COLUMNS(cellAddress) + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of columns + * + * @return int|string The number of columns in cellAddress, or a string if arguments are invalid + */ + public static function COLUMNS($cellAddress = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return 1; + } + if (!is_array($cellAddress)) { + return ExcelError::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $rows; + } + + return $columns; + } + + private static function cellRow(?Cell $cell): int + { + return ($cell !== null) ? $cell->getRow() : 1; + } + + /** + * ROW. + * + * Returns the row number of the given cell reference + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference + * as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, + * then it is assumed to be the reference of the cell in which the ROW function appears; + * otherwise this function returns 1. + * + * Excel Function: + * =ROW([cellAddress]) + * + * @param null|array|string $cellAddress A reference to a range of cells for which you want the row numbers + * + * @return int|mixed[]|string + */ + public static function ROW($cellAddress = null, ?Cell $cell = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return self::cellRow($cell); + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $rowKey => $rowValue) { + foreach ($rowValue as $columnKey => $cellValue) { + return (int) preg_replace('/\D/', '', $rowKey); + } + } + + return self::cellRow($cell); + } + + $cellAddress = $cellAddress ?? ''; + if ($cell !== null) { + [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); + [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); + } + [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); + if (strpos($cellAddress, ':') !== false) { + [$startAddress, $endAddress] = explode(':', $cellAddress); + $startAddress = preg_replace('/\D/', '', $startAddress); + $endAddress = preg_replace('/\D/', '', $endAddress); + + return array_map( + function ($value) { + return [$value]; + }, + // @phpstan-ignore-next-line + range($startAddress, $endAddress) + ); + } + [$cellAddress] = explode(':', $cellAddress); + + return (int) preg_replace('/\D/', '', $cellAddress); + } + + /** + * ROWS. + * + * Returns the number of rows in an array or reference. + * + * Excel Function: + * =ROWS(cellAddress) + * + * @param null|array|string $cellAddress An array or array formula, or a reference to a range of cells + * for which you want the number of rows + * + * @return int|string The number of rows in cellAddress, or a string if arguments are invalid + */ + public static function ROWS($cellAddress = null) + { + if (self::cellAddressNullOrWhitespace($cellAddress)) { + return 1; + } + if (!is_array($cellAddress)) { + return ExcelError::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $columns; + } + + return $rows; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php new file mode 100644 index 00000000..0ac91777 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php @@ -0,0 +1,51 @@ + $entryCount)) { + return ExcelError::VALUE(); + } + + if (is_array($chooseArgs[$chosenEntry])) { + return Functions::flattenArray($chooseArgs[$chosenEntry]); + } + + return $chooseArgs[$chosenEntry]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php new file mode 100644 index 00000000..ff78fbea --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php @@ -0,0 +1,342 @@ +getMessage(); + } + + // We want a simple, enumrated array of arrays where we can reference column by its index number. + $sortArray = array_values(array_map('array_values', $sortArray)); + + return ($byColumn === true) + ? self::sortByColumn($sortArray, $sortIndex, $sortOrder) + : self::sortByRow($sortArray, $sortIndex, $sortOrder); + } + + /** + * SORTBY + * The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. + * The returned array is the same shape as the provided array argument. + * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. + * + * @param mixed $sortArray The range of cells being sorted + * @param mixed $args + * At least one additional argument must be provided, The vector or range to sort on + * After that, arguments are passed as pairs: + * sort order: ascending or descending + * Ascending = 1 (self::ORDER_ASCENDING) + * Descending = -1 (self::ORDER_DESCENDING) + * additional arrays or ranges for multi-level sorting + * + * @return mixed The sorted values from the sort range + */ + public static function sortBy($sortArray, ...$args) + { + if (!is_array($sortArray)) { + // Scalars are always returned "as is" + return $sortArray; + } + + $sortArray = self::enumerateArrayKeys($sortArray); + + $lookupArraySize = count($sortArray); + $argumentCount = count($args); + + try { + $sortBy = $sortOrder = []; + for ($i = 0; $i < $argumentCount; $i += 2) { + $sortBy[] = self::validateSortVector($args[$i], $lookupArraySize); + $sortOrder[] = self::validateSortOrder($args[$i + 1] ?? self::ORDER_ASCENDING); + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::processSortBy($sortArray, $sortBy, $sortOrder); + } + + private static function enumerateArrayKeys(array $sortArray): array + { + array_walk( + $sortArray, + function (&$columns): void { + if (is_array($columns)) { + $columns = array_values($columns); + } + } + ); + + return array_values($sortArray); + } + + /** + * @param mixed $sortIndex + * @param mixed $sortOrder + */ + private static function validateScalarArgumentsForSort(&$sortIndex, &$sortOrder, int $sortArraySize): void + { + if (is_array($sortIndex) || is_array($sortOrder)) { + throw new Exception(ExcelError::VALUE()); + } + + $sortIndex = self::validatePositiveInt($sortIndex, false); + + if ($sortIndex > $sortArraySize) { + throw new Exception(ExcelError::VALUE()); + } + + $sortOrder = self::validateSortOrder($sortOrder); + } + + /** + * @param mixed $sortVector + */ + private static function validateSortVector($sortVector, int $sortArraySize): array + { + if (!is_array($sortVector)) { + throw new Exception(ExcelError::VALUE()); + } + + // It doesn't matter if it's a row or a column vectors, it works either way + $sortVector = Functions::flattenArray($sortVector); + if (count($sortVector) !== $sortArraySize) { + throw new Exception(ExcelError::VALUE()); + } + + return $sortVector; + } + + /** + * @param mixed $sortOrder + */ + private static function validateSortOrder($sortOrder): int + { + $sortOrder = self::validateInt($sortOrder); + if (($sortOrder == self::ORDER_ASCENDING || $sortOrder === self::ORDER_DESCENDING) === false) { + throw new Exception(ExcelError::VALUE()); + } + + return $sortOrder; + } + + /** + * @param array $sortIndex + * @param mixed $sortOrder + */ + private static function validateArrayArgumentsForSort(&$sortIndex, &$sortOrder, int $sortArraySize): void + { + // It doesn't matter if they're row or column vectors, it works either way + $sortIndex = Functions::flattenArray($sortIndex); + $sortOrder = Functions::flattenArray($sortOrder); + + if ( + count($sortOrder) === 0 || count($sortOrder) > $sortArraySize || + (count($sortOrder) > count($sortIndex)) + ) { + throw new Exception(ExcelError::VALUE()); + } + + if (count($sortIndex) > count($sortOrder)) { + // If $sortOrder has fewer elements than $sortIndex, then the last order element is repeated. + $sortOrder = array_merge( + $sortOrder, + array_fill(0, count($sortIndex) - count($sortOrder), array_pop($sortOrder)) + ); + } + + foreach ($sortIndex as $key => &$value) { + self::validateScalarArgumentsForSort($value, $sortOrder[$key], $sortArraySize); + } + } + + private static function prepareSortVectorValues(array $sortVector): array + { + // Strings should be sorted case-insensitive; with booleans converted to locale-strings + return array_map( + function ($value) { + if (is_bool($value)) { + return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); + } elseif (is_string($value)) { + return StringHelper::strToLower($value); + } + + return $value; + }, + $sortVector + ); + } + + /** + * @param array[] $sortIndex + * @param int[] $sortOrder + */ + private static function processSortBy(array $sortArray, array $sortIndex, $sortOrder): array + { + $sortArguments = []; + $sortData = []; + foreach ($sortIndex as $index => $sortValues) { + $sortData[] = $sortValues; + $sortArguments[] = self::prepareSortVectorValues($sortValues); + $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; + } + $sortArguments = self::applyPHP7Patch($sortArray, $sortArguments); + + $sortVector = self::executeVectorSortQuery($sortData, $sortArguments); + + return self::sortLookupArrayFromVector($sortArray, $sortVector); + } + + /** + * @param int[] $sortIndex + * @param int[] $sortOrder + */ + private static function sortByRow(array $sortArray, array $sortIndex, array $sortOrder): array + { + $sortVector = self::buildVectorForSort($sortArray, $sortIndex, $sortOrder); + + return self::sortLookupArrayFromVector($sortArray, $sortVector); + } + + /** + * @param int[] $sortIndex + * @param int[] $sortOrder + */ + private static function sortByColumn(array $sortArray, array $sortIndex, array $sortOrder): array + { + $sortArray = Matrix::transpose($sortArray); + $result = self::sortByRow($sortArray, $sortIndex, $sortOrder); + + return Matrix::transpose($result); + } + + /** + * @param int[] $sortIndex + * @param int[] $sortOrder + */ + private static function buildVectorForSort(array $sortArray, array $sortIndex, array $sortOrder): array + { + $sortArguments = []; + $sortData = []; + foreach ($sortIndex as $index => $sortIndexValue) { + $sortValues = array_column($sortArray, $sortIndexValue - 1); + $sortData[] = $sortValues; + $sortArguments[] = self::prepareSortVectorValues($sortValues); + $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; + } + $sortArguments = self::applyPHP7Patch($sortArray, $sortArguments); + + $sortData = self::executeVectorSortQuery($sortData, $sortArguments); + + return $sortData; + } + + private static function executeVectorSortQuery(array $sortData, array $sortArguments): array + { + $sortData = Matrix::transpose($sortData); + + // We need to set an index that can be retained, as array_multisort doesn't maintain numeric keys. + $sortDataIndexed = []; + foreach ($sortData as $key => $value) { + $sortDataIndexed[Coordinate::stringFromColumnIndex($key + 1)] = $value; + } + unset($sortData); + + $sortArguments[] = &$sortDataIndexed; + + array_multisort(...$sortArguments); + + // After the sort, we restore the numeric keys that will now be in the correct, sorted order + $sortedData = []; + foreach (array_keys($sortDataIndexed) as $key) { + $sortedData[] = Coordinate::columnIndexFromString($key) - 1; + } + + return $sortedData; + } + + private static function sortLookupArrayFromVector(array $sortArray, array $sortVector): array + { + // Building a new array in the correct (sorted) order works; but may be memory heavy for larger arrays + $sortedArray = []; + foreach ($sortVector as $index) { + $sortedArray[] = $sortArray[$index]; + } + + return $sortedArray; + +// uksort( +// $lookupArray, +// function (int $a, int $b) use (array $sortVector) { +// return $sortVector[$a] <=> $sortVector[$b]; +// } +// ); +// +// return $lookupArray; + } + + /** + * Hack to handle PHP 7: + * From PHP 8.0.0, If two members compare as equal in a sort, they retain their original order; + * but prior to PHP 8.0.0, their relative order in the sorted array was undefined. + * MS Excel replicates the PHP 8.0.0 behaviour, retaining the original order of matching elements. + * To replicate that behaviour with PHP 7, we add an extra sort based on the row index. + */ + private static function applyPHP7Patch(array $sortArray, array $sortArguments): array + { + if (PHP_VERSION_ID < 80000) { + $sortArguments[] = range(1, count($sortArray)); + $sortArguments[] = SORT_ASC; + } + + return $sortArguments; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php new file mode 100644 index 00000000..2ba51281 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php @@ -0,0 +1,141 @@ + count($flattenedLookupVector, COUNT_RECURSIVE) + 1) { + // We're looking at a full column check (multiple rows) + $transpose = Matrix::transpose($lookupVector); + $result = self::uniqueByRow($transpose, $exactlyOnce); + + return (is_array($result)) ? Matrix::transpose($result) : $result; + } + + $result = self::countValuesCaseInsensitive($flattenedLookupVector); + + if ($exactlyOnce === true) { + $result = self::exactlyOnceFilter($result); + } + + if (count($result) === 0) { + return ExcelError::CALC(); + } + + $result = array_keys($result); + + return $result; + } + + private static function countValuesCaseInsensitive(array $caseSensitiveLookupValues): array + { + $caseInsensitiveCounts = array_count_values( + array_map( + function (string $value) { + return StringHelper::strToUpper($value); + }, + $caseSensitiveLookupValues + ) + ); + + $caseSensitiveCounts = []; + foreach ($caseInsensitiveCounts as $caseInsensitiveKey => $count) { + if (is_numeric($caseInsensitiveKey)) { + $caseSensitiveCounts[$caseInsensitiveKey] = $count; + } else { + foreach ($caseSensitiveLookupValues as $caseSensitiveValue) { + if ($caseInsensitiveKey === StringHelper::strToUpper($caseSensitiveValue)) { + $caseSensitiveCounts[$caseSensitiveValue] = $count; + + break; + } + } + } + } + + return $caseSensitiveCounts; + } + + private static function exactlyOnceFilter(array $values): array + { + return array_filter( + $values, + function ($value) { + return $value === 1; + } + ); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php new file mode 100644 index 00000000..bc8624f3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php @@ -0,0 +1,115 @@ +getMessage(); + } + + $f = array_keys($lookupArray); + $firstRow = array_pop($f); + if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { + return ExcelError::REF(); + } + $columnKeys = array_keys($lookupArray[$firstRow]); + $returnColumn = $columnKeys[--$indexNumber]; + $firstColumn = array_shift($columnKeys) ?? 1; + + if (!$notExactMatch) { + uasort($lookupArray, ['self', 'vlookupSort']); + } + + $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); + + if ($rowNumber !== null) { + // return the appropriate value + return $lookupArray[$rowNumber][$returnColumn]; + } + + return ExcelError::NA(); + } + + private static function vlookupSort($a, $b) + { + reset($a); + $firstColumn = key($a); + $aLower = StringHelper::strToLower($a[$firstColumn]); + $bLower = StringHelper::strToLower($b[$firstColumn]); + + if ($aLower == $bLower) { + return 0; + } + + return ($aLower < $bLower) ? -1 : 1; + } + + /** + * @param mixed $lookupValue The value that you want to match in lookup_array + * @param int|string $column + */ + private static function vLookupSearch($lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int + { + $lookupLower = StringHelper::strToLower($lookupValue); + + $rowNumber = null; + foreach ($lookupArray as $rowKey => $rowData) { + $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData[$column]); + $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData[$column]); + $cellDataLower = StringHelper::strToLower($rowData[$column]); + + // break if we have passed possible keys + if ( + $notExactMatch && + (($bothNumeric && ($rowData[$column] > $lookupValue)) || + ($bothNotNumeric && ($cellDataLower > $lookupLower))) + ) { + break; + } + + $rowNumber = self::checkMatch( + $bothNumeric, + $bothNotNumeric, + $notExactMatch, + $rowKey, + $cellDataLower, + $lookupLower, + $rowNumber + ); + } + + return $rowNumber; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php index f94c8fcc..993154c3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig.php @@ -2,42 +2,11 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use Matrix\Exception as MatrixException; -use Matrix\Matrix; - +/** + * @deprecated 1.18.0 + */ class MathTrig { - // - // Private method to return an array of the factors of the input value - // - private static function factors($value) - { - $startVal = floor(sqrt($value)); - - $factorArray = []; - for ($i = $startVal; $i > 1; --$i) { - if (($value % $i) == 0) { - $factorArray = array_merge($factorArray, self::factors($value / $i)); - $factorArray = array_merge($factorArray, self::factors($i)); - if ($i <= sqrt($value)) { - break; - } - } - } - if (!empty($factorArray)) { - rsort($factorArray); - - return $factorArray; - } - - return [(int) $value]; - } - - private static function romanCut($num, $n) - { - return ($num - ($num % $n)) / $n; - } - /** * ARABIC. * @@ -46,78 +15,18 @@ private static function romanCut($num, $n) * Excel Function: * ARABIC(text) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 * - * @param string $roman - * - * @return int|string the arabic numberal contrived from the roman numeral - */ - public static function ARABIC($roman) - { - // An empty string should return 0 - $roman = substr(trim(strtoupper((string) Functions::flattenSingleValue($roman))), 0, 255); - if ($roman === '') { - return 0; - } - - // Convert the roman numeral to an arabic number - $negativeNumber = $roman[0] === '-'; - if ($negativeNumber) { - $roman = substr($roman, 1); - } - - try { - $arabic = self::calculateArabic(str_split($roman)); - } catch (\Exception $e) { - return Functions::VALUE(); // Invalid character detected - } - - if ($negativeNumber) { - $arabic *= -1; // The number should be negative - } - - return $arabic; - } - - /** - * Recursively calculate the arabic value of a roman numeral. + * @See MathTrig\Arabic::evaluate() + * Use the evaluate method in the MathTrig\Arabic class instead * - * @param array $roman - * @param int $sum - * @param int $subtract + * @param array|string $roman * - * @return int + * @return array|int|string the arabic numberal contrived from the roman numeral */ - protected static function calculateArabic(array $roman, &$sum = 0, $subtract = 0) + public static function ARABIC($roman) { - $lookup = [ - 'M' => 1000, - 'D' => 500, - 'C' => 100, - 'L' => 50, - 'X' => 10, - 'V' => 5, - 'I' => 1, - ]; - - $numeral = array_shift($roman); - if (!isset($lookup[$numeral])) { - throw new \Exception('Invalid character detected'); - } - - $arabic = $lookup[$numeral]; - if (count($roman) > 0 && isset($lookup[$roman[0]]) && $arabic < $lookup[$roman[0]]) { - $subtract += $arabic; - } else { - $sum += ($arabic - $subtract); - $subtract = 0; - } - - if (count($roman) > 0) { - self::calculateArabic($roman, $sum, $subtract); - } - - return $sum; + return MathTrig\Arabic::evaluate($roman); } /** @@ -136,34 +45,19 @@ protected static function calculateArabic(array $roman, &$sum = 0, $subtract = 0 * Excel Function: * ATAN2(xCoordinate,yCoordinate) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atan2() + * Use the atan2 method in the MathTrig\Trig\Tangent class instead * - * @param float $xCoordinate the x-coordinate of the point - * @param float $yCoordinate the y-coordinate of the point + * @param array|float $xCoordinate the x-coordinate of the point + * @param array|float $yCoordinate the y-coordinate of the point * - * @return float|string the inverse tangent of the specified x- and y-coordinates, or a string containing an error + * @return array|float|string the inverse tangent of the specified x- and y-coordinates, or a string containing an error */ public static function ATAN2($xCoordinate = null, $yCoordinate = null) { - $xCoordinate = Functions::flattenSingleValue($xCoordinate); - $yCoordinate = Functions::flattenSingleValue($yCoordinate); - - $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0; - $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0; - - if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && - ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { - $xCoordinate = (float) $xCoordinate; - $yCoordinate = (float) $yCoordinate; - - if (($xCoordinate == 0) && ($yCoordinate == 0)) { - return Functions::DIV0(); - } - - return atan2($yCoordinate, $xCoordinate); - } - - return Functions::VALUE(); + return MathTrig\Trig\Tangent::atan2($xCoordinate, $yCoordinate); } /** @@ -174,39 +68,20 @@ public static function ATAN2($xCoordinate = null, $yCoordinate = null) * Excel Function: * BASE(Number, Radix [Min_length]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @See MathTrig\Base::evaluate() + * Use the evaluate method in the MathTrig\Base class instead * * @param float $number * @param float $radix * @param int $minLength * - * @return string the text representation with the given radix (base) + * @return array|string the text representation with the given radix (base) */ public static function BASE($number, $radix, $minLength = null) { - $number = Functions::flattenSingleValue($number); - $radix = Functions::flattenSingleValue($radix); - $minLength = Functions::flattenSingleValue($minLength); - - if (is_numeric($number) && is_numeric($radix) && ($minLength === null || is_numeric($minLength))) { - // Truncate to an integer - $number = (int) $number; - $radix = (int) $radix; - $minLength = (int) $minLength; - - if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { - return Functions::NAN(); // Numeric range constraints - } - - $outcome = strtoupper((string) base_convert($number, 10, $radix)); - if ($minLength !== null) { - $outcome = str_pad($outcome, $minLength, '0', STR_PAD_LEFT); // String padding - } - - return $outcome; - } - - return Functions::VALUE(); + return MathTrig\Base::evaluate($number, $radix, $minLength); } /** @@ -220,34 +95,19 @@ public static function BASE($number, $radix, $minLength = null) * Excel Function: * CEILING(number[,significance]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * * @param float $number the number you want to round * @param float $significance the multiple to which you want to round * - * @return float|string Rounded Number, or a string containing an error + * @return array|float|string Rounded Number, or a string containing an error + * + * @see MathTrig\Ceiling::ceiling() + * Use the ceiling() method in the MathTrig\Ceiling class instead */ public static function CEILING($number, $significance = null) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if (($significance === null) && - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) { - $significance = $number / abs($number); - } - - if ((is_numeric($number)) && (is_numeric($significance))) { - if (($number == 0.0) || ($significance == 0.0)) { - return 0.0; - } elseif (self::SIGN($number) == self::SIGN($significance)) { - return ceil($number / $significance) * $significance; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Ceiling::ceiling($number, $significance); } /** @@ -259,29 +119,19 @@ public static function CEILING($number, $significance = null) * Excel Function: * COMBIN(numObjs,numInSet) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @see MathTrig\Combinations::withoutRepetition() + * Use the withoutRepetition() method in the MathTrig\Combinations class instead * - * @param int $numObjs Number of different objects - * @param int $numInSet Number of objects in each combination + * @param array|int $numObjs Number of different objects + * @param array|int $numInSet Number of objects in each combination * - * @return int|string Number of combinations, or a string containing an error + * @return array|float|int|string Number of combinations, or a string containing an error */ public static function COMBIN($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); - $numInSet = Functions::flattenSingleValue($numInSet); - - if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { - if ($numObjs < $numInSet) { - return Functions::NAN(); - } elseif ($numInSet < 0) { - return Functions::NAN(); - } - - return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); - } - - return Functions::VALUE(); + return MathTrig\Combinations::withoutRepetition($numObjs, $numInSet); } /** @@ -296,29 +146,31 @@ public static function COMBIN($numObjs, $numInSet) * Excel Function: * EVEN(number) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 * - * @param float $number Number to round + * @see MathTrig\Round::even() + * Use the even() method in the MathTrig\Round class instead + * + * @param array|float $number Number to round * - * @return int|string Rounded Number, or a string containing an error + * @return array|float|int|string Rounded Number, or a string containing an error */ public static function EVEN($number) { - $number = Functions::flattenSingleValue($number); - - if ($number === null) { - return 0; - } elseif (is_bool($number)) { - $number = (int) $number; - } - - if (is_numeric($number)) { - $significance = 2 * self::SIGN($number); - - return (int) self::CEILING($number, $significance); - } + return MathTrig\Round::even($number); + } - return Functions::VALUE(); + /** + * Helper function for Even. + * + * @Deprecated 1.18.0 + * + * @see MathTrig\Helpers::getEven() + * Use the evaluate() method in the MathTrig\Helpers class instead + */ + public static function getEven(float $number): int + { + return (int) MathTrig\Helpers::getEven($number); } /** @@ -330,35 +182,18 @@ public static function EVEN($number) * Excel Function: * FACT(factVal) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @param array|float $factVal Factorial Value * - * @param float $factVal Factorial Value + * @return array|float|int|string Factorial, or a string containing an error * - * @return int|string Factorial, or a string containing an error + *@see MathTrig\Factorial::fact() + * Use the fact() method in the MathTrig\Factorial class instead */ public static function FACT($factVal) { - $factVal = Functions::flattenSingleValue($factVal); - - if (is_numeric($factVal)) { - if ($factVal < 0) { - return Functions::NAN(); - } - $factLoop = floor($factVal); - if ((Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) && - ($factVal > $factLoop)) { - return Functions::NAN(); - } - - $factorial = 1; - while ($factLoop > 1) { - $factorial *= $factLoop--; - } - - return $factorial; - } - - return Functions::VALUE(); + return MathTrig\Factorial::fact($factVal); } /** @@ -369,31 +204,18 @@ public static function FACT($factVal) * Excel Function: * FACTDOUBLE(factVal) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @param array|float $factVal Factorial Value * - * @param float $factVal Factorial Value + * @return array|float|int|string Double Factorial, or a string containing an error * - * @return int|string Double Factorial, or a string containing an error + *@see MathTrig\Factorial::factDouble() + * Use the factDouble() method in the MathTrig\Factorial class instead */ public static function FACTDOUBLE($factVal) { - $factLoop = Functions::flattenSingleValue($factVal); - - if (is_numeric($factLoop)) { - $factLoop = floor($factLoop); - if ($factVal < 0) { - return Functions::NAN(); - } - $factorial = 1; - while ($factLoop > 1) { - $factorial *= $factLoop--; - --$factLoop; - } - - return $factorial; - } - - return Functions::VALUE(); + return MathTrig\Factorial::factDouble($factVal); } /** @@ -404,38 +226,19 @@ public static function FACTDOUBLE($factVal) * Excel Function: * FLOOR(number[,significance]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * * @param float $number Number to round * @param float $significance Significance * - * @return float|string Rounded Number, or a string containing an error + * @return array|float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::floor() + * Use the floor() method in the MathTrig\Floor class instead */ public static function FLOOR($number, $significance = null) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if (($significance === null) && - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC)) { - $significance = $number / abs($number); - } - - if ((is_numeric($number)) && (is_numeric($significance))) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } elseif (self::SIGN($significance) == 1) { - return floor($number / $significance) * $significance; - } elseif (self::SIGN($number) == -1 && self::SIGN($significance) == -1) { - return floor($number / $significance) * $significance; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Floor::floor($number, $significance); } /** @@ -446,37 +249,20 @@ public static function FLOOR($number, $significance = null) * Excel Function: * FLOOR.MATH(number[,significance[,mode]]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * * @param float $number Number to round * @param float $significance Significance * @param int $mode direction to round negative numbers * - * @return float|string Rounded Number, or a string containing an error + * @return array|float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::math() + * Use the math() method in the MathTrig\Floor class instead */ public static function FLOORMATH($number, $significance = null, $mode = 0) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - $mode = Functions::flattenSingleValue($mode); - - if (is_numeric($number) && $significance === null) { - $significance = $number / abs($number); - } - - if (is_numeric($number) && is_numeric($significance) && is_numeric($mode)) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } elseif (self::SIGN($significance) == -1 || (self::SIGN($number) == -1 && !empty($mode))) { - return ceil($number / $significance) * $significance; - } - - return floor($number / $significance) * $significance; - } - - return Functions::VALUE(); + return MathTrig\Floor::math($number, $significance, $mode); } /** @@ -487,100 +273,65 @@ public static function FLOORMATH($number, $significance = null, $mode = 0) * Excel Function: * FLOOR.PRECISE(number[,significance]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * * @param float $number Number to round * @param float $significance Significance * - * @return float|string Rounded Number, or a string containing an error + * @return array|float|string Rounded Number, or a string containing an error + * + *@see MathTrig\Floor::precise() + * Use the precise() method in the MathTrig\Floor class instead */ public static function FLOORPRECISE($number, $significance = 1) { - $number = Functions::flattenSingleValue($number); - $significance = Functions::flattenSingleValue($significance); - - if ((is_numeric($number)) && (is_numeric($significance))) { - if ($significance == 0.0) { - return Functions::DIV0(); - } elseif ($number == 0.0) { - return 0.0; - } - - return floor($number / abs($significance)) * abs($significance); - } - - return Functions::VALUE(); - } - - private static function evaluateGCD($a, $b) - { - return $b ? self::evaluateGCD($b, $a % $b) : $a; + return MathTrig\Floor::precise($number, $significance); } /** - * GCD. + * INT. * - * Returns the greatest common divisor of a series of numbers. - * The greatest common divisor is the largest integer that divides both - * number1 and number2 without a remainder. + * Casts a floating point value to an integer * * Excel Function: - * GCD(number1[,number2[, ...]]) + * INT(number) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * - * @param mixed ...$args Data values + * @see MathTrig\IntClass::evaluate() + * Use the evaluate() method in the MathTrig\IntClass class instead * - * @return int|mixed|string Greatest Common Divisor, or a string containing an error + * @param array|float $number Number to cast to an integer + * + * @return array|int|string Integer value, or a string containing an error */ - public static function GCD(...$args) + public static function INT($number) { - $args = Functions::flattenArray($args); - // Loop through arguments - foreach (Functions::flattenArray($args) as $value) { - if (!is_numeric($value)) { - return Functions::VALUE(); - } elseif ($value < 0) { - return Functions::NAN(); - } - } - - $gcd = (int) array_pop($args); - do { - $gcd = self::evaluateGCD($gcd, (int) array_pop($args)); - } while (!empty($args)); - - return $gcd; + return MathTrig\IntClass::evaluate($number); } /** - * INT. + * GCD. * - * Casts a floating point value to an integer + * Returns the greatest common divisor of a series of numbers. + * The greatest common divisor is the largest integer that divides both + * number1 and number2 without a remainder. * * Excel Function: - * INT(number) + * GCD(number1[,number2[, ...]]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 * - * @param float $number Number to cast to an integer + * @see MathTrig\Gcd::evaluate() + * Use the evaluate() method in the MathTrig\Gcd class instead + * + * @param mixed ...$args Data values * - * @return int|string Integer value, or a string containing an error + * @return int|mixed|string Greatest Common Divisor, or a string containing an error */ - public static function INT($number) + public static function GCD(...$args) { - $number = Functions::flattenSingleValue($number); - - if ($number === null) { - return 0; - } elseif (is_bool($number)) { - return (int) $number; - } - if (is_numeric($number)) { - return (int) floor($number); - } - - return Functions::VALUE(); + return MathTrig\Gcd::evaluate(...$args); } /** @@ -594,7 +345,10 @@ public static function INT($number) * Excel Function: * LCM(number1[,number2[, ...]]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @see MathTrig\Lcm::evaluate() + * Use the evaluate() method in the MathTrig\Lcm class instead * * @param mixed ...$args Data values * @@ -602,39 +356,7 @@ public static function INT($number) */ public static function LCM(...$args) { - $returnValue = 1; - $allPoweredFactors = []; - // Loop through arguments - foreach (Functions::flattenArray($args) as $value) { - if (!is_numeric($value)) { - return Functions::VALUE(); - } - if ($value == 0) { - return 0; - } elseif ($value < 0) { - return Functions::NAN(); - } - $myFactors = self::factors(floor($value)); - $myCountedFactors = array_count_values($myFactors); - $myPoweredFactors = []; - foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { - $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower); - } - foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { - if (isset($allPoweredFactors[$myPoweredValue])) { - if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { - $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; - } - } else { - $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; - } - } - } - foreach ($allPoweredFactors as $allPoweredFactor) { - $returnValue *= (int) $allPoweredFactor; - } - - return $returnValue; + return MathTrig\Lcm::evaluate(...$args); } /** @@ -645,26 +367,19 @@ public static function LCM(...$args) * Excel Function: * LOG(number[,base]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @see MathTrig\Logarithms::withBase() + * Use the withBase() method in the MathTrig\Logarithms class instead * * @param float $number The positive real number for which you want the logarithm * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. * - * @return float|string The result, or a string containing an error + * @return array|float|string The result, or a string containing an error */ - public static function logBase($number = null, $base = 10) + public static function logBase($number, $base = 10) { - $number = Functions::flattenSingleValue($number); - $base = ($base === null) ? 10 : (float) Functions::flattenSingleValue($base); - - if ((!is_numeric($base)) || (!is_numeric($number))) { - return Functions::VALUE(); - } - if (($base <= 0) || ($number <= 0)) { - return Functions::NAN(); - } - - return log($number, $base); + return MathTrig\Logarithms::withBase($number, $base); } /** @@ -675,7 +390,10 @@ public static function logBase($number = null, $base = 10) * Excel Function: * MDETERM(array) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::determinant() + * Use the determinant() method in the MathTrig\MatrixFunctions class instead * * @param array $matrixValues A matrix of values * @@ -683,40 +401,7 @@ public static function logBase($number = null, $base = 10) */ public static function MDETERM($matrixValues) { - $matrixData = []; - if (!is_array($matrixValues)) { - $matrixValues = [[$matrixValues]]; - } - - $row = $maxColumn = 0; - foreach ($matrixValues as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $column = 0; - foreach ($matrixRow as $matrixCell) { - if ((is_string($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixData[$row][$column] = $matrixCell; - ++$column; - } - if ($column > $maxColumn) { - $maxColumn = $column; - } - ++$row; - } - - $matrix = new Matrix($matrixData); - if (!$matrix->isSquare()) { - return Functions::VALUE(); - } - - try { - return $matrix->determinant(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::determinant($matrixValues); } /** @@ -727,7 +412,10 @@ public static function MDETERM($matrixValues) * Excel Function: * MINVERSE(array) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::inverse() + * Use the inverse() method in the MathTrig\MatrixFunctions class instead * * @param array $matrixValues A matrix of values * @@ -735,49 +423,17 @@ public static function MDETERM($matrixValues) */ public static function MINVERSE($matrixValues) { - $matrixData = []; - if (!is_array($matrixValues)) { - $matrixValues = [[$matrixValues]]; - } - - $row = $maxColumn = 0; - foreach ($matrixValues as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $column = 0; - foreach ($matrixRow as $matrixCell) { - if ((is_string($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixData[$row][$column] = $matrixCell; - ++$column; - } - if ($column > $maxColumn) { - $maxColumn = $column; - } - ++$row; - } - - $matrix = new Matrix($matrixData); - if (!$matrix->isSquare()) { - return Functions::VALUE(); - } - - if ($matrix->determinant() == 0.0) { - return Functions::NAN(); - } - - try { - return $matrix->inverse()->toArray(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::inverse($matrixValues); } /** * MMULT. * + * @Deprecated 1.18.0 + * + * @see MathTrig\MatrixFunctions::multiply() + * Use the multiply() method in the MathTrig\MatrixFunctions class instead + * * @param array $matrixData1 A matrix of values * @param array $matrixData2 A matrix of values * @@ -785,80 +441,25 @@ public static function MINVERSE($matrixValues) */ public static function MMULT($matrixData1, $matrixData2) { - $matrixAData = $matrixBData = []; - if (!is_array($matrixData1)) { - $matrixData1 = [[$matrixData1]]; - } - if (!is_array($matrixData2)) { - $matrixData2 = [[$matrixData2]]; - } - - try { - $rowA = 0; - foreach ($matrixData1 as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $columnA = 0; - foreach ($matrixRow as $matrixCell) { - if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixAData[$rowA][$columnA] = $matrixCell; - ++$columnA; - } - ++$rowA; - } - $matrixA = new Matrix($matrixAData); - $rowB = 0; - foreach ($matrixData2 as $matrixRow) { - if (!is_array($matrixRow)) { - $matrixRow = [$matrixRow]; - } - $columnB = 0; - foreach ($matrixRow as $matrixCell) { - if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { - return Functions::VALUE(); - } - $matrixBData[$rowB][$columnB] = $matrixCell; - ++$columnB; - } - ++$rowB; - } - $matrixB = new Matrix($matrixBData); - - if ($columnA != $rowB) { - return Functions::VALUE(); - } - - return $matrixA->multiply($matrixB)->toArray(); - } catch (MatrixException $ex) { - return Functions::VALUE(); - } + return MathTrig\MatrixFunctions::multiply($matrixData1, $matrixData2); } /** * MOD. * + * @Deprecated 1.18.0 + * + * @see MathTrig\Operations::mod() + * Use the mod() method in the MathTrig\Operations class instead + * * @param int $a Dividend * @param int $b Divisor * - * @return int|string Remainder, or a string containing an error + * @return array|float|int|string Remainder, or a string containing an error */ public static function MOD($a = 1, $b = 1) { - $a = (float) Functions::flattenSingleValue($a); - $b = (float) Functions::flattenSingleValue($b); - - if ($b == 0.0) { - return Functions::DIV0(); - } elseif (($a < 0.0) && ($b > 0.0)) { - return $b - fmod(abs($a), $b); - } elseif (($a > 0.0) && ($b < 0.0)) { - return $b + fmod($a, abs($b)); - } - - return fmod($a, $b); + return MathTrig\Operations::mod($a, $b); } /** @@ -866,30 +467,19 @@ public static function MOD($a = 1, $b = 1) * * Rounds a number to the nearest multiple of a specified value * + * @Deprecated 1.17.0 + * * @param float $number Number to round - * @param int $multiple Multiple to which you want to round $number + * @param array|int $multiple Multiple to which you want to round $number + * + * @return array|float|string Rounded Number, or a string containing an error * - * @return float|string Rounded Number, or a string containing an error + *@see MathTrig\Round::multiple() + * Use the multiple() method in the MathTrig\Mround class instead */ public static function MROUND($number, $multiple) { - $number = Functions::flattenSingleValue($number); - $multiple = Functions::flattenSingleValue($multiple); - - if ((is_numeric($number)) && (is_numeric($multiple))) { - if ($multiple == 0) { - return 0; - } - if ((self::SIGN($number)) == (self::SIGN($multiple))) { - $multiplier = 1 / $multiple; - - return round($number * $multiplier) / $multiplier; - } - - return Functions::NAN(); - } - - return Functions::VALUE(); + return MathTrig\Round::multiple($number, $multiple); } /** @@ -897,36 +487,18 @@ public static function MROUND($number, $multiple) * * Returns the ratio of the factorial of a sum of values to the product of factorials. * - * @param array of mixed Data Series + * @Deprecated 1.18.0 + * + * @See MathTrig\Factorial::multinomial() + * Use the multinomial method in the MathTrig\Factorial class instead + * + * @param mixed[] $args An array of mixed values for the Data Series * * @return float|string The result, or a string containing an error */ public static function MULTINOMIAL(...$args) { - $summer = 0; - $divisor = 1; - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if (is_numeric($arg)) { - if ($arg < 1) { - return Functions::NAN(); - } - $summer += floor($arg); - $divisor *= self::FACT($arg); - } else { - return Functions::VALUE(); - } - } - - // Return - if ($summer > 0) { - $summer = self::FACT($summer); - - return $summer / $divisor; - } - - return 0; + return MathTrig\Factorial::multinomial(...$args); } /** @@ -934,33 +506,18 @@ public static function MULTINOMIAL(...$args) * * Returns number rounded up to the nearest odd integer. * - * @param float $number Number to round + * @Deprecated 1.18.0 + * + * @See MathTrig\Round::odd() + * Use the odd method in the MathTrig\Round class instead + * + * @param array|float $number Number to round * - * @return int|string Rounded Number, or a string containing an error + * @return array|float|int|string Rounded Number, or a string containing an error */ public static function ODD($number) { - $number = Functions::flattenSingleValue($number); - - if ($number === null) { - return 1; - } elseif (is_bool($number)) { - return 1; - } elseif (is_numeric($number)) { - $significance = self::SIGN($number); - if ($significance == 0) { - return 1; - } - - $result = self::CEILING($number, $significance); - if ($result == self::EVEN($result)) { - $result += $significance; - } - - return (int) $result; - } - - return Functions::VALUE(); + return MathTrig\Round::odd($number); } /** @@ -968,27 +525,19 @@ public static function ODD($number) * * Computes x raised to the power y. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::power() + * Use the evaluate method in the MathTrig\Power class instead + * * @param float $x * @param float $y * - * @return float|string The result, or a string containing an error + * @return array|float|int|string The result, or a string containing an error */ public static function POWER($x = 0, $y = 2) { - $x = Functions::flattenSingleValue($x); - $y = Functions::flattenSingleValue($y); - - // Validate parameters - if ($x == 0.0 && $y == 0.0) { - return Functions::NAN(); - } elseif ($x == 0.0 && $y < 0.0) { - return Functions::DIV0(); - } - - // Return - $result = pow($x, $y); - - return (!is_nan($result) && !is_infinite($result)) ? $result : Functions::NAN(); + return MathTrig\Operations::power($x, $y); } /** @@ -996,38 +545,21 @@ public static function POWER($x = 0, $y = 2) * * PRODUCT returns the product of all the values and cells referenced in the argument list. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::product() + * Use the product method in the MathTrig\Operations class instead + * * Excel Function: * PRODUCT(value1[,value2[, ...]]) * - * @category Mathematical and Trigonometric Functions - * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function PRODUCT(...$args) { - // Return value - $returnValue = null; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = $arg; - } else { - $returnValue *= $arg; - } - } - } - - // Return - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return MathTrig\Operations::product(...$args); } /** @@ -1036,90 +568,60 @@ public static function PRODUCT(...$args) * QUOTIENT function returns the integer portion of a division. Numerator is the divided number * and denominator is the divisor. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Operations::quotient() + * Use the quotient method in the MathTrig\Operations class instead + * * Excel Function: * QUOTIENT(value1[,value2[, ...]]) * - * @category Mathematical and Trigonometric Functions - * - * @param mixed ...$args Data values + * @param mixed $numerator + * @param mixed $denominator * - * @return float - */ - public static function QUOTIENT(...$args) - { - // Return value - $returnValue = null; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = ($arg == 0) ? 0 : $arg; - } else { - if (($returnValue == 0) || ($arg == 0)) { - $returnValue = 0; - } else { - $returnValue /= $arg; - } - } - } - } - - // Return - return (int) $returnValue; + * @return array|int|string + */ + public static function QUOTIENT($numerator, $denominator) + { + return MathTrig\Operations::quotient($numerator, $denominator); } /** - * RAND. + * RAND/RANDBETWEEN. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Random::randBetween() + * Use the randBetween or randBetween method in the MathTrig\Random class instead * * @param int $min Minimal value * @param int $max Maximal value * - * @return int Random number + * @return array|float|int|string Random number */ public static function RAND($min = 0, $max = 0) { - $min = Functions::flattenSingleValue($min); - $max = Functions::flattenSingleValue($max); - - if ($min == 0 && $max == 0) { - return (mt_rand(0, 10000000)) / 10000000; - } - - return mt_rand($min, $max); + return MathTrig\Random::randBetween($min, $max); } + /** + * ROMAN. + * + * Converts a number to Roman numeral + * + * @Deprecated 1.17.0 + * + * @Ssee MathTrig\Roman::evaluate() + * Use the evaluate() method in the MathTrig\Roman class instead + * + * @param mixed $aValue Number to convert + * @param mixed $style Number indicating one of five possible forms + * + * @return array|string Roman numeral, or a string containing an error + */ public static function ROMAN($aValue, $style = 0) { - $aValue = Functions::flattenSingleValue($aValue); - $style = ($style === null) ? 0 : (int) Functions::flattenSingleValue($style); - if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { - return Functions::VALUE(); - } - $aValue = (int) $aValue; - if ($aValue == 0) { - return ''; - } - - $mill = ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM']; - $cent = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; - $tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; - $ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; - - $roman = ''; - while ($aValue > 5999) { - $roman .= 'M'; - $aValue -= 1000; - } - $m = self::romanCut($aValue, 1000); - $aValue %= 1000; - $c = self::romanCut($aValue, 100); - $aValue %= 100; - $t = self::romanCut($aValue, 10); - $aValue %= 10; - - return $roman . $mill[$m] . $cent[$c] . $tens[$t] . $ones[$aValue]; + return MathTrig\Roman::evaluate($aValue, $style); } /** @@ -1127,25 +629,19 @@ public static function ROMAN($aValue, $style = 0) * * Rounds a number up to a specified number of decimal places * - * @param float $number Number to round - * @param int $digits Number of digits to which you want to round $number + * @Deprecated 1.17.0 * - * @return float|string Rounded Number, or a string containing an error + * @See MathTrig\Round::up() + * Use the up() method in the MathTrig\Round class instead + * + * @param array|float $number Number to round + * @param array|int $digits Number of digits to which you want to round $number + * + * @return array|float|string Rounded Number, or a string containing an error */ public static function ROUNDUP($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); - - if ((is_numeric($number)) && (is_numeric($digits))) { - if ($number < 0.0) { - return round($number - 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_DOWN); - } - - return round($number + 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_DOWN); - } - - return Functions::VALUE(); + return MathTrig\Round::up($number, $digits); } /** @@ -1153,25 +649,19 @@ public static function ROUNDUP($number, $digits) * * Rounds a number down to a specified number of decimal places * - * @param float $number Number to round - * @param int $digits Number of digits to which you want to round $number + * @Deprecated 1.17.0 + * + * @See MathTrig\Round::down() + * Use the down() method in the MathTrig\Round class instead * - * @return float|string Rounded Number, or a string containing an error + * @param array|float $number Number to round + * @param array|int $digits Number of digits to which you want to round $number + * + * @return array|float|string Rounded Number, or a string containing an error */ public static function ROUNDDOWN($number, $digits) { - $number = Functions::flattenSingleValue($number); - $digits = Functions::flattenSingleValue($digits); - - if ((is_numeric($number)) && (is_numeric($digits))) { - if ($number < 0.0) { - return round($number + 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_UP); - } - - return round($number - 0.5 * pow(0.1, $digits), $digits, PHP_ROUND_HALF_UP); - } - - return Functions::VALUE(); + return MathTrig\Round::down($number, $digits); } /** @@ -1179,40 +669,21 @@ public static function ROUNDDOWN($number, $digits) * * Returns the sum of a power series * - * @param float $x Input value to the power series - * @param float $n Initial power to which you want to raise $x - * @param float $m Step by which to increase $n for each term in the series - * @param array of mixed Data Series + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @See MathTrig\SeriesSum::evaluate() + * Use the evaluate method in the MathTrig\SeriesSum class instead + * + * @param mixed $x Input value + * @param mixed $n Initial power + * @param mixed $m Step + * @param mixed[] $args An array of coefficients for the Data Series + * + * @return array|float|string The result, or a string containing an error */ - public static function SERIESSUM(...$args) + public static function SERIESSUM($x, $n, $m, ...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - $x = array_shift($aArgs); - $n = array_shift($aArgs); - $m = array_shift($aArgs); - - if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) { - // Calculate - $i = 0; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += $arg * pow($x, $n + ($m * $i++)); - } else { - return Functions::VALUE(); - } - } - - return $returnValue; - } - - return Functions::VALUE(); + return MathTrig\SeriesSum::evaluate($x, $n, $m, ...$args); } /** @@ -1221,26 +692,31 @@ public static function SERIESSUM(...$args) * Determines the sign of a number. Returns 1 if the number is positive, zero (0) * if the number is 0, and -1 if the number is negative. * - * @param float $number Number to round + * @Deprecated 1.18.0 + * + * @See MathTrig\Sign::evaluate() + * Use the evaluate method in the MathTrig\Sign class instead + * + * @param array|float $number Number to round * - * @return int|string sign value, or a string containing an error + * @return array|int|string sign value, or a string containing an error */ public static function SIGN($number) { - $number = Functions::flattenSingleValue($number); - - if (is_bool($number)) { - return (int) $number; - } - if (is_numeric($number)) { - if ($number == 0.0) { - return 0; - } - - return $number / abs($number); - } + return MathTrig\Sign::evaluate($number); + } - return Functions::VALUE(); + /** + * returnSign = returns 0/-1/+1. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::returnSign() + * Use the returnSign method in the MathTrig\Helpers class instead + */ + public static function returnSign(float $number): int + { + return MathTrig\Helpers::returnSign($number); } /** @@ -1248,57 +724,18 @@ public static function SIGN($number) * * Returns the square root of (number * pi). * - * @param float $number Number + * @Deprecated 1.18.0 + * + * @See MathTrig\Sqrt::sqrt() + * Use the pi method in the MathTrig\Sqrt class instead * - * @return float|string Square Root of Number * Pi, or a string containing an error + * @param array|float $number Number + * + * @return array|float|string Square Root of Number * Pi, or a string containing an error */ public static function SQRTPI($number) { - $number = Functions::flattenSingleValue($number); - - if (is_numeric($number)) { - if ($number < 0) { - return Functions::NAN(); - } - - return sqrt($number * M_PI); - } - - return Functions::VALUE(); - } - - protected static function filterHiddenArgs($cellReference, $args) - { - return array_filter( - $args, - function ($index) use ($cellReference) { - [, $row, $column] = explode('.', $index); - - return $cellReference->getWorksheet()->getRowDimension($row)->getVisible() && - $cellReference->getWorksheet()->getColumnDimension($column)->getVisible(); - }, - ARRAY_FILTER_USE_KEY - ); - } - - protected static function filterFormulaArgs($cellReference, $args) - { - return array_filter( - $args, - function ($index) use ($cellReference) { - [, $row, $column] = explode('.', $index); - if ($cellReference->getWorksheet()->cellExists($column . $row)) { - //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula - $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); - $cellFormula = !preg_match('/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', $cellReference->getWorksheet()->getCell($column . $row)->getValue()); - - return !$isFormula || $cellFormula; - } - - return true; - }, - ARRAY_FILTER_USE_KEY - ); + return MathTrig\Sqrt::pi($number); } /** @@ -1306,57 +743,25 @@ function ($index) use ($cellReference) { * * Returns a subtotal in a list or database. * - * @param int the number 1 to 11 that specifies which function to + * @Deprecated 1.18.0 + * + * @See MathTrig\Subtotal::evaluate() + * Use the evaluate method in the MathTrig\Subtotal class instead + * + * @param int $functionType + * A number 1 to 11 that specifies which function to * use in calculating subtotals within a range * list * Numbers 101 to 111 shadow the functions of 1 to 11 * but ignore any values in the range that are * in hidden rows or columns - * @param array of mixed Data Series + * @param mixed[] $args A mixed data series of values * * @return float|string */ - public static function SUBTOTAL(...$args) - { - $cellReference = array_pop($args); - $aArgs = Functions::flattenArrayIndexed($args); - $subtotal = array_shift($aArgs); - - // Calculate - if ((is_numeric($subtotal)) && (!is_string($subtotal))) { - if ($subtotal > 100) { - $aArgs = self::filterHiddenArgs($cellReference, $aArgs); - $subtotal -= 100; - } - - $aArgs = self::filterFormulaArgs($cellReference, $aArgs); - switch ($subtotal) { - case 1: - return Statistical::AVERAGE($aArgs); - case 2: - return Statistical::COUNT($aArgs); - case 3: - return Statistical::COUNTA($aArgs); - case 4: - return Statistical::MAX($aArgs); - case 5: - return Statistical::MIN($aArgs); - case 6: - return self::PRODUCT($aArgs); - case 7: - return Statistical::STDEV($aArgs); - case 8: - return Statistical::STDEVP($aArgs); - case 9: - return self::SUM($aArgs); - case 10: - return Statistical::VARFunc($aArgs); - case 11: - return Statistical::VARP($aArgs); - } - } - - return Functions::VALUE(); + public static function SUBTOTAL($functionType, ...$args) + { + return MathTrig\Subtotal::evaluate($functionType, ...$args); } /** @@ -1364,134 +769,67 @@ public static function SUBTOTAL(...$args) * * SUM computes the sum of all the values and cells referenced in the argument list. * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sum::sumErroringStrings() + * Use the sumErroringStrings method in the MathTrig\Sum class instead + * * Excel Function: * SUM(value1[,value2[, ...]]) * - * @category Mathematical and Trigonometric Functions - * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function SUM(...$args) { - $returnValue = 0; - - // Loop through the arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += $arg; - } - } - - return $returnValue; + return MathTrig\Sum::sumIgnoringStrings(...$args); } /** * SUMIF. * - * Counts the number of cells that contain numbers within the list of arguments + * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: - * SUMIF(value1[,value2[, ...]],condition) + * SUMIF(range, criteria, [sum_range]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * - * @param mixed $aArgs Data values - * @param string $condition the criteria that defines which cells will be summed - * @param mixed $sumArgs + * @see Statistical\Conditional::SUMIF() + * Use the SUMIF() method in the Statistical\Conditional class instead * - * @return float + * @param mixed $range Data values + * @param string $criteria the criteria that defines which cells will be summed + * @param mixed $sumRange + * + * @return float|string */ - public static function SUMIF($aArgs, $condition, $sumArgs = []) + public static function SUMIF($range, $criteria, $sumRange = []) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $sumArgs = Functions::flattenArray($sumArgs); - if (empty($sumArgs)) { - $sumArgs = $aArgs; - } - $condition = Functions::ifCondition($condition); - // Loop through arguments - foreach ($aArgs as $key => $arg) { - if (!is_numeric($arg)) { - $arg = str_replace('"', '""', $arg); - $arg = Calculation::wrapResult(strtoupper($arg)); - } - - $testCondition = '=' . $arg . $condition; - $sumValue = array_key_exists($key, $sumArgs) ? $sumArgs[$key] : 0; - - if (is_numeric($sumValue) && - Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is it a value within our criteria and only numeric can be added to the result - $returnValue += $sumValue; - } - } - - return $returnValue; + return Statistical\Conditional::SUMIF($range, $criteria, $sumRange); } /** * SUMIFS. * - * Counts the number of cells that contain numbers within the list of arguments + * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: - * SUMIFS(value1[,value2[, ...]],condition) + * SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::SUMIFS() + * Use the SUMIFS() method in the Statistical\Conditional class instead * * @param mixed $args Data values - * @param string $condition the criteria that defines which cells will be summed * - * @return float + * @return null|float|string */ public static function SUMIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = 0; - - $sumArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each sum and see if arguments and conditions are true - foreach ($sumArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue += $value; - } - } - - // Return - return $returnValue; + return Statistical\Conditional::SUMIFS(...$args); } /** @@ -1500,7 +838,10 @@ public static function SUMIFS(...$args) * Excel Function: * SUMPRODUCT(value1[,value2[, ...]]) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.18.0 + * + * @See MathTrig\Sum::product() + * Use the product method in the MathTrig\Sum class instead * * @param mixed ...$args Data values * @@ -1508,33 +849,7 @@ public static function SUMIFS(...$args) */ public static function SUMPRODUCT(...$args) { - $arrayList = $args; - - $wrkArray = Functions::flattenArray(array_shift($arrayList)); - $wrkCellCount = count($wrkArray); - - for ($i = 0; $i < $wrkCellCount; ++$i) { - if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { - $wrkArray[$i] = 0; - } - } - - foreach ($arrayList as $matrixData) { - $array2 = Functions::flattenArray($matrixData); - $count = count($array2); - if ($wrkCellCount != $count) { - return Functions::VALUE(); - } - - foreach ($array2 as $i => $val) { - if ((!is_numeric($val)) || (is_string($val))) { - $val = 0; - } - $wrkArray[$i] *= $val; - } - } - - return array_sum($wrkArray); + return MathTrig\Sum::product(...$args); } /** @@ -1542,103 +857,75 @@ public static function SUMPRODUCT(...$args) * * SUMSQ returns the sum of the squares of the arguments * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumSquare() + * Use the sumSquare method in the MathTrig\SumSquares class instead + * * Excel Function: * SUMSQ(value1[,value2[, ...]]) * - * @category Mathematical and Trigonometric Functions - * * @param mixed ...$args Data values * - * @return float + * @return float|string */ public static function SUMSQ(...$args) { - $returnValue = 0; - - // Loop through arguments - foreach (Functions::flattenArray($args) as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $returnValue += ($arg * $arg); - } - } - - return $returnValue; + return MathTrig\SumSquares::sumSquare(...$args); } /** * SUMX2MY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXSquaredMinusYSquared() + * Use the sumXSquaredMinusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMX2MY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { - $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXSquaredMinusYSquared($matrixData1, $matrixData2); } /** * SUMX2PY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXSquaredPlusYSquared() + * Use the sumXSquaredPlusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMX2PY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { - $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXSquaredPlusYSquared($matrixData1, $matrixData2); } /** * SUMXMY2. * + * @Deprecated 1.18.0 + * + * @See MathTrig\SumSquares::sumXMinusYSquared() + * Use the sumXMinusYSquared method in the MathTrig\SumSquares class instead + * * @param mixed[] $matrixData1 Matrix #1 * @param mixed[] $matrixData2 Matrix #2 * - * @return float + * @return float|string */ public static function SUMXMY2($matrixData1, $matrixData2) { - $array1 = Functions::flattenArray($matrixData1); - $array2 = Functions::flattenArray($matrixData2); - $count = min(count($array1), count($array2)); - - $result = 0; - for ($i = 0; $i < $count; ++$i) { - if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && - ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { - $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); - } - } - - return $result; + return MathTrig\SumSquares::sumXMinusYSquared($matrixData1, $matrixData2); } /** @@ -1646,30 +933,19 @@ public static function SUMXMY2($matrixData1, $matrixData2) * * Truncates value to the number of fractional digits by number_digits. * + * @Deprecated 1.17.0 + * + * @see MathTrig\Trunc::evaluate() + * Use the evaluate() method in the MathTrig\Trunc class instead + * * @param float $value * @param int $digits * - * @return float|string Truncated value, or a string containing an error + * @return array|float|string Truncated value, or a string containing an error */ public static function TRUNC($value = 0, $digits = 0) { - $value = Functions::flattenSingleValue($value); - $digits = Functions::flattenSingleValue($digits); - - // Validate parameters - if ((!is_numeric($value)) || (!is_numeric($digits))) { - return Functions::VALUE(); - } - $digits = floor($digits); - - // Truncate - $adjust = pow(10, $digits); - - if (($digits > 0) && (rtrim((int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { - return $value; - } - - return ((int) ($value * $adjust)) / $adjust; + return MathTrig\Trunc::evaluate($value, $digits); } /** @@ -1677,21 +953,18 @@ public static function TRUNC($value = 0, $digits = 0) * * Returns the secant of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The secant of the angle + * @See MathTrig\Trig\Secant::sec() + * Use the sec method in the MathTrig\Trig\Secant class instead + * + * @param array|float $angle Number + * + * @return array|float|string The secant of the angle */ public static function SEC($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = cos($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Secant::sec($angle); } /** @@ -1699,21 +972,18 @@ public static function SEC($angle) * * Returns the hyperbolic secant of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The hyperbolic secant of the angle + * @See MathTrig\Trig\Secant::sech() + * Use the sech method in the MathTrig\Trig\Secant class instead + * + * @param array|float $angle Number + * + * @return array|float|string The hyperbolic secant of the angle */ public static function SECH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = cosh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Secant::sech($angle); } /** @@ -1721,21 +991,18 @@ public static function SECH($angle) * * Returns the cosecant of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The cosecant of the angle + * @See MathTrig\Trig\Cosecant::csc() + * Use the csc method in the MathTrig\Trig\Cosecant class instead + * + * @param array|float $angle Number + * + * @return array|float|string The cosecant of the angle */ public static function CSC($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = sin($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cosecant::csc($angle); } /** @@ -1743,21 +1010,18 @@ public static function CSC($angle) * * Returns the hyperbolic cosecant of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The hyperbolic cosecant of the angle + * @See MathTrig\Trig\Cosecant::csch() + * Use the csch method in the MathTrig\Trig\Cosecant class instead + * + * @param array|float $angle Number + * + * @return array|float|string The hyperbolic cosecant of the angle */ public static function CSCH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = sinh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cosecant::csch($angle); } /** @@ -1765,21 +1029,18 @@ public static function CSCH($angle) * * Returns the cotangent of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The cotangent of the angle + * @See MathTrig\Trig\Cotangent::cot() + * Use the cot method in the MathTrig\Trig\Cotangent class instead + * + * @param array|float $angle Number + * + * @return array|float|string The cotangent of the angle */ public static function COT($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = tan($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cotangent::cot($angle); } /** @@ -1787,21 +1048,18 @@ public static function COT($angle) * * Returns the hyperbolic cotangent of an angle. * - * @param float $angle Number + * @Deprecated 1.18.0 * - * @return float|string The hyperbolic cotangent of the angle + * @See MathTrig\Trig\Cotangent::coth() + * Use the coth method in the MathTrig\Trig\Cotangent class instead + * + * @param array|float $angle Number + * + * @return array|float|string The hyperbolic cotangent of the angle */ public static function COTH($angle) { - $angle = Functions::flattenSingleValue($angle); - - if (!is_numeric($angle)) { - return Functions::VALUE(); - } - - $result = tanh($angle); - - return ($result == 0.0) ? Functions::DIV0() : 1 / $result; + return MathTrig\Trig\Cotangent::coth($angle); } /** @@ -1809,19 +1067,35 @@ public static function COTH($angle) * * Returns the arccotangent of a number. * - * @param float $number Number + * @Deprecated 1.18.0 * - * @return float|string The arccotangent of the number + * @See MathTrig\Trig\Cotangent::acot() + * Use the acot method in the MathTrig\Trig\Cotangent class instead + * + * @param array|float $number Number + * + * @return array|float|string The arccotangent of the number */ public static function ACOT($number) { - $number = Functions::flattenSingleValue($number); - - if (!is_numeric($number)) { - return Functions::VALUE(); - } + return MathTrig\Trig\Cotangent::acot($number); + } - return (M_PI / 2) - atan($number); + /** + * Return NAN or value depending on argument. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::numberOrNan() + * Use the numberOrNan method in the MathTrig\Helpers class instead + * + * @param float $result Number + * + * @return float|string + */ + public static function numberOrNan($result) + { + return MathTrig\Helpers::numberOrNan($result); } /** @@ -1829,20 +1103,418 @@ public static function ACOT($number) * * Returns the hyperbolic arccotangent of a number. * - * @param float $number Number + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cotangent::acoth() + * Use the acoth method in the MathTrig\Trig\Cotangent class instead * - * @return float|string The hyperbolic arccotangent of the number + * @param array|float $number Number + * + * @return array|float|string The hyperbolic arccotangent of the number */ public static function ACOTH($number) { - $number = Functions::flattenSingleValue($number); + return MathTrig\Trig\Cotangent::acoth($number); + } - if (!is_numeric($number)) { - return Functions::VALUE(); - } + /** + * ROUND. + * + * Returns the result of builtin function round after validating args. + * + * @Deprecated 1.17.0 + * + * @See MathTrig\Round::round() + * Use the round() method in the MathTrig\Round class instead + * + * @param array|mixed $number Should be numeric + * @param array|mixed $precision Should be int + * + * @return array|float|string Rounded number + */ + public static function builtinROUND($number, $precision) + { + return MathTrig\Round::round($number, $precision); + } + + /** + * ABS. + * + * Returns the result of builtin function abs after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Absolute::evaluate() + * Use the evaluate method in the MathTrig\Absolute class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|int|string Rounded number + */ + public static function builtinABS($number) + { + return MathTrig\Absolute::evaluate($number); + } + + /** + * ACOS. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::acos() + * Use the acos method in the MathTrig\Trig\Cosine class instead + * + * Returns the result of builtin function acos after validating args. + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinACOS($number) + { + return MathTrig\Trig\Cosine::acos($number); + } + + /** + * ACOSH. + * + * Returns the result of builtin function acosh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::acosh() + * Use the acosh method in the MathTrig\Trig\Cosine class instead + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinACOSH($number) + { + return MathTrig\Trig\Cosine::acosh($number); + } + + /** + * ASIN. + * + * Returns the result of builtin function asin after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::asin() + * Use the asin method in the MathTrig\Trig\Sine class instead + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinASIN($number) + { + return MathTrig\Trig\Sine::asin($number); + } + + /** + * ASINH. + * + * Returns the result of builtin function asinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::asinh() + * Use the asinh method in the MathTrig\Trig\Sine class instead + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinASINH($number) + { + return MathTrig\Trig\Sine::asinh($number); + } + + /** + * ATAN. + * + * Returns the result of builtin function atan after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atan() + * Use the atan method in the MathTrig\Trig\Tangent class instead + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinATAN($number) + { + return MathTrig\Trig\Tangent::atan($number); + } + + /** + * ATANH. + * + * Returns the result of builtin function atanh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::atanh() + * Use the atanh method in the MathTrig\Trig\Tangent class instead + * + * @param array|float $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinATANH($number) + { + return MathTrig\Trig\Tangent::atanh($number); + } + + /** + * COS. + * + * Returns the result of builtin function cos after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::cos() + * Use the cos method in the MathTrig\Trig\Cosine class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinCOS($number) + { + return MathTrig\Trig\Cosine::cos($number); + } + + /** + * COSH. + * + * Returns the result of builtin function cos after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Cosine::cosh() + * Use the cosh method in the MathTrig\Trig\Cosine class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinCOSH($number) + { + return MathTrig\Trig\Cosine::cosh($number); + } + + /** + * DEGREES. + * + * Returns the result of builtin function rad2deg after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Angle::toDegrees() + * Use the toDegrees method in the MathTrig\Angle class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinDEGREES($number) + { + return MathTrig\Angle::toDegrees($number); + } + + /** + * EXP. + * + * Returns the result of builtin function exp after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Exp::evaluate() + * Use the evaluate method in the MathTrig\Exp class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinEXP($number) + { + return MathTrig\Exp::evaluate($number); + } + + /** + * LN. + * + * Returns the result of builtin function log after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Logarithms::natural() + * Use the natural method in the MathTrig\Logarithms class instead + * + * @param mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinLN($number) + { + return MathTrig\Logarithms::natural($number); + } + + /** + * LOG10. + * + * Returns the result of builtin function log after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Logarithms::base10() + * Use the natural method in the MathTrig\Logarithms class instead + * + * @param mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinLOG10($number) + { + return MathTrig\Logarithms::base10($number); + } + + /** + * RADIANS. + * + * Returns the result of builtin function deg2rad after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Angle::toRadians() + * Use the toRadians method in the MathTrig\Angle class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinRADIANS($number) + { + return MathTrig\Angle::toRadians($number); + } + + /** + * SIN. + * + * Returns the result of builtin function sin after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::evaluate() + * Use the sin method in the MathTrig\Trig\Sine class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string sine + */ + public static function builtinSIN($number) + { + return MathTrig\Trig\Sine::sin($number); + } + + /** + * SINH. + * + * Returns the result of builtin function sinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Sine::sinh() + * Use the sinh method in the MathTrig\Trig\Sine class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinSINH($number) + { + return MathTrig\Trig\Sine::sinh($number); + } + + /** + * SQRT. + * + * Returns the result of builtin function sqrt after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Sqrt::sqrt() + * Use the sqrt method in the MathTrig\Sqrt class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinSQRT($number) + { + return MathTrig\Sqrt::sqrt($number); + } + + /** + * TAN. + * + * Returns the result of builtin function tan after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::tan() + * Use the tan method in the MathTrig\Trig\Tangent class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinTAN($number) + { + return MathTrig\Trig\Tangent::tan($number); + } - $result = log(($number + 1) / ($number - 1)) / 2; + /** + * TANH. + * + * Returns the result of builtin function sinh after validating args. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Trig\Tangent::tanh() + * Use the tanh method in the MathTrig\Trig\Tangent class instead + * + * @param array|mixed $number Should be numeric + * + * @return array|float|string Rounded number + */ + public static function builtinTANH($number) + { + return MathTrig\Trig\Tangent::tanh($number); + } - return is_nan($result) ? Functions::NAN() : $result; + /** + * Many functions accept null/false/true argument treated as 0/0/1. + * + * @Deprecated 1.18.0 + * + * @See MathTrig\Helpers::validateNumericNullBool() + * Use the validateNumericNullBool method in the MathTrig\Helpers class instead + * + * @param mixed $number + */ + public static function nullFalseTrueToNumber(&$number): void + { + $number = Functions::flattenSingleValue($number); + if ($number === null) { + $number = 0; + } elseif (is_bool($number)) { + $number = (int) $number; + } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php new file mode 100644 index 00000000..f21c6b73 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Absolute.php @@ -0,0 +1,37 @@ +getMessage(); + } + + return abs($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php new file mode 100644 index 00000000..cbeec6f4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Angle.php @@ -0,0 +1,63 @@ +getMessage(); + } + + return rad2deg($number); + } + + /** + * RADIANS. + * + * Returns the result of builtin function deg2rad after validating args. + * + * @param mixed $number Should be numeric, or can be an array of numbers + * + * @return array|float|string Rounded number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function toRadians($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return deg2rad($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php new file mode 100644 index 00000000..ee488505 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Arabic.php @@ -0,0 +1,112 @@ + 1000, + 'D' => 500, + 'C' => 100, + 'L' => 50, + 'X' => 10, + 'V' => 5, + 'I' => 1, + ]; + + /** + * Recursively calculate the arabic value of a roman numeral. + * + * @param int $sum + * @param int $subtract + * + * @return int + */ + private static function calculateArabic(array $roman, &$sum = 0, $subtract = 0) + { + $numeral = array_shift($roman); + if (!isset(self::ROMAN_LOOKUP[$numeral])) { + throw new Exception('Invalid character detected'); + } + + $arabic = self::ROMAN_LOOKUP[$numeral]; + if (count($roman) > 0 && isset(self::ROMAN_LOOKUP[$roman[0]]) && $arabic < self::ROMAN_LOOKUP[$roman[0]]) { + $subtract += $arabic; + } else { + $sum += ($arabic - $subtract); + $subtract = 0; + } + + if (count($roman) > 0) { + self::calculateArabic($roman, $sum, $subtract); + } + + return $sum; + } + + /** + * @param mixed $value + */ + private static function mollifyScrutinizer($value): array + { + return is_array($value) ? $value : []; + } + + private static function strSplit(string $roman): array + { + $rslt = str_split($roman); + + return self::mollifyScrutinizer($rslt); + } + + /** + * ARABIC. + * + * Converts a Roman numeral to an Arabic numeral. + * + * Excel Function: + * ARABIC(text) + * + * @param mixed $roman Should be a string, or can be an array of strings + * + * @return array|int|string the arabic numberal contrived from the roman numeral + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function evaluate($roman) + { + if (is_array($roman)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $roman); + } + + // An empty string should return 0 + $roman = substr(trim(strtoupper((string) $roman)), 0, 255); + if ($roman === '') { + return 0; + } + + // Convert the roman numeral to an arabic number + $negativeNumber = $roman[0] === '-'; + if ($negativeNumber) { + $roman = substr($roman, 1); + } + + try { + $arabic = self::calculateArabic(self::strSplit($roman)); + } catch (Exception $e) { + return ExcelError::VALUE(); // Invalid character detected + } + + if ($negativeNumber) { + $arabic *= -1; // The number should be negative + } + + return $arabic; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php new file mode 100644 index 00000000..2fec9473 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Base.php @@ -0,0 +1,68 @@ +getMessage(); + } + + return self::calculate($number, $radix, $minLength); + } + + /** + * @param mixed $minLength + */ + private static function calculate(float $number, int $radix, $minLength): string + { + if ($minLength === null || is_numeric($minLength)) { + if ($number < 0 || $number >= 2 ** 53 || $radix < 2 || $radix > 36) { + return ExcelError::NAN(); // Numeric range constraints + } + + $outcome = strtoupper((string) base_convert("$number", 10, $radix)); + if ($minLength !== null) { + $outcome = str_pad($outcome, (int) $minLength, '0', STR_PAD_LEFT); // String padding + } + + return $outcome; + } + + return ExcelError::VALUE(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php new file mode 100644 index 00000000..635f1bbb --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Ceiling.php @@ -0,0 +1,167 @@ +getMessage(); + } + + return self::argumentsOk((float) $number, (float) $significance); + } + + /** + * CEILING.MATH. + * + * Round a number down to the nearest integer or to the nearest multiple of significance. + * + * Excel Function: + * CEILING.MATH(number[,significance[,mode]]) + * + * @param mixed $number Number to round + * Or can be an array of values + * @param mixed $significance Significance + * Or can be an array of values + * @param array|int $mode direction to round negative numbers + * Or can be an array of values + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function math($number, $significance = null, $mode = 0) + { + if (is_array($number) || is_array($significance) || is_array($mode)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); + $mode = Helpers::validateNumericNullSubstitution($mode, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (empty($significance * $number)) { + return 0.0; + } + if (self::ceilingMathTest((float) $significance, (float) $number, (int) $mode)) { + return floor($number / $significance) * $significance; + } + + return ceil($number / $significance) * $significance; + } + + /** + * CEILING.PRECISE. + * + * Rounds number up, away from zero, to the nearest multiple of significance. + * + * Excel Function: + * CEILING.PRECISE(number[,significance]) + * + * @param mixed $number the number you want to round + * Or can be an array of values + * @param array|float $significance the multiple to which you want to round + * Or can be an array of values + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function precise($number, $significance = 1) + { + if (is_array($number) || is_array($significance)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (!$significance) { + return 0.0; + } + $result = $number / abs($significance); + + return ceil($result) * $significance * (($significance < 0) ? -1 : 1); + } + + /** + * Let CEILINGMATH complexity pass Scrutinizer. + */ + private static function ceilingMathTest(float $significance, float $number, int $mode): bool + { + return ((float) $significance < 0) || ((float) $number < 0 && !empty($mode)); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOk(float $number, float $significance) + { + if (empty($number * $significance)) { + return 0.0; + } + if (Helpers::returnSign($number) == Helpers::returnSign($significance)) { + return ceil($number / $significance) * $significance; + } + + return ExcelError::NAN(); + } + + private static function floorCheck1Arg(): void + { + $compatibility = Functions::getCompatibilityMode(); + if ($compatibility === Functions::COMPATIBILITY_EXCEL) { + throw new Exception('Excel requires 2 arguments for CEILING'); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php new file mode 100644 index 00000000..5a652da0 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Combinations.php @@ -0,0 +1,91 @@ +getMessage(); + } + + return round(Factorial::fact($numObjs) / Factorial::fact($numObjs - $numInSet)) / Factorial::fact($numInSet); + } + + /** + * COMBINA. + * + * Returns the number of combinations for a given number of items. Use COMBIN to + * determine the total possible number of groups for a given number of items. + * + * Excel Function: + * COMBINA(numObjs,numInSet) + * + * @param mixed $numObjs Number of different objects, or can be an array of numbers + * @param mixed $numInSet Number of objects in each combination, or can be an array of numbers + * + * @return array|float|int|string Number of combinations, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function withRepetition($numObjs, $numInSet) + { + if (is_array($numObjs) || is_array($numInSet)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); + } + + try { + $numObjs = Helpers::validateNumericNullSubstitution($numObjs, null); + $numInSet = Helpers::validateNumericNullSubstitution($numInSet, null); + Helpers::validateNotNegative($numInSet); + Helpers::validateNotNegative($numObjs); + $numObjs = (int) $numObjs; + $numInSet = (int) $numInSet; + // Microsoft documentation says following is true, but Excel + // does not enforce this restriction. + //Helpers::validateNotNegative($numObjs - $numInSet); + if ($numObjs === 0) { + Helpers::validateNotNegative(-$numInSet); + + return 1; + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return round( + Factorial::fact($numObjs + $numInSet - 1) / Factorial::fact($numObjs - 1) + ) / Factorial::fact($numInSet); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php new file mode 100644 index 00000000..f65c2c18 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Exp.php @@ -0,0 +1,37 @@ +getMessage(); + } + + return exp($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php new file mode 100644 index 00000000..b6883e29 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Factorial.php @@ -0,0 +1,125 @@ +getMessage(); + } + + $factLoop = floor($factVal); + if ($factVal > $factLoop) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return Statistical\Distributions\Gamma::gammaValue($factVal + 1); + } + } + + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + } + + return $factorial; + } + + /** + * FACTDOUBLE. + * + * Returns the double factorial of a number. + * + * Excel Function: + * FACTDOUBLE(factVal) + * + * @param array|float $factVal Factorial Value, or can be an array of numbers + * + * @return array|float|int|string Double Factorial, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function factDouble($factVal) + { + if (is_array($factVal)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $factVal); + } + + try { + $factVal = Helpers::validateNumericNullSubstitution($factVal, 0); + Helpers::validateNotNegative($factVal); + } catch (Exception $e) { + return $e->getMessage(); + } + + $factLoop = floor($factVal); + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop; + $factLoop -= 2; + } + + return $factorial; + } + + /** + * MULTINOMIAL. + * + * Returns the ratio of the factorial of a sum of values to the product of factorials. + * + * @param mixed[] $args An array of mixed values for the Data Series + * + * @return float|string The result, or a string containing an error + */ + public static function multinomial(...$args) + { + $summer = 0; + $divisor = 1; + + try { + // Loop through arguments + foreach (Functions::flattenArray($args) as $argx) { + $arg = Helpers::validateNumericNullSubstitution($argx, null); + Helpers::validateNotNegative($arg); + $arg = (int) $arg; + $summer += $arg; + $divisor *= self::fact($arg); + } + } catch (Exception $e) { + return $e->getMessage(); + } + + $summer = self::fact($summer); + + return $summer / $divisor; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php new file mode 100644 index 00000000..2199dda0 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Floor.php @@ -0,0 +1,195 @@ +getMessage(); + } + + return self::argumentsOk((float) $number, (float) $significance); + } + + /** + * FLOOR.MATH. + * + * Round a number down to the nearest integer or to the nearest multiple of significance. + * + * Excel Function: + * FLOOR.MATH(number[,significance[,mode]]) + * + * @param mixed $number Number to round + * Or can be an array of values + * @param mixed $significance Significance + * Or can be an array of values + * @param mixed $mode direction to round negative numbers + * Or can be an array of values + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function math($number, $significance = null, $mode = 0) + { + if (is_array($number) || is_array($significance) || is_array($mode)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance, $mode); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, ($number < 0) ? -1 : 1); + $mode = Helpers::validateNumericNullSubstitution($mode, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::argsOk((float) $number, (float) $significance, (int) $mode); + } + + /** + * FLOOR.PRECISE. + * + * Rounds number down, toward zero, to the nearest multiple of significance. + * + * Excel Function: + * FLOOR.PRECISE(number[,significance]) + * + * @param array|float $number Number to round + * Or can be an array of values + * @param array|float $significance Significance + * Or can be an array of values + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function precise($number, $significance = 1) + { + if (is_array($number) || is_array($significance)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $significance); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $significance = Helpers::validateNumericNullSubstitution($significance, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::argumentsOkPrecise((float) $number, (float) $significance); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOkPrecise(float $number, float $significance) + { + if ($significance == 0.0) { + return ExcelError::DIV0(); + } + if ($number == 0.0) { + return 0.0; + } + + return floor($number / abs($significance)) * abs($significance); + } + + /** + * Avoid Scrutinizer complexity problems. + * + * @return float|string Rounded Number, or a string containing an error + */ + private static function argsOk(float $number, float $significance, int $mode) + { + if (!$significance) { + return ExcelError::DIV0(); + } + if (!$number) { + return 0.0; + } + if (self::floorMathTest($number, $significance, $mode)) { + return ceil($number / $significance) * $significance; + } + + return floor($number / $significance) * $significance; + } + + /** + * Let FLOORMATH complexity pass Scrutinizer. + */ + private static function floorMathTest(float $number, float $significance, int $mode): bool + { + return Helpers::returnSign($significance) == -1 || (Helpers::returnSign($number) == -1 && !empty($mode)); + } + + /** + * Avoid Scrutinizer problems concerning complexity. + * + * @return float|string + */ + private static function argumentsOk(float $number, float $significance) + { + if ($significance == 0.0) { + return ExcelError::DIV0(); + } + if ($number == 0.0) { + return 0.0; + } + if (Helpers::returnSign($significance) == 1) { + return floor($number / $significance) * $significance; + } + if (Helpers::returnSign($number) == -1 && Helpers::returnSign($significance) == -1) { + return floor($number / $significance) * $significance; + } + + return ExcelError::NAN(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php new file mode 100644 index 00000000..f7035998 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Gcd.php @@ -0,0 +1,70 @@ +getMessage(); + } + + if (count($arrayArgs) <= 0) { + return ExcelError::VALUE(); + } + $gcd = (int) array_pop($arrayArgs); + do { + $gcd = self::evaluateGCD($gcd, (int) array_pop($arrayArgs)); + } while (!empty($arrayArgs)); + + return $gcd; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php new file mode 100644 index 00000000..348aa5b3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Helpers.php @@ -0,0 +1,130 @@ += 0. + * + * @param float|int $number + */ + public static function validateNotNegative($number, ?string $except = null): void + { + if ($number >= 0) { + return; + } + + throw new Exception($except ?? ExcelError::NAN()); + } + + /** + * Confirm number > 0. + * + * @param float|int $number + */ + public static function validatePositive($number, ?string $except = null): void + { + if ($number > 0) { + return; + } + + throw new Exception($except ?? ExcelError::NAN()); + } + + /** + * Confirm number != 0. + * + * @param float|int $number + */ + public static function validateNotZero($number): void + { + if ($number) { + return; + } + + throw new Exception(ExcelError::DIV0()); + } + + public static function returnSign(float $number): int + { + return $number ? (($number > 0) ? 1 : -1) : 0; + } + + public static function getEven(float $number): float + { + $significance = 2 * self::returnSign($number); + + return $significance ? (ceil($number / $significance) * $significance) : 0; + } + + /** + * Return NAN or value depending on argument. + * + * @param float $result Number + * + * @return float|string + */ + public static function numberOrNan($result) + { + return is_nan($result) ? ExcelError::NAN() : $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php new file mode 100644 index 00000000..f7f7764b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/IntClass.php @@ -0,0 +1,40 @@ +getMessage(); + } + + return (int) floor($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php new file mode 100644 index 00000000..3b23c1da --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Lcm.php @@ -0,0 +1,111 @@ + 1; --$i) { + if (($value % $i) == 0) { + $factorArray = array_merge($factorArray, self::factors($value / $i)); + $factorArray = array_merge($factorArray, self::factors($i)); + if ($i <= sqrt($value)) { + break; + } + } + } + if (!empty($factorArray)) { + rsort($factorArray); + + return $factorArray; + } + + return [(int) $value]; + } + + /** + * LCM. + * + * Returns the lowest common multiplier of a series of numbers + * The least common multiple is the smallest positive integer that is a multiple + * of all integer arguments number1, number2, and so on. Use LCM to add fractions + * with different denominators. + * + * Excel Function: + * LCM(number1[,number2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int|string Lowest Common Multiplier, or a string containing an error + */ + public static function evaluate(...$args) + { + try { + $arrayArgs = []; + $anyZeros = 0; + $anyNonNulls = 0; + foreach (Functions::flattenArray($args) as $value1) { + $anyNonNulls += (int) ($value1 !== null); + $value = Helpers::validateNumericNullSubstitution($value1, 1); + Helpers::validateNotNegative($value); + $arrayArgs[] = (int) $value; + $anyZeros += (int) !((bool) $value); + } + self::testNonNulls($anyNonNulls); + if ($anyZeros) { + return 0; + } + } catch (Exception $e) { + return $e->getMessage(); + } + + $returnValue = 1; + $allPoweredFactors = []; + // Loop through arguments + foreach ($arrayArgs as $value) { + $myFactors = self::factors(floor($value)); + $myCountedFactors = array_count_values($myFactors); + $myPoweredFactors = []; + foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { + $myPoweredFactors[$myCountedFactor] = $myCountedFactor ** $myCountedPower; + } + self::processPoweredFactors($allPoweredFactors, $myPoweredFactors); + } + foreach ($allPoweredFactors as $allPoweredFactor) { + $returnValue *= (int) $allPoweredFactor; + } + + return $returnValue; + } + + private static function processPoweredFactors(array &$allPoweredFactors, array &$myPoweredFactors): void + { + foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { + if (isset($allPoweredFactors[$myPoweredValue])) { + if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } else { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } + } + + private static function testNonNulls(int $anyNonNulls): void + { + if (!$anyNonNulls) { + throw new Exception(ExcelError::VALUE()); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php new file mode 100644 index 00000000..7b07f09d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Logarithms.php @@ -0,0 +1,102 @@ +getMessage(); + } + + return log($number, $base); + } + + /** + * LOG10. + * + * Returns the result of builtin function log after validating args. + * + * @param mixed $number Should be numeric + * Or can be an array of values + * + * @return array|float|string Rounded number + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function base10($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + Helpers::validatePositive($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return log10($number); + } + + /** + * LN. + * + * Returns the result of builtin function log after validating args. + * + * @param mixed $number Should be numeric + * Or can be an array of values + * + * @return array|float|string Rounded number + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function natural($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + Helpers::validatePositive($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return log($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php new file mode 100644 index 00000000..5a5125a8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/MatrixFunctions.php @@ -0,0 +1,179 @@ +getMessage(); + } + + if ($step === 0) { + return array_chunk( + array_fill(0, $rows * $columns, $start), + max($columns, 1) + ); + } + + return array_chunk( + range($start, $start + (($rows * $columns - 1) * $step), $step), + max($columns, 1) + ); + } + + /** + * MDETERM. + * + * Returns the matrix determinant of an array. + * + * Excel Function: + * MDETERM(array) + * + * @param mixed $matrixValues A matrix of values + * + * @return float|string The result, or a string containing an error + */ + public static function determinant($matrixValues) + { + try { + $matrix = self::getMatrix($matrixValues); + + return $matrix->determinant(); + } catch (MatrixException $ex) { + return ExcelError::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MINVERSE. + * + * Returns the inverse matrix for the matrix stored in an array. + * + * Excel Function: + * MINVERSE(array) + * + * @param mixed $matrixValues A matrix of values + * + * @return array|string The result, or a string containing an error + */ + public static function inverse($matrixValues) + { + try { + $matrix = self::getMatrix($matrixValues); + + return $matrix->inverse()->toArray(); + } catch (MatrixDiv0Exception $e) { + return ExcelError::NAN(); + } catch (MatrixException $e) { + return ExcelError::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MMULT. + * + * @param mixed $matrixData1 A matrix of values + * @param mixed $matrixData2 A matrix of values + * + * @return array|string The result, or a string containing an error + */ + public static function multiply($matrixData1, $matrixData2) + { + try { + $matrixA = self::getMatrix($matrixData1); + $matrixB = self::getMatrix($matrixData2); + + return $matrixA->multiply($matrixB)->toArray(); + } catch (MatrixException $ex) { + return ExcelError::VALUE(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + + /** + * MUnit. + * + * @param mixed $dimension Number of rows and columns + * + * @return array|string The result, or a string containing an error + */ + public static function identity($dimension) + { + try { + $dimension = (int) Helpers::validateNumericNullBool($dimension); + Helpers::validatePositive($dimension, ExcelError::VALUE()); + $matrix = Builder::createIdentityMatrix($dimension, 0)->toArray(); + + return $matrix; + } catch (Exception $e) { + return $e->getMessage(); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php new file mode 100644 index 00000000..7fd30233 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Operations.php @@ -0,0 +1,164 @@ +getMessage(); + } + + if (($dividend < 0.0) && ($divisor > 0.0)) { + return $divisor - fmod(abs($dividend), $divisor); + } + if (($dividend > 0.0) && ($divisor < 0.0)) { + return $divisor + fmod($dividend, abs($divisor)); + } + + return fmod($dividend, $divisor); + } + + /** + * POWER. + * + * Computes x raised to the power y. + * + * @param array|float|int $x + * Or can be an array of values + * @param array|float|int $y + * Or can be an array of values + * + * @return array|float|int|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function power($x, $y) + { + if (is_array($x) || is_array($y)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $x, $y); + } + + try { + $x = Helpers::validateNumericNullBool($x); + $y = Helpers::validateNumericNullBool($y); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Validate parameters + if (!$x && !$y) { + return ExcelError::NAN(); + } + if (!$x && $y < 0.0) { + return ExcelError::DIV0(); + } + + // Return + $result = $x ** $y; + + return Helpers::numberOrNan($result); + } + + /** + * PRODUCT. + * + * PRODUCT returns the product of all the values and cells referenced in the argument list. + * + * Excel Function: + * PRODUCT(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string + */ + public static function product(...$args) + { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (Functions::flattenArray($args) as $arg) { + // Is it a numeric value? + if (is_numeric($arg)) { + if ($returnValue === null) { + $returnValue = $arg; + } else { + $returnValue *= $arg; + } + } else { + return ExcelError::VALUE(); + } + } + + // Return + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } + + /** + * QUOTIENT. + * + * QUOTIENT function returns the integer portion of a division. Numerator is the divided number + * and denominator is the divisor. + * + * Excel Function: + * QUOTIENT(value1,value2) + * + * @param mixed $numerator Expect float|int + * Or can be an array of values + * @param mixed $denominator Expect float|int + * Or can be an array of values + * + * @return array|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function quotient($numerator, $denominator) + { + if (is_array($numerator) || is_array($denominator)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $numerator, $denominator); + } + + try { + $numerator = Helpers::validateNumericNullSubstitution($numerator, 0); + $denominator = Helpers::validateNumericNullSubstitution($denominator, 0); + Helpers::validateNotZero($denominator); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (int) ($numerator / $denominator); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php new file mode 100644 index 00000000..b9fcfc73 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Random.php @@ -0,0 +1,99 @@ +getMessage(); + } + + return mt_rand($min, $max); + } + + /** + * RANDARRAY. + * + * Generates a list of sequential numbers in an array. + * + * Excel Function: + * RANDARRAY([rows],[columns],[start],[step]) + * + * @param mixed $rows the number of rows to return, defaults to 1 + * @param mixed $columns the number of columns to return, defaults to 1 + * @param mixed $min the minimum number to be returned, defaults to 0 + * @param mixed $max the maximum number to be returned, defaults to 1 + * @param bool $wholeNumber the type of numbers to return: + * False - Decimal numbers to 15 decimal places. (default) + * True - Whole (integer) numbers + * + * @return array|string The resulting array, or a string containing an error + */ + public static function randArray($rows = 1, $columns = 1, $min = 0, $max = 1, $wholeNumber = false) + { + try { + $rows = (int) Helpers::validateNumericNullSubstitution($rows, 1); + Helpers::validatePositive($rows); + $columns = (int) Helpers::validateNumericNullSubstitution($columns, 1); + Helpers::validatePositive($columns); + $min = Helpers::validateNumericNullSubstitution($min, 1); + $max = Helpers::validateNumericNullSubstitution($max, 1); + + if ($max <= $min) { + return ExcelError::VALUE(); + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return array_chunk( + array_map( + function () use ($min, $max, $wholeNumber) { + return $wholeNumber + ? mt_rand((int) $min, (int) $max) + : (mt_rand() / mt_getrandmax()) * ($max - $min) + $min; + }, + array_fill(0, $rows * $columns, $min) + ), + max($columns, 1) + ); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php new file mode 100644 index 00000000..05415481 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Roman.php @@ -0,0 +1,846 @@ + ['VL'], + 46 => ['VLI'], + 47 => ['VLII'], + 48 => ['VLIII'], + 49 => ['VLIV', 'IL'], + 95 => ['VC'], + 96 => ['VCI'], + 97 => ['VCII'], + 98 => ['VCIII'], + 99 => ['VCIV', 'IC'], + 145 => ['CVL'], + 146 => ['CVLI'], + 147 => ['CVLII'], + 148 => ['CVLIII'], + 149 => ['CVLIV', 'CIL'], + 195 => ['CVC'], + 196 => ['CVCI'], + 197 => ['CVCII'], + 198 => ['CVCIII'], + 199 => ['CVCIV', 'CIC'], + 245 => ['CCVL'], + 246 => ['CCVLI'], + 247 => ['CCVLII'], + 248 => ['CCVLIII'], + 249 => ['CCVLIV', 'CCIL'], + 295 => ['CCVC'], + 296 => ['CCVCI'], + 297 => ['CCVCII'], + 298 => ['CCVCIII'], + 299 => ['CCVCIV', 'CCIC'], + 345 => ['CCCVL'], + 346 => ['CCCVLI'], + 347 => ['CCCVLII'], + 348 => ['CCCVLIII'], + 349 => ['CCCVLIV', 'CCCIL'], + 395 => ['CCCVC'], + 396 => ['CCCVCI'], + 397 => ['CCCVCII'], + 398 => ['CCCVCIII'], + 399 => ['CCCVCIV', 'CCCIC'], + 445 => ['CDVL'], + 446 => ['CDVLI'], + 447 => ['CDVLII'], + 448 => ['CDVLIII'], + 449 => ['CDVLIV', 'CDIL'], + 450 => ['LD'], + 451 => ['LDI'], + 452 => ['LDII'], + 453 => ['LDIII'], + 454 => ['LDIV'], + 455 => ['LDV'], + 456 => ['LDVI'], + 457 => ['LDVII'], + 458 => ['LDVIII'], + 459 => ['LDIX'], + 460 => ['LDX'], + 461 => ['LDXI'], + 462 => ['LDXII'], + 463 => ['LDXIII'], + 464 => ['LDXIV'], + 465 => ['LDXV'], + 466 => ['LDXVI'], + 467 => ['LDXVII'], + 468 => ['LDXVIII'], + 469 => ['LDXIX'], + 470 => ['LDXX'], + 471 => ['LDXXI'], + 472 => ['LDXXII'], + 473 => ['LDXXIII'], + 474 => ['LDXXIV'], + 475 => ['LDXXV'], + 476 => ['LDXXVI'], + 477 => ['LDXXVII'], + 478 => ['LDXXVIII'], + 479 => ['LDXXIX'], + 480 => ['LDXXX'], + 481 => ['LDXXXI'], + 482 => ['LDXXXII'], + 483 => ['LDXXXIII'], + 484 => ['LDXXXIV'], + 485 => ['LDXXXV'], + 486 => ['LDXXXVI'], + 487 => ['LDXXXVII'], + 488 => ['LDXXXVIII'], + 489 => ['LDXXXIX'], + 490 => ['LDXL', 'XD'], + 491 => ['LDXLI', 'XDI'], + 492 => ['LDXLII', 'XDII'], + 493 => ['LDXLIII', 'XDIII'], + 494 => ['LDXLIV', 'XDIV'], + 495 => ['LDVL', 'XDV', 'VD'], + 496 => ['LDVLI', 'XDVI', 'VDI'], + 497 => ['LDVLII', 'XDVII', 'VDII'], + 498 => ['LDVLIII', 'XDVIII', 'VDIII'], + 499 => ['LDVLIV', 'XDIX', 'VDIV', 'ID'], + 545 => ['DVL'], + 546 => ['DVLI'], + 547 => ['DVLII'], + 548 => ['DVLIII'], + 549 => ['DVLIV', 'DIL'], + 595 => ['DVC'], + 596 => ['DVCI'], + 597 => ['DVCII'], + 598 => ['DVCIII'], + 599 => ['DVCIV', 'DIC'], + 645 => ['DCVL'], + 646 => ['DCVLI'], + 647 => ['DCVLII'], + 648 => ['DCVLIII'], + 649 => ['DCVLIV', 'DCIL'], + 695 => ['DCVC'], + 696 => ['DCVCI'], + 697 => ['DCVCII'], + 698 => ['DCVCIII'], + 699 => ['DCVCIV', 'DCIC'], + 745 => ['DCCVL'], + 746 => ['DCCVLI'], + 747 => ['DCCVLII'], + 748 => ['DCCVLIII'], + 749 => ['DCCVLIV', 'DCCIL'], + 795 => ['DCCVC'], + 796 => ['DCCVCI'], + 797 => ['DCCVCII'], + 798 => ['DCCVCIII'], + 799 => ['DCCVCIV', 'DCCIC'], + 845 => ['DCCCVL'], + 846 => ['DCCCVLI'], + 847 => ['DCCCVLII'], + 848 => ['DCCCVLIII'], + 849 => ['DCCCVLIV', 'DCCCIL'], + 895 => ['DCCCVC'], + 896 => ['DCCCVCI'], + 897 => ['DCCCVCII'], + 898 => ['DCCCVCIII'], + 899 => ['DCCCVCIV', 'DCCCIC'], + 945 => ['CMVL'], + 946 => ['CMVLI'], + 947 => ['CMVLII'], + 948 => ['CMVLIII'], + 949 => ['CMVLIV', 'CMIL'], + 950 => ['LM'], + 951 => ['LMI'], + 952 => ['LMII'], + 953 => ['LMIII'], + 954 => ['LMIV'], + 955 => ['LMV'], + 956 => ['LMVI'], + 957 => ['LMVII'], + 958 => ['LMVIII'], + 959 => ['LMIX'], + 960 => ['LMX'], + 961 => ['LMXI'], + 962 => ['LMXII'], + 963 => ['LMXIII'], + 964 => ['LMXIV'], + 965 => ['LMXV'], + 966 => ['LMXVI'], + 967 => ['LMXVII'], + 968 => ['LMXVIII'], + 969 => ['LMXIX'], + 970 => ['LMXX'], + 971 => ['LMXXI'], + 972 => ['LMXXII'], + 973 => ['LMXXIII'], + 974 => ['LMXXIV'], + 975 => ['LMXXV'], + 976 => ['LMXXVI'], + 977 => ['LMXXVII'], + 978 => ['LMXXVIII'], + 979 => ['LMXXIX'], + 980 => ['LMXXX'], + 981 => ['LMXXXI'], + 982 => ['LMXXXII'], + 983 => ['LMXXXIII'], + 984 => ['LMXXXIV'], + 985 => ['LMXXXV'], + 986 => ['LMXXXVI'], + 987 => ['LMXXXVII'], + 988 => ['LMXXXVIII'], + 989 => ['LMXXXIX'], + 990 => ['LMXL', 'XM'], + 991 => ['LMXLI', 'XMI'], + 992 => ['LMXLII', 'XMII'], + 993 => ['LMXLIII', 'XMIII'], + 994 => ['LMXLIV', 'XMIV'], + 995 => ['LMVL', 'XMV', 'VM'], + 996 => ['LMVLI', 'XMVI', 'VMI'], + 997 => ['LMVLII', 'XMVII', 'VMII'], + 998 => ['LMVLIII', 'XMVIII', 'VMIII'], + 999 => ['LMVLIV', 'XMIX', 'VMIV', 'IM'], + 1045 => ['MVL'], + 1046 => ['MVLI'], + 1047 => ['MVLII'], + 1048 => ['MVLIII'], + 1049 => ['MVLIV', 'MIL'], + 1095 => ['MVC'], + 1096 => ['MVCI'], + 1097 => ['MVCII'], + 1098 => ['MVCIII'], + 1099 => ['MVCIV', 'MIC'], + 1145 => ['MCVL'], + 1146 => ['MCVLI'], + 1147 => ['MCVLII'], + 1148 => ['MCVLIII'], + 1149 => ['MCVLIV', 'MCIL'], + 1195 => ['MCVC'], + 1196 => ['MCVCI'], + 1197 => ['MCVCII'], + 1198 => ['MCVCIII'], + 1199 => ['MCVCIV', 'MCIC'], + 1245 => ['MCCVL'], + 1246 => ['MCCVLI'], + 1247 => ['MCCVLII'], + 1248 => ['MCCVLIII'], + 1249 => ['MCCVLIV', 'MCCIL'], + 1295 => ['MCCVC'], + 1296 => ['MCCVCI'], + 1297 => ['MCCVCII'], + 1298 => ['MCCVCIII'], + 1299 => ['MCCVCIV', 'MCCIC'], + 1345 => ['MCCCVL'], + 1346 => ['MCCCVLI'], + 1347 => ['MCCCVLII'], + 1348 => ['MCCCVLIII'], + 1349 => ['MCCCVLIV', 'MCCCIL'], + 1395 => ['MCCCVC'], + 1396 => ['MCCCVCI'], + 1397 => ['MCCCVCII'], + 1398 => ['MCCCVCIII'], + 1399 => ['MCCCVCIV', 'MCCCIC'], + 1445 => ['MCDVL'], + 1446 => ['MCDVLI'], + 1447 => ['MCDVLII'], + 1448 => ['MCDVLIII'], + 1449 => ['MCDVLIV', 'MCDIL'], + 1450 => ['MLD'], + 1451 => ['MLDI'], + 1452 => ['MLDII'], + 1453 => ['MLDIII'], + 1454 => ['MLDIV'], + 1455 => ['MLDV'], + 1456 => ['MLDVI'], + 1457 => ['MLDVII'], + 1458 => ['MLDVIII'], + 1459 => ['MLDIX'], + 1460 => ['MLDX'], + 1461 => ['MLDXI'], + 1462 => ['MLDXII'], + 1463 => ['MLDXIII'], + 1464 => ['MLDXIV'], + 1465 => ['MLDXV'], + 1466 => ['MLDXVI'], + 1467 => ['MLDXVII'], + 1468 => ['MLDXVIII'], + 1469 => ['MLDXIX'], + 1470 => ['MLDXX'], + 1471 => ['MLDXXI'], + 1472 => ['MLDXXII'], + 1473 => ['MLDXXIII'], + 1474 => ['MLDXXIV'], + 1475 => ['MLDXXV'], + 1476 => ['MLDXXVI'], + 1477 => ['MLDXXVII'], + 1478 => ['MLDXXVIII'], + 1479 => ['MLDXXIX'], + 1480 => ['MLDXXX'], + 1481 => ['MLDXXXI'], + 1482 => ['MLDXXXII'], + 1483 => ['MLDXXXIII'], + 1484 => ['MLDXXXIV'], + 1485 => ['MLDXXXV'], + 1486 => ['MLDXXXVI'], + 1487 => ['MLDXXXVII'], + 1488 => ['MLDXXXVIII'], + 1489 => ['MLDXXXIX'], + 1490 => ['MLDXL', 'MXD'], + 1491 => ['MLDXLI', 'MXDI'], + 1492 => ['MLDXLII', 'MXDII'], + 1493 => ['MLDXLIII', 'MXDIII'], + 1494 => ['MLDXLIV', 'MXDIV'], + 1495 => ['MLDVL', 'MXDV', 'MVD'], + 1496 => ['MLDVLI', 'MXDVI', 'MVDI'], + 1497 => ['MLDVLII', 'MXDVII', 'MVDII'], + 1498 => ['MLDVLIII', 'MXDVIII', 'MVDIII'], + 1499 => ['MLDVLIV', 'MXDIX', 'MVDIV', 'MID'], + 1545 => ['MDVL'], + 1546 => ['MDVLI'], + 1547 => ['MDVLII'], + 1548 => ['MDVLIII'], + 1549 => ['MDVLIV', 'MDIL'], + 1595 => ['MDVC'], + 1596 => ['MDVCI'], + 1597 => ['MDVCII'], + 1598 => ['MDVCIII'], + 1599 => ['MDVCIV', 'MDIC'], + 1645 => ['MDCVL'], + 1646 => ['MDCVLI'], + 1647 => ['MDCVLII'], + 1648 => ['MDCVLIII'], + 1649 => ['MDCVLIV', 'MDCIL'], + 1695 => ['MDCVC'], + 1696 => ['MDCVCI'], + 1697 => ['MDCVCII'], + 1698 => ['MDCVCIII'], + 1699 => ['MDCVCIV', 'MDCIC'], + 1745 => ['MDCCVL'], + 1746 => ['MDCCVLI'], + 1747 => ['MDCCVLII'], + 1748 => ['MDCCVLIII'], + 1749 => ['MDCCVLIV', 'MDCCIL'], + 1795 => ['MDCCVC'], + 1796 => ['MDCCVCI'], + 1797 => ['MDCCVCII'], + 1798 => ['MDCCVCIII'], + 1799 => ['MDCCVCIV', 'MDCCIC'], + 1845 => ['MDCCCVL'], + 1846 => ['MDCCCVLI'], + 1847 => ['MDCCCVLII'], + 1848 => ['MDCCCVLIII'], + 1849 => ['MDCCCVLIV', 'MDCCCIL'], + 1895 => ['MDCCCVC'], + 1896 => ['MDCCCVCI'], + 1897 => ['MDCCCVCII'], + 1898 => ['MDCCCVCIII'], + 1899 => ['MDCCCVCIV', 'MDCCCIC'], + 1945 => ['MCMVL'], + 1946 => ['MCMVLI'], + 1947 => ['MCMVLII'], + 1948 => ['MCMVLIII'], + 1949 => ['MCMVLIV', 'MCMIL'], + 1950 => ['MLM'], + 1951 => ['MLMI'], + 1952 => ['MLMII'], + 1953 => ['MLMIII'], + 1954 => ['MLMIV'], + 1955 => ['MLMV'], + 1956 => ['MLMVI'], + 1957 => ['MLMVII'], + 1958 => ['MLMVIII'], + 1959 => ['MLMIX'], + 1960 => ['MLMX'], + 1961 => ['MLMXI'], + 1962 => ['MLMXII'], + 1963 => ['MLMXIII'], + 1964 => ['MLMXIV'], + 1965 => ['MLMXV'], + 1966 => ['MLMXVI'], + 1967 => ['MLMXVII'], + 1968 => ['MLMXVIII'], + 1969 => ['MLMXIX'], + 1970 => ['MLMXX'], + 1971 => ['MLMXXI'], + 1972 => ['MLMXXII'], + 1973 => ['MLMXXIII'], + 1974 => ['MLMXXIV'], + 1975 => ['MLMXXV'], + 1976 => ['MLMXXVI'], + 1977 => ['MLMXXVII'], + 1978 => ['MLMXXVIII'], + 1979 => ['MLMXXIX'], + 1980 => ['MLMXXX'], + 1981 => ['MLMXXXI'], + 1982 => ['MLMXXXII'], + 1983 => ['MLMXXXIII'], + 1984 => ['MLMXXXIV'], + 1985 => ['MLMXXXV'], + 1986 => ['MLMXXXVI'], + 1987 => ['MLMXXXVII'], + 1988 => ['MLMXXXVIII'], + 1989 => ['MLMXXXIX'], + 1990 => ['MLMXL', 'MXM'], + 1991 => ['MLMXLI', 'MXMI'], + 1992 => ['MLMXLII', 'MXMII'], + 1993 => ['MLMXLIII', 'MXMIII'], + 1994 => ['MLMXLIV', 'MXMIV'], + 1995 => ['MLMVL', 'MXMV', 'MVM'], + 1996 => ['MLMVLI', 'MXMVI', 'MVMI'], + 1997 => ['MLMVLII', 'MXMVII', 'MVMII'], + 1998 => ['MLMVLIII', 'MXMVIII', 'MVMIII'], + 1999 => ['MLMVLIV', 'MXMIX', 'MVMIV', 'MIM'], + 2045 => ['MMVL'], + 2046 => ['MMVLI'], + 2047 => ['MMVLII'], + 2048 => ['MMVLIII'], + 2049 => ['MMVLIV', 'MMIL'], + 2095 => ['MMVC'], + 2096 => ['MMVCI'], + 2097 => ['MMVCII'], + 2098 => ['MMVCIII'], + 2099 => ['MMVCIV', 'MMIC'], + 2145 => ['MMCVL'], + 2146 => ['MMCVLI'], + 2147 => ['MMCVLII'], + 2148 => ['MMCVLIII'], + 2149 => ['MMCVLIV', 'MMCIL'], + 2195 => ['MMCVC'], + 2196 => ['MMCVCI'], + 2197 => ['MMCVCII'], + 2198 => ['MMCVCIII'], + 2199 => ['MMCVCIV', 'MMCIC'], + 2245 => ['MMCCVL'], + 2246 => ['MMCCVLI'], + 2247 => ['MMCCVLII'], + 2248 => ['MMCCVLIII'], + 2249 => ['MMCCVLIV', 'MMCCIL'], + 2295 => ['MMCCVC'], + 2296 => ['MMCCVCI'], + 2297 => ['MMCCVCII'], + 2298 => ['MMCCVCIII'], + 2299 => ['MMCCVCIV', 'MMCCIC'], + 2345 => ['MMCCCVL'], + 2346 => ['MMCCCVLI'], + 2347 => ['MMCCCVLII'], + 2348 => ['MMCCCVLIII'], + 2349 => ['MMCCCVLIV', 'MMCCCIL'], + 2395 => ['MMCCCVC'], + 2396 => ['MMCCCVCI'], + 2397 => ['MMCCCVCII'], + 2398 => ['MMCCCVCIII'], + 2399 => ['MMCCCVCIV', 'MMCCCIC'], + 2445 => ['MMCDVL'], + 2446 => ['MMCDVLI'], + 2447 => ['MMCDVLII'], + 2448 => ['MMCDVLIII'], + 2449 => ['MMCDVLIV', 'MMCDIL'], + 2450 => ['MMLD'], + 2451 => ['MMLDI'], + 2452 => ['MMLDII'], + 2453 => ['MMLDIII'], + 2454 => ['MMLDIV'], + 2455 => ['MMLDV'], + 2456 => ['MMLDVI'], + 2457 => ['MMLDVII'], + 2458 => ['MMLDVIII'], + 2459 => ['MMLDIX'], + 2460 => ['MMLDX'], + 2461 => ['MMLDXI'], + 2462 => ['MMLDXII'], + 2463 => ['MMLDXIII'], + 2464 => ['MMLDXIV'], + 2465 => ['MMLDXV'], + 2466 => ['MMLDXVI'], + 2467 => ['MMLDXVII'], + 2468 => ['MMLDXVIII'], + 2469 => ['MMLDXIX'], + 2470 => ['MMLDXX'], + 2471 => ['MMLDXXI'], + 2472 => ['MMLDXXII'], + 2473 => ['MMLDXXIII'], + 2474 => ['MMLDXXIV'], + 2475 => ['MMLDXXV'], + 2476 => ['MMLDXXVI'], + 2477 => ['MMLDXXVII'], + 2478 => ['MMLDXXVIII'], + 2479 => ['MMLDXXIX'], + 2480 => ['MMLDXXX'], + 2481 => ['MMLDXXXI'], + 2482 => ['MMLDXXXII'], + 2483 => ['MMLDXXXIII'], + 2484 => ['MMLDXXXIV'], + 2485 => ['MMLDXXXV'], + 2486 => ['MMLDXXXVI'], + 2487 => ['MMLDXXXVII'], + 2488 => ['MMLDXXXVIII'], + 2489 => ['MMLDXXXIX'], + 2490 => ['MMLDXL', 'MMXD'], + 2491 => ['MMLDXLI', 'MMXDI'], + 2492 => ['MMLDXLII', 'MMXDII'], + 2493 => ['MMLDXLIII', 'MMXDIII'], + 2494 => ['MMLDXLIV', 'MMXDIV'], + 2495 => ['MMLDVL', 'MMXDV', 'MMVD'], + 2496 => ['MMLDVLI', 'MMXDVI', 'MMVDI'], + 2497 => ['MMLDVLII', 'MMXDVII', 'MMVDII'], + 2498 => ['MMLDVLIII', 'MMXDVIII', 'MMVDIII'], + 2499 => ['MMLDVLIV', 'MMXDIX', 'MMVDIV', 'MMID'], + 2545 => ['MMDVL'], + 2546 => ['MMDVLI'], + 2547 => ['MMDVLII'], + 2548 => ['MMDVLIII'], + 2549 => ['MMDVLIV', 'MMDIL'], + 2595 => ['MMDVC'], + 2596 => ['MMDVCI'], + 2597 => ['MMDVCII'], + 2598 => ['MMDVCIII'], + 2599 => ['MMDVCIV', 'MMDIC'], + 2645 => ['MMDCVL'], + 2646 => ['MMDCVLI'], + 2647 => ['MMDCVLII'], + 2648 => ['MMDCVLIII'], + 2649 => ['MMDCVLIV', 'MMDCIL'], + 2695 => ['MMDCVC'], + 2696 => ['MMDCVCI'], + 2697 => ['MMDCVCII'], + 2698 => ['MMDCVCIII'], + 2699 => ['MMDCVCIV', 'MMDCIC'], + 2745 => ['MMDCCVL'], + 2746 => ['MMDCCVLI'], + 2747 => ['MMDCCVLII'], + 2748 => ['MMDCCVLIII'], + 2749 => ['MMDCCVLIV', 'MMDCCIL'], + 2795 => ['MMDCCVC'], + 2796 => ['MMDCCVCI'], + 2797 => ['MMDCCVCII'], + 2798 => ['MMDCCVCIII'], + 2799 => ['MMDCCVCIV', 'MMDCCIC'], + 2845 => ['MMDCCCVL'], + 2846 => ['MMDCCCVLI'], + 2847 => ['MMDCCCVLII'], + 2848 => ['MMDCCCVLIII'], + 2849 => ['MMDCCCVLIV', 'MMDCCCIL'], + 2895 => ['MMDCCCVC'], + 2896 => ['MMDCCCVCI'], + 2897 => ['MMDCCCVCII'], + 2898 => ['MMDCCCVCIII'], + 2899 => ['MMDCCCVCIV', 'MMDCCCIC'], + 2945 => ['MMCMVL'], + 2946 => ['MMCMVLI'], + 2947 => ['MMCMVLII'], + 2948 => ['MMCMVLIII'], + 2949 => ['MMCMVLIV', 'MMCMIL'], + 2950 => ['MMLM'], + 2951 => ['MMLMI'], + 2952 => ['MMLMII'], + 2953 => ['MMLMIII'], + 2954 => ['MMLMIV'], + 2955 => ['MMLMV'], + 2956 => ['MMLMVI'], + 2957 => ['MMLMVII'], + 2958 => ['MMLMVIII'], + 2959 => ['MMLMIX'], + 2960 => ['MMLMX'], + 2961 => ['MMLMXI'], + 2962 => ['MMLMXII'], + 2963 => ['MMLMXIII'], + 2964 => ['MMLMXIV'], + 2965 => ['MMLMXV'], + 2966 => ['MMLMXVI'], + 2967 => ['MMLMXVII'], + 2968 => ['MMLMXVIII'], + 2969 => ['MMLMXIX'], + 2970 => ['MMLMXX'], + 2971 => ['MMLMXXI'], + 2972 => ['MMLMXXII'], + 2973 => ['MMLMXXIII'], + 2974 => ['MMLMXXIV'], + 2975 => ['MMLMXXV'], + 2976 => ['MMLMXXVI'], + 2977 => ['MMLMXXVII'], + 2978 => ['MMLMXXVIII'], + 2979 => ['MMLMXXIX'], + 2980 => ['MMLMXXX'], + 2981 => ['MMLMXXXI'], + 2982 => ['MMLMXXXII'], + 2983 => ['MMLMXXXIII'], + 2984 => ['MMLMXXXIV'], + 2985 => ['MMLMXXXV'], + 2986 => ['MMLMXXXVI'], + 2987 => ['MMLMXXXVII'], + 2988 => ['MMLMXXXVIII'], + 2989 => ['MMLMXXXIX'], + 2990 => ['MMLMXL', 'MMXM'], + 2991 => ['MMLMXLI', 'MMXMI'], + 2992 => ['MMLMXLII', 'MMXMII'], + 2993 => ['MMLMXLIII', 'MMXMIII'], + 2994 => ['MMLMXLIV', 'MMXMIV'], + 2995 => ['MMLMVL', 'MMXMV', 'MMVM'], + 2996 => ['MMLMVLI', 'MMXMVI', 'MMVMI'], + 2997 => ['MMLMVLII', 'MMXMVII', 'MMVMII'], + 2998 => ['MMLMVLIII', 'MMXMVIII', 'MMVMIII'], + 2999 => ['MMLMVLIV', 'MMXMIX', 'MMVMIV', 'MMIM'], + 3045 => ['MMMVL'], + 3046 => ['MMMVLI'], + 3047 => ['MMMVLII'], + 3048 => ['MMMVLIII'], + 3049 => ['MMMVLIV', 'MMMIL'], + 3095 => ['MMMVC'], + 3096 => ['MMMVCI'], + 3097 => ['MMMVCII'], + 3098 => ['MMMVCIII'], + 3099 => ['MMMVCIV', 'MMMIC'], + 3145 => ['MMMCVL'], + 3146 => ['MMMCVLI'], + 3147 => ['MMMCVLII'], + 3148 => ['MMMCVLIII'], + 3149 => ['MMMCVLIV', 'MMMCIL'], + 3195 => ['MMMCVC'], + 3196 => ['MMMCVCI'], + 3197 => ['MMMCVCII'], + 3198 => ['MMMCVCIII'], + 3199 => ['MMMCVCIV', 'MMMCIC'], + 3245 => ['MMMCCVL'], + 3246 => ['MMMCCVLI'], + 3247 => ['MMMCCVLII'], + 3248 => ['MMMCCVLIII'], + 3249 => ['MMMCCVLIV', 'MMMCCIL'], + 3295 => ['MMMCCVC'], + 3296 => ['MMMCCVCI'], + 3297 => ['MMMCCVCII'], + 3298 => ['MMMCCVCIII'], + 3299 => ['MMMCCVCIV', 'MMMCCIC'], + 3345 => ['MMMCCCVL'], + 3346 => ['MMMCCCVLI'], + 3347 => ['MMMCCCVLII'], + 3348 => ['MMMCCCVLIII'], + 3349 => ['MMMCCCVLIV', 'MMMCCCIL'], + 3395 => ['MMMCCCVC'], + 3396 => ['MMMCCCVCI'], + 3397 => ['MMMCCCVCII'], + 3398 => ['MMMCCCVCIII'], + 3399 => ['MMMCCCVCIV', 'MMMCCCIC'], + 3445 => ['MMMCDVL'], + 3446 => ['MMMCDVLI'], + 3447 => ['MMMCDVLII'], + 3448 => ['MMMCDVLIII'], + 3449 => ['MMMCDVLIV', 'MMMCDIL'], + 3450 => ['MMMLD'], + 3451 => ['MMMLDI'], + 3452 => ['MMMLDII'], + 3453 => ['MMMLDIII'], + 3454 => ['MMMLDIV'], + 3455 => ['MMMLDV'], + 3456 => ['MMMLDVI'], + 3457 => ['MMMLDVII'], + 3458 => ['MMMLDVIII'], + 3459 => ['MMMLDIX'], + 3460 => ['MMMLDX'], + 3461 => ['MMMLDXI'], + 3462 => ['MMMLDXII'], + 3463 => ['MMMLDXIII'], + 3464 => ['MMMLDXIV'], + 3465 => ['MMMLDXV'], + 3466 => ['MMMLDXVI'], + 3467 => ['MMMLDXVII'], + 3468 => ['MMMLDXVIII'], + 3469 => ['MMMLDXIX'], + 3470 => ['MMMLDXX'], + 3471 => ['MMMLDXXI'], + 3472 => ['MMMLDXXII'], + 3473 => ['MMMLDXXIII'], + 3474 => ['MMMLDXXIV'], + 3475 => ['MMMLDXXV'], + 3476 => ['MMMLDXXVI'], + 3477 => ['MMMLDXXVII'], + 3478 => ['MMMLDXXVIII'], + 3479 => ['MMMLDXXIX'], + 3480 => ['MMMLDXXX'], + 3481 => ['MMMLDXXXI'], + 3482 => ['MMMLDXXXII'], + 3483 => ['MMMLDXXXIII'], + 3484 => ['MMMLDXXXIV'], + 3485 => ['MMMLDXXXV'], + 3486 => ['MMMLDXXXVI'], + 3487 => ['MMMLDXXXVII'], + 3488 => ['MMMLDXXXVIII'], + 3489 => ['MMMLDXXXIX'], + 3490 => ['MMMLDXL', 'MMMXD'], + 3491 => ['MMMLDXLI', 'MMMXDI'], + 3492 => ['MMMLDXLII', 'MMMXDII'], + 3493 => ['MMMLDXLIII', 'MMMXDIII'], + 3494 => ['MMMLDXLIV', 'MMMXDIV'], + 3495 => ['MMMLDVL', 'MMMXDV', 'MMMVD'], + 3496 => ['MMMLDVLI', 'MMMXDVI', 'MMMVDI'], + 3497 => ['MMMLDVLII', 'MMMXDVII', 'MMMVDII'], + 3498 => ['MMMLDVLIII', 'MMMXDVIII', 'MMMVDIII'], + 3499 => ['MMMLDVLIV', 'MMMXDIX', 'MMMVDIV', 'MMMID'], + 3545 => ['MMMDVL'], + 3546 => ['MMMDVLI'], + 3547 => ['MMMDVLII'], + 3548 => ['MMMDVLIII'], + 3549 => ['MMMDVLIV', 'MMMDIL'], + 3595 => ['MMMDVC'], + 3596 => ['MMMDVCI'], + 3597 => ['MMMDVCII'], + 3598 => ['MMMDVCIII'], + 3599 => ['MMMDVCIV', 'MMMDIC'], + 3645 => ['MMMDCVL'], + 3646 => ['MMMDCVLI'], + 3647 => ['MMMDCVLII'], + 3648 => ['MMMDCVLIII'], + 3649 => ['MMMDCVLIV', 'MMMDCIL'], + 3695 => ['MMMDCVC'], + 3696 => ['MMMDCVCI'], + 3697 => ['MMMDCVCII'], + 3698 => ['MMMDCVCIII'], + 3699 => ['MMMDCVCIV', 'MMMDCIC'], + 3745 => ['MMMDCCVL'], + 3746 => ['MMMDCCVLI'], + 3747 => ['MMMDCCVLII'], + 3748 => ['MMMDCCVLIII'], + 3749 => ['MMMDCCVLIV', 'MMMDCCIL'], + 3795 => ['MMMDCCVC'], + 3796 => ['MMMDCCVCI'], + 3797 => ['MMMDCCVCII'], + 3798 => ['MMMDCCVCIII'], + 3799 => ['MMMDCCVCIV', 'MMMDCCIC'], + 3845 => ['MMMDCCCVL'], + 3846 => ['MMMDCCCVLI'], + 3847 => ['MMMDCCCVLII'], + 3848 => ['MMMDCCCVLIII'], + 3849 => ['MMMDCCCVLIV', 'MMMDCCCIL'], + 3895 => ['MMMDCCCVC'], + 3896 => ['MMMDCCCVCI'], + 3897 => ['MMMDCCCVCII'], + 3898 => ['MMMDCCCVCIII'], + 3899 => ['MMMDCCCVCIV', 'MMMDCCCIC'], + 3945 => ['MMMCMVL'], + 3946 => ['MMMCMVLI'], + 3947 => ['MMMCMVLII'], + 3948 => ['MMMCMVLIII'], + 3949 => ['MMMCMVLIV', 'MMMCMIL'], + 3950 => ['MMMLM'], + 3951 => ['MMMLMI'], + 3952 => ['MMMLMII'], + 3953 => ['MMMLMIII'], + 3954 => ['MMMLMIV'], + 3955 => ['MMMLMV'], + 3956 => ['MMMLMVI'], + 3957 => ['MMMLMVII'], + 3958 => ['MMMLMVIII'], + 3959 => ['MMMLMIX'], + 3960 => ['MMMLMX'], + 3961 => ['MMMLMXI'], + 3962 => ['MMMLMXII'], + 3963 => ['MMMLMXIII'], + 3964 => ['MMMLMXIV'], + 3965 => ['MMMLMXV'], + 3966 => ['MMMLMXVI'], + 3967 => ['MMMLMXVII'], + 3968 => ['MMMLMXVIII'], + 3969 => ['MMMLMXIX'], + 3970 => ['MMMLMXX'], + 3971 => ['MMMLMXXI'], + 3972 => ['MMMLMXXII'], + 3973 => ['MMMLMXXIII'], + 3974 => ['MMMLMXXIV'], + 3975 => ['MMMLMXXV'], + 3976 => ['MMMLMXXVI'], + 3977 => ['MMMLMXXVII'], + 3978 => ['MMMLMXXVIII'], + 3979 => ['MMMLMXXIX'], + 3980 => ['MMMLMXXX'], + 3981 => ['MMMLMXXXI'], + 3982 => ['MMMLMXXXII'], + 3983 => ['MMMLMXXXIII'], + 3984 => ['MMMLMXXXIV'], + 3985 => ['MMMLMXXXV'], + 3986 => ['MMMLMXXXVI'], + 3987 => ['MMMLMXXXVII'], + 3988 => ['MMMLMXXXVIII'], + 3989 => ['MMMLMXXXIX'], + 3990 => ['MMMLMXL', 'MMMXM'], + 3991 => ['MMMLMXLI', 'MMMXMI'], + 3992 => ['MMMLMXLII', 'MMMXMII'], + 3993 => ['MMMLMXLIII', 'MMMXMIII'], + 3994 => ['MMMLMXLIV', 'MMMXMIV'], + 3995 => ['MMMLMVL', 'MMMXMV', 'MMMVM'], + 3996 => ['MMMLMVLI', 'MMMXMVI', 'MMMVMI'], + 3997 => ['MMMLMVLII', 'MMMXMVII', 'MMMVMII'], + 3998 => ['MMMLMVLIII', 'MMMXMVIII', 'MMMVMIII'], + 3999 => ['MMMLMVLIV', 'MMMXMIX', 'MMMVMIV', 'MMMIM'], + ]; + + private const THOUSANDS = ['', 'M', 'MM', 'MMM']; + private const HUNDREDS = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']; + private const TENS = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']; + private const ONES = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; + const MAX_ROMAN_VALUE = 3999; + const MAX_ROMAN_STYLE = 4; + + private static function valueOk(int $aValue, int $style): string + { + $origValue = $aValue; + $m = \intdiv($aValue, 1000); + $aValue %= 1000; + $c = \intdiv($aValue, 100); + $aValue %= 100; + $t = \intdiv($aValue, 10); + $aValue %= 10; + $result = self::THOUSANDS[$m] . self::HUNDREDS[$c] . self::TENS[$t] . self::ONES[$aValue]; + if ($style > 0) { + if (array_key_exists($origValue, self::VALUES)) { + $arr = self::VALUES[$origValue]; + $idx = min($style, count($arr)) - 1; + $result = $arr[$idx]; + } + } + + return $result; + } + + private static function styleOk(int $aValue, int $style): string + { + return ($aValue < 0 || $aValue > self::MAX_ROMAN_VALUE) ? ExcelError::VALUE() : self::valueOk($aValue, $style); + } + + public static function calculateRoman(int $aValue, int $style): string + { + return ($style < 0 || $style > self::MAX_ROMAN_STYLE) ? ExcelError::VALUE() : self::styleOk($aValue, $style); + } + + /** + * ROMAN. + * + * Converts a number to Roman numeral + * + * @param mixed $aValue Number to convert + * Or can be an array of numbers + * @param mixed $style Number indicating one of five possible forms + * Or can be an array of styles + * + * @return array|string Roman numeral, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function evaluate($aValue, $style = 0) + { + if (is_array($aValue) || is_array($style)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $aValue, $style); + } + + try { + $aValue = Helpers::validateNumericNullBool($aValue); + if (is_bool($style)) { + $style = $style ? 0 : 4; + } + $style = Helpers::validateNumericNullSubstitution($style, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + return self::calculateRoman((int) $aValue, (int) $style); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php new file mode 100644 index 00000000..776f7eb9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Round.php @@ -0,0 +1,218 @@ +getMessage(); + } + + return round($number, (int) $precision); + } + + /** + * ROUNDUP. + * + * Rounds a number up to a specified number of decimal places + * + * @param array|float $number Number to round, or can be an array of numbers + * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function up($number, $digits) + { + if (is_array($number) || is_array($digits)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0.0) { + return 0.0; + } + + if ($number < 0.0) { + return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); + } + + return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_DOWN); + } + + /** + * ROUNDDOWN. + * + * Rounds a number down to a specified number of decimal places + * + * @param array|float $number Number to round, or can be an array of numbers + * @param array|int $digits Number of digits to which you want to round $number, or can be an array of numbers + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function down($number, $digits) + { + if (is_array($number) || is_array($digits)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $digits); + } + + try { + $number = Helpers::validateNumericNullBool($number); + $digits = (int) Helpers::validateNumericNullSubstitution($digits, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0.0) { + return 0.0; + } + + if ($number < 0.0) { + return round($number + 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); + } + + return round($number - 0.5 * 0.1 ** $digits, $digits, PHP_ROUND_HALF_UP); + } + + /** + * MROUND. + * + * Rounds a number to the nearest multiple of a specified value + * + * @param mixed $number Expect float. Number to round, or can be an array of numbers + * @param mixed $multiple Expect int. Multiple to which you want to round, or can be an array of numbers. + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function multiple($number, $multiple) + { + if (is_array($number) || is_array($multiple)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $number, $multiple); + } + + try { + $number = Helpers::validateNumericNullSubstitution($number, 0); + $multiple = Helpers::validateNumericNullSubstitution($multiple, null); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($number == 0 || $multiple == 0) { + return 0; + } + if ((Helpers::returnSign($number)) == (Helpers::returnSign($multiple))) { + $multiplier = 1 / $multiple; + + return round($number * $multiplier) / $multiplier; + } + + return ExcelError::NAN(); + } + + /** + * EVEN. + * + * Returns number rounded up to the nearest even integer. + * You can use this function for processing items that come in twos. For example, + * a packing crate accepts rows of one or two items. The crate is full when + * the number of items, rounded up to the nearest two, matches the crate's + * capacity. + * + * Excel Function: + * EVEN(number) + * + * @param array|float $number Number to round, or can be an array of numbers + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function even($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::getEven($number); + } + + /** + * ODD. + * + * Returns number rounded up to the nearest odd integer. + * + * @param array|float $number Number to round, or can be an array of numbers + * + * @return array|float|string Rounded Number, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function odd($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + $significance = Helpers::returnSign($number); + if ($significance == 0) { + return 1; + } + + $result = ceil($number / $significance) * $significance; + if ($result == Helpers::getEven($result)) { + $result += $significance; + } + + return $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php new file mode 100644 index 00000000..ecce359f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SeriesSum.php @@ -0,0 +1,53 @@ +getMessage(); + } + + return $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php new file mode 100644 index 00000000..e40e1f6d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sign.php @@ -0,0 +1,38 @@ +getMessage(); + } + + return Helpers::returnSign($number); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php new file mode 100644 index 00000000..bb9f15fd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sqrt.php @@ -0,0 +1,64 @@ +getMessage(); + } + + return Helpers::numberOrNan(sqrt($number)); + } + + /** + * SQRTPI. + * + * Returns the square root of (number * pi). + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string Square Root of Number * Pi, or a string containing an error + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function pi($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullSubstitution($number, 0); + Helpers::validateNotNegative($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return sqrt($number * M_PI); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php new file mode 100644 index 00000000..74f95dec --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Subtotal.php @@ -0,0 +1,115 @@ +getWorksheet()->getRowDimension($row)->getVisible(); + }, + ARRAY_FILTER_USE_KEY + ); + } + + /** + * @param mixed $cellReference + * @param mixed $args + */ + protected static function filterFormulaArgs($cellReference, $args): array + { + return array_filter( + $args, + function ($index) use ($cellReference) { + [, $row, $column] = explode('.', $index); + $retVal = true; + if ($cellReference->getWorksheet()->cellExists($column . $row)) { + //take this cell out if it contains the SUBTOTAL or AGGREGATE functions in a formula + $isFormula = $cellReference->getWorksheet()->getCell($column . $row)->isFormula(); + $cellFormula = !preg_match( + '/^=.*\b(SUBTOTAL|AGGREGATE)\s*\(/i', + $cellReference->getWorksheet()->getCell($column . $row)->getValue() ?? '' + ); + + $retVal = !$isFormula || $cellFormula; + } + + return $retVal; + }, + ARRAY_FILTER_USE_KEY + ); + } + + /** @var callable[] */ + private const CALL_FUNCTIONS = [ + 1 => [Statistical\Averages::class, 'average'], // 1 and 101 + [Statistical\Counts::class, 'COUNT'], // 2 and 102 + [Statistical\Counts::class, 'COUNTA'], // 3 and 103 + [Statistical\Maximum::class, 'max'], // 4 and 104 + [Statistical\Minimum::class, 'min'], // 5 and 105 + [Operations::class, 'product'], // 6 and 106 + [Statistical\StandardDeviations::class, 'STDEV'], // 7 and 107 + [Statistical\StandardDeviations::class, 'STDEVP'], // 8 and 108 + [Sum::class, 'sumIgnoringStrings'], // 9 and 109 + [Statistical\Variances::class, 'VAR'], // 10 and 110 + [Statistical\Variances::class, 'VARP'], // 111 and 111 + ]; + + /** + * SUBTOTAL. + * + * Returns a subtotal in a list or database. + * + * @param mixed $functionType + * A number 1 to 11 that specifies which function to + * use in calculating subtotals within a range + * list + * Numbers 101 to 111 shadow the functions of 1 to 11 + * but ignore any values in the range that are + * in hidden rows + * @param mixed[] $args A mixed data series of values + * + * @return float|string + */ + public static function evaluate($functionType, ...$args) + { + $cellReference = array_pop($args); + $aArgs = Functions::flattenArrayIndexed($args); + + try { + $subtotal = (int) Helpers::validateNumericNullBool($functionType); + } catch (Exception $e) { + return $e->getMessage(); + } + + // Calculate + if ($subtotal > 100) { + $aArgs = self::filterHiddenArgs($cellReference, $aArgs); + $subtotal -= 100; + } + + $aArgs = self::filterFormulaArgs($cellReference, $aArgs); + if (array_key_exists($subtotal, self::CALL_FUNCTIONS)) { + /** @var callable */ + $call = self::CALL_FUNCTIONS[$subtotal]; + + return call_user_func_array($call, $aArgs); + } + + return ExcelError::VALUE(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php new file mode 100644 index 00000000..1a797c8a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Sum.php @@ -0,0 +1,118 @@ + $arg) { + // Is it a numeric value? + if (is_numeric($arg) || empty($arg)) { + if (is_string($arg)) { + $arg = (int) $arg; + } + $returnValue += $arg; + } elseif (is_bool($arg)) { + $returnValue += (int) $arg; + } elseif (ErrorValue::isError($arg)) { + return $arg; + // ignore non-numerics from cell, but fail as literals (except null) + } elseif ($arg !== null && !Functions::isCellValue($k)) { + return ExcelError::VALUE(); + } + } + + return $returnValue; + } + + /** + * SUMPRODUCT. + * + * Excel Function: + * SUMPRODUCT(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function product(...$args) + { + $arrayList = $args; + + $wrkArray = Functions::flattenArray(array_shift($arrayList)); + $wrkCellCount = count($wrkArray); + + for ($i = 0; $i < $wrkCellCount; ++$i) { + if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { + $wrkArray[$i] = 0; + } + } + + foreach ($arrayList as $matrixData) { + $array2 = Functions::flattenArray($matrixData); + $count = count($array2); + if ($wrkCellCount != $count) { + return ExcelError::VALUE(); + } + + foreach ($array2 as $i => $val) { + if ((!is_numeric($val)) || (is_string($val))) { + $val = 0; + } + $wrkArray[$i] *= $val; + } + } + + return array_sum($wrkArray); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php new file mode 100644 index 00000000..34b397cd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/SumSquares.php @@ -0,0 +1,143 @@ +getMessage(); + } + + return $returnValue; + } + + private static function getCount(array $array1, array $array2): int + { + $count = count($array1); + if ($count !== count($array2)) { + throw new Exception(ExcelError::NA()); + } + + return $count; + } + + /** + * These functions accept only numeric arguments, not even strings which are numeric. + * + * @param mixed $item + */ + private static function numericNotString($item): bool + { + return is_numeric($item) && !is_string($item); + } + + /** + * SUMX2MY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXSquaredMinusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } + + /** + * SUMX2PY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXSquaredPlusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } + + /** + * SUMXMY2. + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * + * @return float|string + */ + public static function sumXMinusYSquared($matrixData1, $matrixData2) + { + try { + $array1 = Functions::flattenArray($matrixData1); + $array2 = Functions::flattenArray($matrixData2); + $count = self::getCount($array1, $array2); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (self::numericNotString($array1[$i]) && self::numericNotString($array2[$i])) { + $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); + } + } + } catch (Exception $e) { + return $e->getMessage(); + } + + return $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php new file mode 100644 index 00000000..845b6c14 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosecant.php @@ -0,0 +1,64 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(1.0, sin($angle)); + } + + /** + * CSCH. + * + * Returns the hyperbolic cosecant of an angle. + * + * @param array|float $angle Number, or can be an array of numbers + * + * @return array|float|string The hyperbolic cosecant of the angle + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function csch($angle) + { + if (is_array($angle)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); + } + + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, sinh($angle)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php new file mode 100644 index 00000000..c06f04df --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cosine.php @@ -0,0 +1,116 @@ +getMessage(); + } + + return cos($number); + } + + /** + * COSH. + * + * Returns the result of builtin function cosh after validating args. + * + * @param mixed $number Should be numeric, or can be an array of numbers + * + * @return array|float|string hyperbolic cosine + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function cosh($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return cosh($number); + } + + /** + * ACOS. + * + * Returns the arccosine of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The arccosine of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function acos($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(acos($number)); + } + + /** + * ACOSH. + * + * Returns the arc inverse hyperbolic cosine of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The inverse hyperbolic cosine of the number, or an error string + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function acosh($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(acosh($number)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php new file mode 100644 index 00000000..eeedef9b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Cotangent.php @@ -0,0 +1,118 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(cos($angle), sin($angle)); + } + + /** + * COTH. + * + * Returns the hyperbolic cotangent of an angle. + * + * @param array|float $angle Number, or can be an array of numbers + * + * @return array|float|string The hyperbolic cotangent of the angle + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function coth($angle) + { + if (is_array($angle)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); + } + + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, tanh($angle)); + } + + /** + * ACOT. + * + * Returns the arccotangent of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The arccotangent of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function acot($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (M_PI / 2) - atan($number); + } + + /** + * ACOTH. + * + * Returns the hyperbolic arccotangent of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The hyperbolic arccotangent of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function acoth($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + $result = ($number === 1) ? NAN : (log(($number + 1) / ($number - 1)) / 2); + + return Helpers::numberOrNan($result); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php new file mode 100644 index 00000000..2d26e5dd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Secant.php @@ -0,0 +1,64 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(1.0, cos($angle)); + } + + /** + * SECH. + * + * Returns the hyperbolic secant of an angle. + * + * @param array|float $angle Number, or can be an array of numbers + * + * @return array|float|string The hyperbolic secant of the angle + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function sech($angle) + { + if (is_array($angle)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); + } + + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::verySmallDenominator(1.0, cosh($angle)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php new file mode 100644 index 00000000..6af568ce --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Sine.php @@ -0,0 +1,116 @@ +getMessage(); + } + + return sin($angle); + } + + /** + * SINH. + * + * Returns the result of builtin function sinh after validating args. + * + * @param mixed $angle Should be numeric, or can be an array of numbers + * + * @return array|float|string hyperbolic sine + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function sinh($angle) + { + if (is_array($angle)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); + } + + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return sinh($angle); + } + + /** + * ASIN. + * + * Returns the arcsine of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The arcsine of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function asin($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(asin($number)); + } + + /** + * ASINH. + * + * Returns the inverse hyperbolic sine of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The inverse hyperbolic sine of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function asinh($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(asinh($number)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php new file mode 100644 index 00000000..9e770210 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trig/Tangent.php @@ -0,0 +1,161 @@ +getMessage(); + } + + return Helpers::verySmallDenominator(sin($angle), cos($angle)); + } + + /** + * TANH. + * + * Returns the result of builtin function sinh after validating args. + * + * @param mixed $angle Should be numeric, or can be an array of numbers + * + * @return array|float|string hyperbolic tangent + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function tanh($angle) + { + if (is_array($angle)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $angle); + } + + try { + $angle = Helpers::validateNumericNullBool($angle); + } catch (Exception $e) { + return $e->getMessage(); + } + + return tanh($angle); + } + + /** + * ATAN. + * + * Returns the arctangent of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The arctangent of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function atan($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(atan($number)); + } + + /** + * ATANH. + * + * Returns the inverse hyperbolic tangent of a number. + * + * @param array|float $number Number, or can be an array of numbers + * + * @return array|float|string The inverse hyperbolic tangent of the number + * If an array of numbers is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function atanh($number) + { + if (is_array($number)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $number); + } + + try { + $number = Helpers::validateNumericNullBool($number); + } catch (Exception $e) { + return $e->getMessage(); + } + + return Helpers::numberOrNan(atanh($number)); + } + + /** + * ATAN2. + * + * This function calculates the arc tangent of the two variables x and y. It is similar to + * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used + * to determine the quadrant of the result. + * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a + * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between + * -pi and pi, excluding -pi. + * + * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard + * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. + * + * Excel Function: + * ATAN2(xCoordinate,yCoordinate) + * + * @param mixed $xCoordinate should be float, the x-coordinate of the point, or can be an array of numbers + * @param mixed $yCoordinate should be float, the y-coordinate of the point, or can be an array of numbers + * + * @return array|float|string + * The inverse tangent of the specified x- and y-coordinates, or a string containing an error + * If an array of numbers is passed as one of the arguments, then the returned result will also be an array + * with the same dimensions + */ + public static function atan2($xCoordinate, $yCoordinate) + { + if (is_array($xCoordinate) || is_array($yCoordinate)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $xCoordinate, $yCoordinate); + } + + try { + $xCoordinate = Helpers::validateNumericNullBool($xCoordinate); + $yCoordinate = Helpers::validateNumericNullBool($yCoordinate); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($xCoordinate == 0) && ($yCoordinate == 0)) { + return ExcelError::DIV0(); + } + + return atan2($yCoordinate, $xCoordinate); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php new file mode 100644 index 00000000..943e209d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/MathTrig/Trunc.php @@ -0,0 +1,50 @@ +getMessage(); + } + + $digits = floor($digits); + + // Truncate + $adjust = 10 ** $digits; + + if (($digits > 0) && (rtrim((string) (int) ((abs($value) - abs((int) $value)) * $adjust), '0') < $adjust / 10)) { + return $value; + } + + return ((int) ($value * $adjust)) / $adjust; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php index b1c7fb02..497c9297 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical.php @@ -2,560 +2,27 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend; - +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Conditional; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Confidence; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Counts; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Maximum; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Minimum; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Permutations; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Trends; +use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Variances; + +/** + * @deprecated 1.18.0 + */ class Statistical { const LOG_GAMMA_X_MAX_VALUE = 2.55e305; - const XMININ = 2.23e-308; const EPS = 2.22e-16; const MAX_VALUE = 1.2e308; - const MAX_ITERATIONS = 256; const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; - private static function checkTrendArrays(&$array1, &$array2) - { - if (!is_array($array1)) { - $array1 = [$array1]; - } - if (!is_array($array2)) { - $array2 = [$array2]; - } - - $array1 = Functions::flattenArray($array1); - $array2 = Functions::flattenArray($array2); - foreach ($array1 as $key => $value) { - if ((is_bool($value)) || (is_string($value)) || ($value === null)) { - unset($array1[$key], $array2[$key]); - } - } - foreach ($array2 as $key => $value) { - if ((is_bool($value)) || (is_string($value)) || ($value === null)) { - unset($array1[$key], $array2[$key]); - } - } - $array1 = array_merge($array1); - $array2 = array_merge($array2); - - return true; - } - - /** - * Incomplete beta function. - * - * @author Jaco van Kooten - * @author Paul Meagher - * - * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). - * - * @param mixed $x require 0<=x<=1 - * @param mixed $p require p>0 - * @param mixed $q require q>0 - * - * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow - */ - private static function incompleteBeta($x, $p, $q) - { - if ($x <= 0.0) { - return 0.0; - } elseif ($x >= 1.0) { - return 1.0; - } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { - return 0.0; - } - $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); - if ($x < ($p + 1.0) / ($p + $q + 2.0)) { - return $beta_gam * self::betaFraction($x, $p, $q) / $p; - } - - return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); - } - - // Function cache for logBeta function - private static $logBetaCacheP = 0.0; - - private static $logBetaCacheQ = 0.0; - - private static $logBetaCacheResult = 0.0; - - /** - * The natural logarithm of the beta function. - * - * @param mixed $p require p>0 - * @param mixed $q require q>0 - * - * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow - * - * @author Jaco van Kooten - */ - private static function logBeta($p, $q) - { - if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { - self::$logBetaCacheP = $p; - self::$logBetaCacheQ = $q; - if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { - self::$logBetaCacheResult = 0.0; - } else { - self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q); - } - } - - return self::$logBetaCacheResult; - } - - /** - * Evaluates of continued fraction part of incomplete beta function. - * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). - * - * @author Jaco van Kooten - * - * @param mixed $x - * @param mixed $p - * @param mixed $q - * - * @return float - */ - private static function betaFraction($x, $p, $q) - { - $c = 1.0; - $sum_pq = $p + $q; - $p_plus = $p + 1.0; - $p_minus = $p - 1.0; - $h = 1.0 - $sum_pq * $x / $p_plus; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $frac = $h; - $m = 1; - $delta = 0.0; - while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { - $m2 = 2 * $m; - // even index for d - $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); - $h = 1.0 + $d * $h; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $c = 1.0 + $d / $c; - if (abs($c) < self::XMININ) { - $c = self::XMININ; - } - $frac *= $h * $c; - // odd index for d - $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); - $h = 1.0 + $d * $h; - if (abs($h) < self::XMININ) { - $h = self::XMININ; - } - $h = 1.0 / $h; - $c = 1.0 + $d / $c; - if (abs($c) < self::XMININ) { - $c = self::XMININ; - } - $delta = $h * $c; - $frac *= $delta; - ++$m; - } - - return $frac; - } - - /** - * logGamma function. - * - * @version 1.1 - * - * @author Jaco van Kooten - * - * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. - * - * The natural logarithm of the gamma function.
        - * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
        - * Applied Mathematics Division
        - * Argonne National Laboratory
        - * Argonne, IL 60439
        - *

        - * References: - *

          - *
        1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural - * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
        2. - *
        3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
        4. - *
        5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
        6. - *
        - *

        - *

        - * From the original documentation: - *

        - *

        - * This routine calculates the LOG(GAMMA) function for a positive real argument X. - * Computation is based on an algorithm outlined in references 1 and 2. - * The program uses rational functions that theoretically approximate LOG(GAMMA) - * to at least 18 significant decimal digits. The approximation for X > 12 is from - * reference 3, while approximations for X < 12.0 are similar to those in reference - * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, - * the compiler, the intrinsic functions, and proper selection of the - * machine-dependent constants. - *

        - *

        - * Error returns:
        - * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. - * The computation is believed to be free of underflow and overflow. - *

        - * - * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 - */ - - // Function cache for logGamma - private static $logGammaCacheResult = 0.0; - - private static $logGammaCacheX = 0.0; - - private static function logGamma($x) - { - // Log Gamma related constants - static $lg_d1 = -0.5772156649015328605195174; - static $lg_d2 = 0.4227843350984671393993777; - static $lg_d4 = 1.791759469228055000094023; - - static $lg_p1 = [ - 4.945235359296727046734888, - 201.8112620856775083915565, - 2290.838373831346393026739, - 11319.67205903380828685045, - 28557.24635671635335736389, - 38484.96228443793359990269, - 26377.48787624195437963534, - 7225.813979700288197698961, - ]; - static $lg_p2 = [ - 4.974607845568932035012064, - 542.4138599891070494101986, - 15506.93864978364947665077, - 184793.2904445632425417223, - 1088204.76946882876749847, - 3338152.967987029735917223, - 5106661.678927352456275255, - 3074109.054850539556250927, - ]; - static $lg_p4 = [ - 14745.02166059939948905062, - 2426813.369486704502836312, - 121475557.4045093227939592, - 2663432449.630976949898078, - 29403789566.34553899906876, - 170266573776.5398868392998, - 492612579337.743088758812, - 560625185622.3951465078242, - ]; - static $lg_q1 = [ - 67.48212550303777196073036, - 1113.332393857199323513008, - 7738.757056935398733233834, - 27639.87074403340708898585, - 54993.10206226157329794414, - 61611.22180066002127833352, - 36351.27591501940507276287, - 8785.536302431013170870835, - ]; - static $lg_q2 = [ - 183.0328399370592604055942, - 7765.049321445005871323047, - 133190.3827966074194402448, - 1136705.821321969608938755, - 5267964.117437946917577538, - 13467014.54311101692290052, - 17827365.30353274213975932, - 9533095.591844353613395747, - ]; - static $lg_q4 = [ - 2690.530175870899333379843, - 639388.5654300092398984238, - 41355999.30241388052042842, - 1120872109.61614794137657, - 14886137286.78813811542398, - 101680358627.2438228077304, - 341747634550.7377132798597, - 446315818741.9713286462081, - ]; - static $lg_c = [ - -0.001910444077728, - 8.4171387781295e-4, - -5.952379913043012e-4, - 7.93650793500350248e-4, - -0.002777777777777681622553, - 0.08333333333333333331554247, - 0.0057083835261, - ]; - - // Rough estimate of the fourth root of logGamma_xBig - static $lg_frtbig = 2.25e76; - static $pnt68 = 0.6796875; - - if ($x == self::$logGammaCacheX) { - return self::$logGammaCacheResult; - } - $y = $x; - if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { - if ($y <= self::EPS) { - $res = -log($y); - } elseif ($y <= 1.5) { - // --------------------- - // EPS .LT. X .LE. 1.5 - // --------------------- - if ($y < $pnt68) { - $corr = -log($y); - $xm1 = $y; - } else { - $corr = 0.0; - $xm1 = $y - 1.0; - } - if ($y <= 0.5 || $y >= $pnt68) { - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm1 + $lg_p1[$i]; - $xden = $xden * $xm1 + $lg_q1[$i]; - } - $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden)); - } else { - $xm2 = $y - 1.0; - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm2 + $lg_p2[$i]; - $xden = $xden * $xm2 + $lg_q2[$i]; - } - $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); - } - } elseif ($y <= 4.0) { - // --------------------- - // 1.5 .LT. X .LE. 4.0 - // --------------------- - $xm2 = $y - 2.0; - $xden = 1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm2 + $lg_p2[$i]; - $xden = $xden * $xm2 + $lg_q2[$i]; - } - $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); - } elseif ($y <= 12.0) { - // ---------------------- - // 4.0 .LT. X .LE. 12.0 - // ---------------------- - $xm4 = $y - 4.0; - $xden = -1.0; - $xnum = 0.0; - for ($i = 0; $i < 8; ++$i) { - $xnum = $xnum * $xm4 + $lg_p4[$i]; - $xden = $xden * $xm4 + $lg_q4[$i]; - } - $res = $lg_d4 + $xm4 * ($xnum / $xden); - } else { - // --------------------------------- - // Evaluate for argument .GE. 12.0 - // --------------------------------- - $res = 0.0; - if ($y <= $lg_frtbig) { - $res = $lg_c[6]; - $ysq = $y * $y; - for ($i = 0; $i < 6; ++$i) { - $res = $res / $ysq + $lg_c[$i]; - } - $res /= $y; - $corr = log($y); - $res = $res + log(self::SQRT2PI) - 0.5 * $corr; - $res += $y * ($corr - 1.0); - } - } - } else { - // -------------------------- - // Return for bad arguments - // -------------------------- - $res = self::MAX_VALUE; - } - // ------------------------------ - // Final adjustments and return - // ------------------------------ - self::$logGammaCacheX = $x; - self::$logGammaCacheResult = $res; - - return $res; - } - - // - // Private implementation of the incomplete Gamma function - // - private static function incompleteGamma($a, $x) - { - static $max = 32; - $summer = 0; - for ($n = 0; $n <= $max; ++$n) { - $divisor = $a; - for ($i = 1; $i <= $n; ++$i) { - $divisor *= ($a + $i); - } - $summer += (pow($x, $n) / $divisor); - } - - return pow($x, $a) * exp(0 - $x) * $summer; - } - - // - // Private implementation of the Gamma function - // - private static function gamma($data) - { - if ($data == 0.0) { - return 0; - } - - static $p0 = 1.000000000190015; - static $p = [ - 1 => 76.18009172947146, - 2 => -86.50532032941677, - 3 => 24.01409824083091, - 4 => -1.231739572450155, - 5 => 1.208650973866179e-3, - 6 => -5.395239384953e-6, - ]; - - $y = $x = $data; - $tmp = $x + 5.5; - $tmp -= ($x + 0.5) * log($tmp); - - $summer = $p0; - for ($j = 1; $j <= 6; ++$j) { - $summer += ($p[$j] / ++$y); - } - - return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); - } - - /* - * inverse_ncdf.php - * ------------------- - * begin : Friday, January 16, 2004 - * copyright : (C) 2004 Michael Nickerson - * email : nickersonm@yahoo.com - * - */ - private static function inverseNcdf($p) - { - // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to - // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as - // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html - // I have not checked the accuracy of this implementation. Be aware that PHP - // will truncate the coeficcients to 14 digits. - - // You have permission to use and distribute this function freely for - // whatever purpose you want, but please show common courtesy and give credit - // where credit is due. - - // Input paramater is $p - probability - where 0 < p < 1. - - // Coefficients in rational approximations - static $a = [ - 1 => -3.969683028665376e+01, - 2 => 2.209460984245205e+02, - 3 => -2.759285104469687e+02, - 4 => 1.383577518672690e+02, - 5 => -3.066479806614716e+01, - 6 => 2.506628277459239e+00, - ]; - - static $b = [ - 1 => -5.447609879822406e+01, - 2 => 1.615858368580409e+02, - 3 => -1.556989798598866e+02, - 4 => 6.680131188771972e+01, - 5 => -1.328068155288572e+01, - ]; - - static $c = [ - 1 => -7.784894002430293e-03, - 2 => -3.223964580411365e-01, - 3 => -2.400758277161838e+00, - 4 => -2.549732539343734e+00, - 5 => 4.374664141464968e+00, - 6 => 2.938163982698783e+00, - ]; - - static $d = [ - 1 => 7.784695709041462e-03, - 2 => 3.224671290700398e-01, - 3 => 2.445134137142996e+00, - 4 => 3.754408661907416e+00, - ]; - - // Define lower and upper region break-points. - $p_low = 0.02425; //Use lower region approx. below this - $p_high = 1 - $p_low; //Use upper region approx. above this - - if (0 < $p && $p < $p_low) { - // Rational approximation for lower region. - $q = sqrt(-2 * log($p)); - - return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / - (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); - } elseif ($p_low <= $p && $p <= $p_high) { - // Rational approximation for central region. - $q = $p - 0.5; - $r = $q * $q; - - return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / - ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); - } elseif ($p_high < $p && $p < 1) { - // Rational approximation for upper region. - $q = sqrt(-2 * log(1 - $p)); - - return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / - (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); - } - // If 0 < p < 1, return a null value - return Functions::NULL(); - } - - /** - * MS Excel does not count Booleans if passed as cell values, but they are counted if passed as literals. - * OpenOffice Calc always counts Booleans. - * Gnumeric never counts Booleans. - * - * @param mixed $arg - * @param mixed $k - * - * @return int|mixed - */ - private static function testAcceptedBoolean($arg, $k) - { - if ((is_bool($arg)) && - ((!Functions::isCellValue($k) && (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL)) || - (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE))) { - $arg = (int) $arg; - } - - return $arg; - } - - /** - * @param mixed $arg - * @param mixed $k - * - * @return bool - */ - private static function isAcceptedCountable($arg, $k) - { - if (((is_numeric($arg)) && (!is_string($arg))) || - ((is_numeric($arg)) && (!Functions::isCellValue($k)) && - (Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC))) { - return true; - } - - return false; - } - /** * AVEDEV. * @@ -565,7 +32,10 @@ private static function isAcceptedCountable($arg, $k) * Excel Function: * AVEDEV(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::averageDeviations() + * Use the averageDeviations() method in the Statistical\Averages class instead * * @param mixed ...$args Data values * @@ -573,39 +43,7 @@ private static function isAcceptedCountable($arg, $k) */ public static function AVEDEV(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = 0; - - $aMean = self::AVERAGE(...$args); - if ($aMean === Functions::DIV0()) { - return Functions::NAN(); - } elseif ($aMean === Functions::VALUE()) { - return Functions::VALUE(); - } - - $aCount = 0; - foreach ($aArgs as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { - return Functions::VALUE(); - } - if (self::isAcceptedCountable($arg, $k)) { - $returnValue += abs($arg - $aMean); - ++$aCount; - } - } - - // Return - if ($aCount === 0) { - return Functions::DIV0(); - } - - return $returnValue / $aCount; + return Averages::averageDeviations(...$args); } /** @@ -616,7 +54,10 @@ public static function AVEDEV(...$args) * Excel Function: * AVERAGE(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::average() + * Use the average() method in the Statistical\Averages class instead * * @param mixed ...$args Data values * @@ -624,29 +65,7 @@ public static function AVEDEV(...$args) */ public static function AVERAGE(...$args) { - $returnValue = $aCount = 0; - - // Loop through arguments - foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { - return Functions::VALUE(); - } - if (self::isAcceptedCountable($arg, $k)) { - $returnValue += $arg; - ++$aCount; - } - } - - // Return - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Averages::average(...$args); } /** @@ -657,7 +76,10 @@ public static function AVERAGE(...$args) * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Averages::averageA() + * Use the averageA() method in the Statistical\Averages class instead * * @param mixed ...$args Data values * @@ -665,31 +87,7 @@ public static function AVERAGE(...$args) */ public static function AVERAGEA(...$args) { - $returnValue = null; - - $aCount = 0; - // Loop through arguments - foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { - if ((is_bool($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $returnValue += $arg; - ++$aCount; - } - } - } - - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Averages::averageA(...$args); } /** @@ -700,49 +98,20 @@ public static function AVERAGEA(...$args) * Excel Function: * AVERAGEIF(value1[,value2[, ...]],condition) * - * @category Mathematical and Trigonometric Functions + * @Deprecated 1.17.0 * - * @param mixed $aArgs Data values + * @see Statistical\Conditional::AVERAGEIF() + * Use the AVERAGEIF() method in the Statistical\Conditional class instead + * + * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be checked - * @param mixed[] $averageArgs Data values + * @param mixed[] $averageRange Data values * - * @return float|string + * @return null|float|string */ - public static function AVERAGEIF($aArgs, $condition, $averageArgs = []) + public static function AVERAGEIF($range, $condition, $averageRange = []) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $averageArgs = Functions::flattenArray($averageArgs); - if (empty($averageArgs)) { - $averageArgs = $aArgs; - } - $condition = Functions::ifCondition($condition); - $conditionIsNumeric = strpos($condition, '"') === false; - - // Loop through arguments - $aCount = 0; - foreach ($aArgs as $key => $arg) { - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - continue; - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - continue; - } - $testCondition = '=' . $arg . $condition; - if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - $returnValue += $averageArgs[$key]; - ++$aCount; - } - } - - if ($aCount > 0) { - return $returnValue / $aCount; - } - - return Functions::DIV0(); + return Conditional::AVERAGEIF($range, $condition, $averageRange); } /** @@ -750,44 +119,33 @@ public static function AVERAGEIF($aArgs, $condition, $averageArgs = []) * * Returns the beta distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Beta::distribution() + * Use the distribution() method in the Statistical\Distributions\Beta class instead + * * @param float $value Value at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * @param mixed $rMin * @param mixed $rMax * - * @return float|string + * @return array|float|string */ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) { - $value = Functions::flattenSingleValue($value); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); - - if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { - if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { - return Functions::NAN(); - } - if ($rMin > $rMax) { - $tmp = $rMin; - $rMin = $rMax; - $rMax = $tmp; - } - $value -= $rMin; - $value /= ($rMax - $rMin); - - return self::incompleteBeta($value, $alpha, $beta); - } - - return Functions::VALUE(); + return Statistical\Distributions\Beta::distribution($value, $alpha, $beta, $rMin, $rMax); } /** * BETAINV. * - * Returns the inverse of the beta distribution. + * Returns the inverse of the Beta distribution. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Beta::inverse() + * Use the inverse() method in the Statistical\Distributions\Beta class instead * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution @@ -795,48 +153,11 @@ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) * @param float $rMin Minimum value * @param float $rMax Maximum value * - * @return float|string + * @return array|float|string */ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1) { - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - $rMin = Functions::flattenSingleValue($rMin); - $rMax = Functions::flattenSingleValue($rMax); - - if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { - if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ($rMin > $rMax) { - $tmp = $rMin; - $rMin = $rMax; - $rMax = $tmp; - } - $a = 0; - $b = 2; - - $i = 0; - while ((($b - $a) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - $guess = ($a + $b) / 2; - $result = self::BETADIST($guess, $alpha, $beta); - if (($result == $probability) || ($result == 0)) { - $b = $a; - } elseif ($result > $probability) { - $b = $guess; - } else { - $a = $guess; - } - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($rMin + $guess * ($rMax - $rMin), 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\Beta::inverse($probability, $alpha, $beta, $rMin, $rMax); } /** @@ -848,43 +169,21 @@ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1 * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * - * @param float $value Number of successes in trials - * @param float $trials Number of trials - * @param float $probability Probability of success on each trial - * @param bool $cumulative + * @Deprecated 1.18.0 * - * @return float|string + * @see Statistical\Distributions\Binomial::distribution() + * Use the distribution() method in the Statistical\Distributions\Binomial class instead + * + * @param mixed $value Number of successes in trials + * @param mixed $trials Number of trials + * @param mixed $probability Probability of success on each trial + * @param mixed $cumulative + * + * @return array|float|string */ public static function BINOMDIST($value, $trials, $probability, $cumulative) { - $value = Functions::flattenSingleValue($value); - $trials = Functions::flattenSingleValue($trials); - $probability = Functions::flattenSingleValue($probability); - - if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) { - $value = floor($value); - $trials = floor($trials); - if (($value < 0) || ($value > $trials)) { - return Functions::NAN(); - } - if (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - $summer = 0; - for ($i = 0; $i <= $value; ++$i) { - $summer += MathTrig::COMBIN($trials, $i) * pow($probability, $i) * pow(1 - $probability, $trials - $i); - } - - return $summer; - } - - return MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::distribution($value, $trials, $probability, $cumulative); } /** @@ -892,33 +191,19 @@ public static function BINOMDIST($value, $trials, $probability, $cumulative) * * Returns the one-tailed probability of the chi-squared distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\ChiSquared::distributionRightTail() + * Use the distributionRightTail() method in the Statistical\Distributions\ChiSquared class instead + * * @param float $value Value for the function * @param float $degrees degrees of freedom * - * @return float|string + * @return array|float|string */ public static function CHIDIST($value, $degrees) { - $value = Functions::flattenSingleValue($value); - $degrees = Functions::flattenSingleValue($degrees); - - if ((is_numeric($value)) && (is_numeric($degrees))) { - $degrees = floor($degrees); - if ($degrees < 1) { - return Functions::NAN(); - } - if ($value < 0) { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - return 1; - } - - return Functions::NAN(); - } - - return 1 - (self::incompleteGamma($degrees / 2, $value / 2) / self::gamma($degrees / 2)); - } - - return Functions::VALUE(); + return Statistical\Distributions\ChiSquared::distributionRightTail($value, $degrees); } /** @@ -926,59 +211,19 @@ public static function CHIDIST($value, $degrees) * * Returns the one-tailed probability of the chi-squared distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\ChiSquared::inverseRightTail() + * Use the inverseRightTail() method in the Statistical\Distributions\ChiSquared class instead + * * @param float $probability Probability for the function * @param float $degrees degrees of freedom * - * @return float|string + * @return array|float|string */ public static function CHIINV($probability, $degrees) { - $probability = Functions::flattenSingleValue($probability); - $degrees = Functions::flattenSingleValue($degrees); - - if ((is_numeric($probability)) && (is_numeric($degrees))) { - $degrees = floor($degrees); - - $xLo = 100; - $xHi = 0; - - $x = $xNew = 1; - $dx = 1; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $result = 1 - (self::incompleteGamma($degrees / 2, $x / 2) / self::gamma($degrees / 2)); - $error = $result - $probability; - if ($error == 0.0) { - $dx = 0; - } elseif ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - // Avoid division by zero - if ($result != 0.0) { - $dx = $error / $result; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($x, 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\ChiSquared::inverseRightTail($probability, $degrees); } /** @@ -986,31 +231,20 @@ public static function CHIINV($probability, $degrees) * * Returns the confidence interval for a population mean * + * @Deprecated 1.18.0 + * + * @see Statistical\Confidence::CONFIDENCE() + * Use the CONFIDENCE() method in the Statistical\Confidence class instead + * * @param float $alpha * @param float $stdDev Standard Deviation * @param float $size * - * @return float|string + * @return array|float|string */ public static function CONFIDENCE($alpha, $stdDev, $size) { - $alpha = Functions::flattenSingleValue($alpha); - $stdDev = Functions::flattenSingleValue($stdDev); - $size = Functions::flattenSingleValue($size); - - if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) { - $size = floor($size); - if (($alpha <= 0) || ($alpha >= 1)) { - return Functions::NAN(); - } - if (($stdDev <= 0) || ($size < 1)) { - return Functions::NAN(); - } - - return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size); - } - - return Functions::VALUE(); + return Confidence::CONFIDENCE($alpha, $stdDev, $size); } /** @@ -1018,6 +252,11 @@ public static function CONFIDENCE($alpha, $stdDev, $size) * * Returns covariance, the average of the products of deviations for each data point pair. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::CORREL() + * Use the CORREL() method in the Statistical\Trends class instead + * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X * @@ -1025,24 +264,7 @@ public static function CONFIDENCE($alpha, $stdDev, $size) */ public static function CORREL($yValues, $xValues = null) { - if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { - return Functions::VALUE(); - } - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getCorrelation(); + return Trends::CORREL($xValues, $yValues); } /** @@ -1053,7 +275,10 @@ public static function CORREL($yValues, $xValues = null) * Excel Function: * COUNT(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNT() + * Use the COUNT() method in the Statistical\Counts class instead * * @param mixed ...$args Data values * @@ -1061,21 +286,7 @@ public static function CORREL($yValues, $xValues = null) */ public static function COUNT(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - foreach ($aArgs as $k => $arg) { - $arg = self::testAcceptedBoolean($arg, $k); - // Is it a numeric value? - // Strings containing numeric values are only counted if they are string literals (not cell values) - // and then only in MS Excel and in Open Office, not in Gnumeric - if (self::isAcceptedCountable($arg, $k)) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNT(...$args); } /** @@ -1086,7 +297,10 @@ public static function COUNT(...$args) * Excel Function: * COUNTA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNTA() + * Use the COUNTA() method in the Statistical\Counts class instead * * @param mixed ...$args Data values * @@ -1094,18 +308,7 @@ public static function COUNT(...$args) */ public static function COUNTA(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - foreach ($aArgs as $k => $arg) { - // Nulls are counted if literals, but not if cell values - if ($arg !== null || (!Functions::isCellValue($k))) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNTA(...$args); } /** @@ -1116,7 +319,10 @@ public static function COUNTA(...$args) * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Counts::COUNTBLANK() + * Use the COUNTBLANK() method in the Statistical\Counts class instead * * @param mixed ...$args Data values * @@ -1124,18 +330,7 @@ public static function COUNTA(...$args) */ public static function COUNTBLANK(...$args) { - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a blank cell? - if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { - ++$returnValue; - } - } - - return $returnValue; + return Counts::COUNTBLANK(...$args); } /** @@ -1144,40 +339,21 @@ public static function COUNTBLANK(...$args) * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: - * COUNTIF(value1[,value2[, ...]],condition) + * COUNTIF(range,condition) + * + * @Deprecated 1.17.0 * - * @category Statistical Functions + * @see Statistical\Conditional::COUNTIF() + * Use the COUNTIF() method in the Statistical\Conditional class instead * - * @param mixed $aArgs Data values + * @param mixed $range Data values * @param string $condition the criteria that defines which cells will be counted * * @return int */ - public static function COUNTIF($aArgs, $condition) + public static function COUNTIF($range, $condition) { - $returnValue = 0; - - $aArgs = Functions::flattenArray($aArgs); - $condition = Functions::ifCondition($condition); - $conditionIsNumeric = strpos($condition, '"') === false; - // Loop through arguments - foreach ($aArgs as $arg) { - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - continue; - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - continue; - } - $testCondition = '=' . $arg . $condition; - if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is it a value within our criteria - ++$returnValue; - } - } - - return $returnValue; + return Conditional::COUNTIF($range, $condition); } /** @@ -1188,68 +364,18 @@ public static function COUNTIF($aArgs, $condition) * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * - * @category Statistical Functions + * @Deprecated 1.17.0 * - * @param mixed $args Criterias + * @see Statistical\Conditional::COUNTIFS() + * Use the COUNTIFS() method in the Statistical\Conditional class instead + * + * @param mixed $args Pairs of Ranges and Criteria * * @return int */ public static function COUNTIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = 0; - - if (empty($arrayList)) { - return $returnValue; - } - - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach (array_keys($aArgsArray[0]) as $index) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $conditionIsNumeric = strpos($condition, '"') === false; - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - if ($conditionIsNumeric) { - $valid = false; - - break; // if false found, don't need to check other conditions - } - $arg = Calculation::wrapResult(strtoupper($arg)); - } elseif (!$conditionIsNumeric) { - $valid = false; - - break; // if false found, don't need to check other conditions - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - ++$returnValue; - } - } - - // Return - return $returnValue; + return Conditional::COUNTIFS(...$args); } /** @@ -1257,6 +383,11 @@ public static function COUNTIFS(...$args) * * Returns covariance, the average of the products of deviations for each data point pair. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::COVAR() + * Use the COVAR() method in the Statistical\Trends class instead + * * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues array of mixed Data Series X * @@ -1264,21 +395,7 @@ public static function COUNTIFS(...$args) */ public static function COVAR($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getCovariance(); + return Trends::COVAR($yValues, $xValues); } /** @@ -1289,123 +406,20 @@ public static function COVAR($yValues, $xValues) * * See https://support.microsoft.com/en-us/help/828117/ for details of the algorithm used * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Binomial::inverse() + * Use the inverse() method in the Statistical\Distributions\Binomial class instead + * * @param float $trials number of Bernoulli trials * @param float $probability probability of a success on each trial * @param float $alpha criterion value * - * @return int|string - * - * @todo Warning. This implementation differs from the algorithm detailed on the MS - * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess - * This eliminates a potential endless loop error, but may have an adverse affect on the - * accuracy of the function (although all my tests have so far returned correct results). + * @return array|int|string */ public static function CRITBINOM($trials, $probability, $alpha) { - $trials = floor(Functions::flattenSingleValue($trials)); - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - - if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) { - $trials = (int) $trials; - if ($trials < 0) { - return Functions::NAN(); - } elseif (($probability < 0.0) || ($probability > 1.0)) { - return Functions::NAN(); - } elseif (($alpha < 0.0) || ($alpha > 1.0)) { - return Functions::NAN(); - } - - if ($alpha <= 0.5) { - $t = sqrt(log(1 / ($alpha * $alpha))); - $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)); - } else { - $t = sqrt(log(1 / pow(1 - $alpha, 2))); - $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t); - } - - $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability))); - if ($Guess < 0) { - $Guess = 0; - } elseif ($Guess > $trials) { - $Guess = $trials; - } - - $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0; - $EssentiallyZero = 10e-12; - - $m = floor($trials * $probability); - ++$TotalUnscaledProbability; - if ($m == $Guess) { - ++$UnscaledPGuess; - } - if ($m <= $Guess) { - ++$UnscaledCumPGuess; - } - - $PreviousValue = 1; - $Done = false; - $k = $m + 1; - while ((!$Done) && ($k <= $trials)) { - $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability)); - $TotalUnscaledProbability += $CurrentValue; - if ($k == $Guess) { - $UnscaledPGuess += $CurrentValue; - } - if ($k <= $Guess) { - $UnscaledCumPGuess += $CurrentValue; - } - if ($CurrentValue <= $EssentiallyZero) { - $Done = true; - } - $PreviousValue = $CurrentValue; - ++$k; - } - - $PreviousValue = 1; - $Done = false; - $k = $m - 1; - while ((!$Done) && ($k >= 0)) { - $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability); - $TotalUnscaledProbability += $CurrentValue; - if ($k == $Guess) { - $UnscaledPGuess += $CurrentValue; - } - if ($k <= $Guess) { - $UnscaledCumPGuess += $CurrentValue; - } - if ($CurrentValue <= $EssentiallyZero) { - $Done = true; - } - $PreviousValue = $CurrentValue; - --$k; - } - - $PGuess = $UnscaledPGuess / $TotalUnscaledProbability; - $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability; - - $CumPGuessMinus1 = $CumPGuess - 1; - - while (true) { - if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) { - return $Guess; - } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) { - $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability); - $CumPGuessMinus1 = $CumPGuess; - $CumPGuess = $CumPGuess + $PGuessPlus1; - $PGuess = $PGuessPlus1; - ++$Guess; - } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) { - $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability; - $CumPGuess = $CumPGuessMinus1; - $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess; - $PGuess = $PGuessMinus1; - --$Guess; - } - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::inverse($trials, $probability, $alpha); } /** @@ -1416,7 +430,10 @@ public static function CRITBINOM($trials, $probability, $alpha) * Excel Function: * DEVSQ(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::sumSquares() + * Use the sumSquares() method in the Statistical\Deviations class instead * * @param mixed ...$args Data values * @@ -1424,40 +441,7 @@ public static function CRITBINOM($trials, $probability, $alpha) */ public static function DEVSQ(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean != Functions::DIV0()) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - // Is it a numeric value? - if ((is_bool($arg)) && - ((!Functions::isCellValue($k)) || - (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) { - $arg = (int) $arg; - } - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = pow(($arg - $aMean), 2); - } else { - $returnValue += pow(($arg - $aMean), 2); - } - ++$aCount; - } - } - - // Return - if ($returnValue === null) { - return Functions::NAN(); - } - - return $returnValue; - } - - return self::NA(); + return Statistical\Deviations::sumSquares(...$args); } /** @@ -1467,32 +451,46 @@ public static function DEVSQ(...$args) * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Exponential::distribution() + * Use the distribution() method in the Statistical\Distributions\Exponential class instead + * * @param float $value Value of the function * @param float $lambda The parameter value * @param bool $cumulative * - * @return float|string + * @return array|float|string */ public static function EXPONDIST($value, $lambda, $cumulative) { - $value = Functions::flattenSingleValue($value); - $lambda = Functions::flattenSingleValue($lambda); - $cumulative = Functions::flattenSingleValue($cumulative); - - if ((is_numeric($value)) && (is_numeric($lambda))) { - if (($value < 0) || ($lambda < 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 1 - exp(0 - $value * $lambda); - } - - return $lambda * exp(0 - $value * $lambda); - } - } + return Statistical\Distributions\Exponential::distribution($value, $lambda, $cumulative); + } - return Functions::VALUE(); + /** + * F.DIST. + * + * Returns the F probability distribution. + * You can use this function to determine whether two data sets have different degrees of diversity. + * For example, you can examine the test scores of men and women entering high school, and determine + * if the variability in the females is different from that found in the males. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\F::distribution() + * Use the distribution() method in the Statistical\Distributions\Exponential class instead + * + * @param float $value Value of the function + * @param int $u The numerator degrees of freedom + * @param int $v The denominator degrees of freedom + * @param bool $cumulative If cumulative is TRUE, F.DIST returns the cumulative distribution function; + * if FALSE, it returns the probability density function. + * + * @return array|float|string + */ + public static function FDIST2($value, $u, $v, $cumulative) + { + return Statistical\Distributions\F::distribution($value, $u, $v, $cumulative); } /** @@ -1502,23 +500,18 @@ public static function EXPONDIST($value, $lambda, $cumulative) * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Fisher::distribution() + * Use the distribution() method in the Statistical\Distributions\Fisher class instead + * * @param float $value * - * @return float|string + * @return array|float|string */ public static function FISHER($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - if (($value <= -1) || ($value >= 1)) { - return Functions::NAN(); - } - - return 0.5 * log((1 + $value) / (1 - $value)); - } - - return Functions::VALUE(); + return Statistical\Distributions\Fisher::distribution($value); } /** @@ -1528,19 +521,18 @@ public static function FISHER($value) * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Fisher::inverse() + * Use the inverse() method in the Statistical\Distributions\Fisher class instead + * * @param float $value * - * @return float|string + * @return array|float|string */ public static function FISHERINV($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - return (exp(2 * $value) - 1) / (exp(2 * $value) + 1); - } - - return Functions::VALUE(); + return Statistical\Distributions\Fisher::inverse($value); } /** @@ -1548,32 +540,39 @@ public static function FISHERINV($value) * * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::FORECAST() + * Use the FORECAST() method in the Statistical\Trends class instead + * * @param float $xValue Value of X for which we want to find Y * @param mixed $yValues array of mixed Data Series Y * @param mixed $xValues of mixed Data Series X * - * @return bool|float|string + * @return array|bool|float|string */ public static function FORECAST($xValue, $yValues, $xValues) { - $xValue = Functions::flattenSingleValue($xValue); - if (!is_numeric($xValue)) { - return Functions::VALUE(); - } elseif (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + return Trends::FORECAST($xValue, $yValues, $xValues); + } - return $bestFitLinear->getValueOfYForX($xValue); + /** + * GAMMA. + * + * Returns the gamma function value. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::gamma() + * Use the gamma() method in the Statistical\Distributions\Gamma class instead + * + * @param float $value + * + * @return array|float|string The result, or a string containing an error + */ + public static function GAMMAFunction($value) + { + return Statistical\Distributions\Gamma::gamma($value); } /** @@ -1581,96 +580,42 @@ public static function FORECAST($xValue, $yValues, $xValues) * * Returns the gamma distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::distribution() + * Use the distribution() method in the Statistical\Distributions\Gamma class instead + * * @param float $value Value at which you want to evaluate the distribution * @param float $a Parameter to the distribution * @param float $b Parameter to the distribution * @param bool $cumulative * - * @return float|string + * @return array|float|string */ public static function GAMMADIST($value, $a, $b, $cumulative) { - $value = Functions::flattenSingleValue($value); - $a = Functions::flattenSingleValue($a); - $b = Functions::flattenSingleValue($b); - - if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) { - if (($value < 0) || ($a <= 0) || ($b <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return self::incompleteGamma($a, $value / $b) / self::gamma($a); - } - - return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a - 1) * exp(0 - ($value / $b)); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Gamma::distribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * - * Returns the inverse of the beta distribution. + * Returns the inverse of the Gamma distribution. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::inverse() + * Use the inverse() method in the Statistical\Distributions\Gamma class instead * * @param float $probability Probability at which you want to evaluate the distribution * @param float $alpha Parameter to the distribution * @param float $beta Parameter to the distribution * - * @return float|string + * @return array|float|string */ public static function GAMMAINV($probability, $alpha, $beta) { - $probability = Functions::flattenSingleValue($probability); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - - if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) { - if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - - $xLo = 0; - $xHi = $alpha * $beta * 5; - - $x = $xNew = 1; - $error = $pdf = 0; - $dx = 1024; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability; - if ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - $pdf = self::GAMMADIST($x, $alpha, $beta, false); - // Avoid division by zero - if ($pdf != 0.0) { - $dx = $error / $pdf; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return $x; - } - - return Functions::VALUE(); + return Statistical\Distributions\Gamma::inverse($probability, $alpha, $beta); } /** @@ -1678,23 +623,38 @@ public static function GAMMAINV($probability, $alpha, $beta) * * Returns the natural logarithm of the gamma function. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Gamma::ln() + * Use the ln() method in the Statistical\Distributions\Gamma class instead + * * @param float $value * - * @return float|string + * @return array|float|string */ public static function GAMMALN($value) { - $value = Functions::flattenSingleValue($value); - - if (is_numeric($value)) { - if ($value <= 0) { - return Functions::NAN(); - } - - return log(self::gamma($value)); - } + return Statistical\Distributions\Gamma::ln($value); + } - return Functions::VALUE(); + /** + * GAUSS. + * + * Calculates the probability that a member of a standard normal population will fall between + * the mean and z standard deviations from the mean. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::gauss() + * Use the gauss() method in the Statistical\Distributions\StandardNormal class instead + * + * @param float $value + * + * @return array|float|string The result, or a string containing an error + */ + public static function GAUSS($value) + { + return Statistical\Distributions\StandardNormal::gauss($value); } /** @@ -1707,7 +667,10 @@ public static function GAMMALN($value) * Excel Function: * GEOMEAN(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Averages\Mean::geometric() + * Use the geometric() method in the Statistical\Averages\Mean class instead * * @param mixed ...$args Data values * @@ -1715,17 +678,7 @@ public static function GAMMALN($value) */ public static function GEOMEAN(...$args) { - $aArgs = Functions::flattenArray($args); - - $aMean = MathTrig::PRODUCT($aArgs); - if (is_numeric($aMean) && ($aMean > 0)) { - $aCount = self::COUNT($aArgs); - if (self::MIN($aArgs) > 0) { - return pow($aMean, (1 / $aCount)); - } - } - - return Functions::NAN(); + return Statistical\Averages\Mean::geometric(...$args); } /** @@ -1733,31 +686,21 @@ public static function GEOMEAN(...$args) * * Returns values along a predicted exponential Trend * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::GROWTH() + * Use the GROWTH() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * - * @return array of float + * @return float[] */ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) { - $yValues = Functions::flattenArray($yValues); - $xValues = Functions::flattenArray($xValues); - $newValues = Functions::flattenArray($newValues); - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - - $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); - if (empty($newValues)) { - $newValues = $bestFitExponential->getXValues(); - } - - $returnArray = []; - foreach ($newValues as $xValue) { - $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue); - } - - return $returnArray; + return Trends::GROWTH($yValues, $xValues, $newValues, $const); } /** @@ -1769,7 +712,10 @@ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = * Excel Function: * HARMEAN(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Averages\Mean::harmonic() + * Use the harmonic() method in the Statistical\Averages\Mean class instead * * @param mixed ...$args Data values * @@ -1777,32 +723,7 @@ public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = */ public static function HARMEAN(...$args) { - // Return value - $returnValue = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - if (self::MIN($aArgs) < 0) { - return Functions::NAN(); - } - $aCount = 0; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($arg <= 0) { - return Functions::NAN(); - } - $returnValue += (1 / $arg); - ++$aCount; - } - } - - // Return - if ($aCount > 0) { - return 1 / ($returnValue / $aCount); - } - - return Functions::NA(); + return Statistical\Averages\Mean::harmonic(...$args); } /** @@ -1811,37 +732,26 @@ public static function HARMEAN(...$args) * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * - * @param float $sampleSuccesses Number of successes in the sample - * @param float $sampleNumber Size of the sample - * @param float $populationSuccesses Number of successes in the population - * @param float $populationNumber Population size + * @Deprecated 1.18.0 * - * @return float|string + * @see Statistical\Distributions\HyperGeometric::distribution() + * Use the distribution() method in the Statistical\Distributions\HyperGeometric class instead + * + * @param mixed $sampleSuccesses Number of successes in the sample + * @param mixed $sampleNumber Size of the sample + * @param mixed $populationSuccesses Number of successes in the population + * @param mixed $populationNumber Population size + * + * @return array|float|string */ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { - $sampleSuccesses = floor(Functions::flattenSingleValue($sampleSuccesses)); - $sampleNumber = floor(Functions::flattenSingleValue($sampleNumber)); - $populationSuccesses = floor(Functions::flattenSingleValue($populationSuccesses)); - $populationNumber = floor(Functions::flattenSingleValue($populationNumber)); - - if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) { - if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { - return Functions::NAN(); - } - if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { - return Functions::NAN(); - } - if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { - return Functions::NAN(); - } - - return MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) * - MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) / - MathTrig::COMBIN($populationNumber, $sampleNumber); - } - - return Functions::VALUE(); + return Statistical\Distributions\HyperGeometric::distribution( + $sampleSuccesses, + $sampleNumber, + $populationSuccesses, + $populationNumber + ); } /** @@ -1849,6 +759,11 @@ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationS * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::INTERCEPT() + * Use the INTERCEPT() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -1856,21 +771,7 @@ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationS */ public static function INTERCEPT($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getIntersect(); + return Trends::INTERCEPT($yValues, $xValues); } /** @@ -1881,38 +782,18 @@ public static function INTERCEPT($yValues, $xValues) * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::kurtosis() + * Use the kurtosis() method in the Statistical\Deviations class instead + * * @param array ...$args Data Series * * @return float|string */ public static function KURT(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - $mean = self::AVERAGE($aArgs); - $stdDev = self::STDEV($aArgs); - - if ($stdDev > 0) { - $count = $summer = 0; - // Loop through arguments - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summer += pow((($arg - $mean) / $stdDev), 4); - ++$count; - } - } - } - - // Return - if ($count > 3) { - return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * pow($count - 1, 2) / (($count - 2) * ($count - 3))); - } - } - - return Functions::DIV0(); + return Statistical\Deviations::kurtosis(...$args); } /** @@ -1924,39 +805,18 @@ public static function KURT(...$args) * Excel Function: * LARGE(value1[,value2[, ...]],entry) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Size::large() + * Use the large() method in the Statistical\Size class instead * * @param mixed $args Data values - * @param int $entry Position (ordered from the largest) in the array or range of data to return * * @return float|string The result, or a string containing an error */ public static function LARGE(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = floor(array_pop($aArgs)); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $count = self::COUNT($mArgs); - $entry = floor(--$entry); - if (($entry < 0) || ($entry >= $count) || ($count == 0)) { - return Functions::NAN(); - } - rsort($mArgs); - - return $mArgs[$entry]; - } - - return Functions::VALUE(); + return Statistical\Size::large(...$args); } /** @@ -1965,6 +825,11 @@ public static function LARGE(...$args) * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, * and then returns an array that describes the line. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::LINEST() + * Use the LINEST() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 @@ -1974,48 +839,7 @@ public static function LARGE(...$args) */ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) { - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); - if ($xValues === null) { - $xValues = range(1, count(Functions::flattenArray($yValues))); - } - - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return 0; - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); - if ($stats) { - return [ - [ - $bestFitLinear->getSlope(), - $bestFitLinear->getSlopeSE(), - $bestFitLinear->getGoodnessOfFit(), - $bestFitLinear->getF(), - $bestFitLinear->getSSRegression(), - ], - [ - $bestFitLinear->getIntersect(), - $bestFitLinear->getIntersectSE(), - $bestFitLinear->getStdevOfResiduals(), - $bestFitLinear->getDFResiduals(), - $bestFitLinear->getSSResiduals(), - ], - ]; - } - - return [ - $bestFitLinear->getSlope(), - $bestFitLinear->getIntersect(), - ]; + return Trends::LINEST($yValues, $xValues, $const, $stats); } /** @@ -2024,6 +848,11 @@ public static function LINEST($yValues, $xValues = null, $const = true, $stats = * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::LOGEST() + * Use the LOGEST() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param bool $const a logical value specifying whether to force the intersect to equal 0 @@ -2033,54 +862,7 @@ public static function LINEST($yValues, $xValues = null, $const = true, $stats = */ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) { - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); - if ($xValues === null) { - $xValues = range(1, count(Functions::flattenArray($yValues))); - } - - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - foreach ($yValues as $value) { - if ($value <= 0.0) { - return Functions::NAN(); - } - } - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return 1; - } - - $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); - if ($stats) { - return [ - [ - $bestFitExponential->getSlope(), - $bestFitExponential->getSlopeSE(), - $bestFitExponential->getGoodnessOfFit(), - $bestFitExponential->getF(), - $bestFitExponential->getSSRegression(), - ], - [ - $bestFitExponential->getIntersect(), - $bestFitExponential->getIntersectSE(), - $bestFitExponential->getStdevOfResiduals(), - $bestFitExponential->getDFResiduals(), - $bestFitExponential->getSSResiduals(), - ], - ]; - } - - return [ - $bestFitExponential->getSlope(), - $bestFitExponential->getIntersect(), - ]; + return Trends::LOGEST($yValues, $xValues, $const, $stats); } /** @@ -2088,31 +870,24 @@ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = * * Returns the inverse of the normal cumulative distribution * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::inverse() + * Use the inverse() method in the Statistical\Distributions\LogNormal class instead + * * @param float $probability * @param float $mean * @param float $stdDev * - * @return float|string The result, or a string containing an error + * @return array|float|string The result, or a string containing an error * - * @todo Try implementing P J Acklam's refinement algorithm for greater + * @TODO Try implementing P J Acklam's refinement algorithm for greater * accuracy if I can get my head round the mathematics * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ */ public static function LOGINV($probability, $mean, $stdDev) { - $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) { - return Functions::NAN(); - } - - return exp($mean + $stdDev * self::NORMSINV($probability)); - } - - return Functions::VALUE(); + return Statistical\Distributions\LogNormal::inverse($probability, $mean, $stdDev); } /** @@ -2121,27 +896,43 @@ public static function LOGINV($probability, $mean, $stdDev) * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed * with parameters mean and standard_dev. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::cumulative() + * Use the cumulative() method in the Statistical\Distributions\LogNormal class instead + * * @param float $value * @param float $mean * @param float $stdDev * - * @return float|string The result, or a string containing an error + * @return array|float|string The result, or a string containing an error */ public static function LOGNORMDIST($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($value <= 0) || ($stdDev <= 0)) { - return Functions::NAN(); - } - - return self::NORMSDIST((log($value) - $mean) / $stdDev); - } + return Statistical\Distributions\LogNormal::cumulative($value, $mean, $stdDev); + } - return Functions::VALUE(); + /** + * LOGNORM.DIST. + * + * Returns the lognormal distribution of x, where ln(x) is normally distributed + * with parameters mean and standard_dev. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\LogNormal::distribution() + * Use the distribution() method in the Statistical\Distributions\LogNormal class instead + * + * @param float $value + * @param float $mean + * @param float $stdDev + * @param bool $cumulative + * + * @return array|float|string The result, or a string containing an error + */ + public static function LOGNORMDIST2($value, $mean, $stdDev, $cumulative = false) + { + return Statistical\Distributions\LogNormal::distribution($value, $mean, $stdDev, $cumulative); } /** @@ -2151,34 +942,20 @@ public static function LOGNORMDIST($value, $mean, $stdDev) * with negative numbers considered smaller than positive numbers. * * Excel Function: - * MAX(value1[,value2[, ...]]) + * max(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Maximum::max() + * Use the MAX() method in the Statistical\Maximum class instead */ public static function MAX(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if (($returnValue === null) || ($arg > $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Maximum::max(...$args); } /** @@ -2187,39 +964,20 @@ public static function MAX(...$args) * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: - * MAXA(value1[,value2[, ...]]) + * maxA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Maximum::maxA() + * Use the MAXA() method in the Statistical\Maximum class instead */ public static function MAXA(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if (($returnValue === null) || ($arg > $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Maximum::maxA(...$args); } /** @@ -2230,7 +988,10 @@ public static function MAXA(...$args) * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::MAXIFS() + * Use the MAXIFS() method in the Statistical\Conditional class instead * * @param mixed $args Data range and criterias * @@ -2238,47 +999,7 @@ public static function MAXA(...$args) */ public static function MAXIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = null; - - $maxArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach ($maxArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue = $returnValue === null ? $value : max($value, $returnValue); - } - } - - // Return - return $returnValue; + return Conditional::MAXIFS(...$args); } /** @@ -2289,7 +1010,10 @@ public static function MAXIFS(...$args) * Excel Function: * MEDIAN(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Averages::median() + * Use the median() method in the Statistical\Averages class instead * * @param mixed ...$args Data values * @@ -2297,31 +1021,7 @@ public static function MAXIFS(...$args) */ public static function MEDIAN(...$args) { - $returnValue = Functions::NAN(); - - $mArgs = []; - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - - $mValueCount = count($mArgs); - if ($mValueCount > 0) { - sort($mArgs, SORT_NUMERIC); - $mValueCount = $mValueCount / 2; - if ($mValueCount == floor($mValueCount)) { - $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2; - } else { - $mValueCount = floor($mValueCount); - $returnValue = $mArgs[$mValueCount]; - } - } - - return $returnValue; + return Statistical\Averages::median(...$args); } /** @@ -2333,32 +1033,18 @@ public static function MEDIAN(...$args) * Excel Function: * MIN(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Minimum::min() + * Use the min() method in the Statistical\Minimum class instead */ public static function MIN(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if (($returnValue === null) || ($arg < $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Minimum::min(...$args); } /** @@ -2369,37 +1055,18 @@ public static function MIN(...$args) * Excel Function: * MINA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 * * @param mixed ...$args Data values * * @return float + * + *@see Statistical\Minimum::minA() + * Use the minA() method in the Statistical\Minimum class instead */ public static function MINA(...$args) { - $returnValue = null; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if (($returnValue === null) || ($arg < $returnValue)) { - $returnValue = $arg; - } - } - } - - if ($returnValue === null) { - return 0; - } - - return $returnValue; + return Minimum::minA(...$args); } /** @@ -2410,7 +1077,10 @@ public static function MINA(...$args) * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Conditional::MINIFS() + * Use the MINIFS() method in the Statistical\Conditional class instead * * @param mixed $args Data range and criterias * @@ -2418,85 +1088,7 @@ public static function MINA(...$args) */ public static function MINIFS(...$args) { - $arrayList = $args; - - // Return value - $returnValue = null; - - $minArgs = Functions::flattenArray(array_shift($arrayList)); - $aArgsArray = []; - $conditions = []; - - while (count($arrayList) > 0) { - $aArgsArray[] = Functions::flattenArray(array_shift($arrayList)); - $conditions[] = Functions::ifCondition(array_shift($arrayList)); - } - - // Loop through each arg and see if arguments and conditions are true - foreach ($minArgs as $index => $value) { - $valid = true; - - foreach ($conditions as $cidx => $condition) { - $arg = $aArgsArray[$cidx][$index]; - - // Loop through arguments - if (!is_numeric($arg)) { - $arg = Calculation::wrapResult(strtoupper($arg)); - } - $testCondition = '=' . $arg . $condition; - if (!Calculation::getInstance()->_calculateFormulaValue($testCondition)) { - // Is not a value within our criteria - $valid = false; - - break; // if false found, don't need to check other conditions - } - } - - if ($valid) { - $returnValue = $returnValue === null ? $value : min($value, $returnValue); - } - } - - // Return - return $returnValue; - } - - // - // Special variant of array_count_values that isn't limited to strings and integers, - // but can work with floating point numbers as values - // - private static function modeCalc($data) - { - $frequencyArray = []; - foreach ($data as $datum) { - $found = false; - foreach ($frequencyArray as $key => $value) { - if ((string) $value['value'] == (string) $datum) { - ++$frequencyArray[$key]['frequency']; - $found = true; - - break; - } - } - if (!$found) { - $frequencyArray[] = [ - 'value' => $datum, - 'frequency' => 1, - ]; - } - } - - foreach ($frequencyArray as $key => $value) { - $frequencyList[$key] = $value['frequency']; - $valueList[$key] = $value['value']; - } - array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray); - - if ($frequencyArray[0]['frequency'] == 1) { - return Functions::NA(); - } - - return $frequencyArray[0]['value']; + return Conditional::MINIFS(...$args); } /** @@ -2507,7 +1099,10 @@ private static function modeCalc($data) * Excel Function: * MODE(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Averages::mode() + * Use the mode() method in the Statistical\Averages class instead * * @param mixed ...$args Data values * @@ -2515,24 +1110,7 @@ private static function modeCalc($data) */ public static function MODE(...$args) { - $returnValue = Functions::NA(); - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - - if (!empty($mArgs)) { - return self::modeCalc($mArgs); - } - - return $returnValue; + return Statistical\Averages::mode(...$args); } /** @@ -2544,34 +1122,20 @@ public static function MODE(...$args) * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * - * @param float $failures Number of Failures - * @param float $successes Threshold number of Successes - * @param float $probability Probability of success on each trial + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\Binomial::negative() + * Use the negative() method in the Statistical\Distributions\Binomial class instead + * + * @param mixed $failures Number of Failures + * @param mixed $successes Threshold number of Successes + * @param mixed $probability Probability of success on each trial + * + * @return array|float|string The result, or a string containing an error */ public static function NEGBINOMDIST($failures, $successes, $probability) { - $failures = floor(Functions::flattenSingleValue($failures)); - $successes = floor(Functions::flattenSingleValue($successes)); - $probability = Functions::flattenSingleValue($probability); - - if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) { - if (($failures < 0) || ($successes < 1)) { - return Functions::NAN(); - } elseif (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { - if (($failures + $successes - 1) <= 0) { - return Functions::NAN(); - } - } - - return (MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * (pow($probability, $successes)) * (pow(1 - $probability, $failures)); - } - - return Functions::VALUE(); + return Statistical\Distributions\Binomial::negative($failures, $successes, $probability); } /** @@ -2581,33 +1145,21 @@ public static function NEGBINOMDIST($failures, $successes, $probability) * function has a very wide range of applications in statistics, including hypothesis * testing. * - * @param float $value - * @param float $mean Mean Value - * @param float $stdDev Standard Deviation - * @param bool $cumulative + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\Normal::distribution() + * Use the distribution() method in the Statistical\Distributions\Normal class instead + * + * @param mixed $value + * @param mixed $mean Mean Value + * @param mixed $stdDev Standard Deviation + * @param mixed $cumulative + * + * @return array|float|string The result, or a string containing an error */ public static function NORMDIST($value, $mean, $stdDev, $cumulative) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if ($stdDev < 0) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 0.5 * (1 + Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2)))); - } - - return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean, 2) / (2 * ($stdDev * $stdDev)))); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Normal::distribution($value, $mean, $stdDev, $cumulative); } /** @@ -2615,30 +1167,20 @@ public static function NORMDIST($value, $mean, $stdDev, $cumulative) * * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. * - * @param float $probability - * @param float $mean Mean Value - * @param float $stdDev Standard Deviation + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\Normal::inverse() + * Use the inverse() method in the Statistical\Distributions\Normal class instead + * + * @param mixed $probability + * @param mixed $mean Mean Value + * @param mixed $stdDev Standard Deviation + * + * @return array|float|string The result, or a string containing an error */ public static function NORMINV($probability, $mean, $stdDev) { - $probability = Functions::flattenSingleValue($probability); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if (($probability < 0) || ($probability > 1)) { - return Functions::NAN(); - } - if ($stdDev < 0) { - return Functions::NAN(); - } - - return (self::inverseNcdf($probability) * $stdDev) + $mean; - } - - return Functions::VALUE(); + return Statistical\Distributions\Normal::inverse($probability, $mean, $stdDev); } /** @@ -2648,15 +1190,40 @@ public static function NORMINV($probability, $mean, $stdDev) * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * - * @param float $value + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\StandardNormal::cumulative() + * Use the cumulative() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value + * + * @return array|float|string The result, or a string containing an error */ public static function NORMSDIST($value) { - $value = Functions::flattenSingleValue($value); + return Statistical\Distributions\StandardNormal::cumulative($value); + } - return self::NORMDIST($value, 0, 1, true); + /** + * NORM.S.DIST. + * + * Returns the standard normal cumulative distribution function. The distribution has + * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a + * table of standard normal curve areas. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::distribution() + * Use the distribution() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value + * @param mixed $cumulative + * + * @return array|float|string The result, or a string containing an error + */ + public static function NORMSDIST2($value, $cumulative) + { + return Statistical\Distributions\StandardNormal::distribution($value, $cumulative); } /** @@ -2664,13 +1231,18 @@ public static function NORMSDIST($value) * * Returns the inverse of the standard normal cumulative distribution * - * @param float $value + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\StandardNormal::inverse() + * Use the inverse() method in the Statistical\Distributions\StandardNormal class instead + * + * @param mixed $value + * + * @return array|float|string The result, or a string containing an error */ public static function NORMSINV($value) { - return self::NORMINV($value, 0, 1); + return Statistical\Distributions\StandardNormal::inverse($value); } /** @@ -2681,95 +1253,42 @@ public static function NORMSINV($value) * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::PERCENTILE() + * Use the PERCENTILE() method in the Statistical\Percentiles class instead * * @param mixed $args Data values - * @param float $entry Percentile value in the range 0..1, inclusive. * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = array_pop($aArgs); - - if ((is_numeric($entry)) && (!is_string($entry))) { - if (($entry < 0) || ($entry > 1)) { - return Functions::NAN(); - } - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $mValueCount = count($mArgs); - if ($mValueCount > 0) { - sort($mArgs); - $count = self::COUNT($mArgs); - $index = $entry * ($count - 1); - $iBase = floor($index); - if ($index == $iBase) { - return $mArgs[$index]; - } - $iNext = $iBase + 1; - $iProportion = $index - $iBase; - - return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); - } - } - - return Functions::VALUE(); + return Statistical\Percentiles::PERCENTILE(...$args); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. + * Note that the returned rank is simply rounded to the appropriate significant digits, + * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return + * 0.667 rather than 0.666 * - * @param float[] $valueSet An array of, or a reference to, a list of numbers - * @param int $value the number whose rank you want to find - * @param int $significance the number of significant digits for the returned percentage value + * @Deprecated 1.18.0 * - * @return float + * @see Statistical\Percentiles::PERCENTRANK() + * Use the PERCENTRANK() method in the Statistical\Percentiles class instead + * + * @param mixed $valueSet An array of, or a reference to, a list of numbers + * @param mixed $value the number whose rank you want to find + * @param mixed $significance the number of significant digits for the returned percentage value + * + * @return float|string (string if result is an error) */ public static function PERCENTRANK($valueSet, $value, $significance = 3) { - $valueSet = Functions::flattenArray($valueSet); - $value = Functions::flattenSingleValue($value); - $significance = ($significance === null) ? 3 : (int) Functions::flattenSingleValue($significance); - - foreach ($valueSet as $key => $valueEntry) { - if (!is_numeric($valueEntry)) { - unset($valueSet[$key]); - } - } - sort($valueSet, SORT_NUMERIC); - $valueCount = count($valueSet); - if ($valueCount == 0) { - return Functions::NAN(); - } - - $valueAdjustor = $valueCount - 1; - if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { - return Functions::NA(); - } - - $pos = array_search($value, $valueSet); - if ($pos === false) { - $pos = 0; - $testValue = $valueSet[0]; - while ($testValue < $value) { - $testValue = $valueSet[++$pos]; - } - --$pos; - $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); - } - - return round($pos / $valueAdjustor, $significance); + return Statistical\Percentiles::PERCENTRANK($valueSet, $value, $significance); } /** @@ -2781,26 +1300,19 @@ public static function PERCENTRANK($valueSet, $value, $significance = 3) * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * + * @Deprecated 1.17.0 + * + * @see Statistical\Permutations::PERMUT() + * Use the PERMUT() method in the Statistical\Permutations class instead + * * @param int $numObjs Number of different objects * @param int $numInSet Number of objects in each permutation * - * @return int|string Number of permutations, or a string containing an error + * @return array|float|int|string Number of permutations, or a string containing an error */ public static function PERMUT($numObjs, $numInSet) { - $numObjs = Functions::flattenSingleValue($numObjs); - $numInSet = Functions::flattenSingleValue($numInSet); - - if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { - $numInSet = floor($numInSet); - if ($numObjs < $numInSet) { - return Functions::NAN(); - } - - return round(MathTrig::FACT($numObjs) / MathTrig::FACT($numObjs - $numInSet)); - } - - return Functions::VALUE(); + return Permutations::PERMUT($numObjs, $numInSet); } /** @@ -2810,37 +1322,20 @@ public static function PERMUT($numObjs, $numInSet) * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * - * @param float $value - * @param float $mean Mean Value - * @param bool $cumulative + * @Deprecated 1.18.0 * - * @return float|string The result, or a string containing an error + * @see Statistical\Distributions\Poisson::distribution() + * Use the distribution() method in the Statistical\Distributions\Poisson class instead + * + * @param mixed $value + * @param mixed $mean Mean Value + * @param mixed $cumulative + * + * @return array|float|string The result, or a string containing an error */ public static function POISSON($value, $mean, $cumulative) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - - if ((is_numeric($value)) && (is_numeric($mean))) { - if (($value < 0) || ($mean <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - $summer = 0; - $floor = floor($value); - for ($i = 0; $i <= $floor; ++$i) { - $summer += pow($mean, $i) / MathTrig::FACT($i); - } - - return exp(0 - $mean) * $summer; - } - - return (exp(0 - $mean) * pow($mean, $value)) / MathTrig::FACT($value); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Poisson::distribution($value, $mean, $cumulative); } /** @@ -2851,30 +1346,18 @@ public static function POISSON($value, $mean, $cumulative) * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::QUARTILE() + * Use the QUARTILE() method in the Statistical\Percentiles class instead * * @param mixed $args Data values - * @param int $entry Quartile value in the range 1..3, inclusive. * * @return float|string The result, or a string containing an error */ public static function QUARTILE(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = floor(array_pop($aArgs)); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $entry /= 4; - if (($entry < 0) || ($entry > 1)) { - return Functions::NAN(); - } - - return self::PERCENTILE($aArgs, $entry); - } - - return Functions::VALUE(); + return Statistical\Percentiles::QUARTILE(...$args); } /** @@ -2882,35 +1365,20 @@ public static function QUARTILE(...$args) * * Returns the rank of a number in a list of numbers. * - * @param int $value the number whose rank you want to find - * @param float[] $valueSet An array of, or a reference to, a list of numbers - * @param int $order Order to sort the values in the value set + * @Deprecated 1.18.0 + * + * @see Statistical\Percentiles::RANK() + * Use the RANK() method in the Statistical\Percentiles class instead + * + * @param mixed $value the number whose rank you want to find + * @param mixed $valueSet An array of, or a reference to, a list of numbers + * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error */ public static function RANK($value, $valueSet, $order = 0) { - $value = Functions::flattenSingleValue($value); - $valueSet = Functions::flattenArray($valueSet); - $order = ($order === null) ? 0 : (int) Functions::flattenSingleValue($order); - - foreach ($valueSet as $key => $valueEntry) { - if (!is_numeric($valueEntry)) { - unset($valueSet[$key]); - } - } - - if ($order == 0) { - rsort($valueSet, SORT_NUMERIC); - } else { - sort($valueSet, SORT_NUMERIC); - } - $pos = array_search($value, $valueSet); - if ($pos === false) { - return Functions::NA(); - } - - return ++$pos; + return Statistical\Percentiles::RANK($value, $valueSet, $order); } /** @@ -2918,6 +1386,11 @@ public static function RANK($value, $valueSet, $order = 0) * * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::RSQ() + * Use the RSQ() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -2925,21 +1398,7 @@ public static function RANK($value, $valueSet, $order = 0) */ public static function RSQ($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getGoodnessOfFit(); + return Trends::RSQ($yValues, $xValues); } /** @@ -2950,35 +1409,18 @@ public static function RSQ($yValues, $xValues) * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * + * @Deprecated 1.18.0 + * + * @see Statistical\Deviations::skew() + * Use the skew() method in the Statistical\Deviations class instead + * * @param array ...$args Data Series * * @return float|string The result, or a string containing an error */ public static function SKEW(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - $mean = self::AVERAGE($aArgs); - $stdDev = self::STDEV($aArgs); - - $count = $summer = 0; - // Loop through arguments - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summer += pow((($arg - $mean) / $stdDev), 3); - ++$count; - } - } - } - - if ($count > 2) { - return $summer * ($count / (($count - 1) * ($count - 2))); - } - - return Functions::DIV0(); + return Statistical\Deviations::skew(...$args); } /** @@ -2986,6 +1428,11 @@ public static function SKEW(...$args) * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::SLOPE() + * Use the SLOPE() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @@ -2993,21 +1440,7 @@ public static function SKEW(...$args) */ public static function SLOPE($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getSlope(); + return Trends::SLOPE($yValues, $xValues); } /** @@ -3019,39 +1452,18 @@ public static function SLOPE($yValues, $xValues) * Excel Function: * SMALL(value1[,value2[, ...]],entry) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + * @see Statistical\Size::small() + * Use the small() method in the Statistical\Size class instead * * @param mixed $args Data values - * @param int $entry Position (ordered from the smallest) in the array or range of data to return * * @return float|string The result, or a string containing an error */ public static function SMALL(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $entry = array_pop($aArgs); - - if ((is_numeric($entry)) && (!is_string($entry))) { - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $count = self::COUNT($mArgs); - $entry = floor(--$entry); - if (($entry < 0) || ($entry >= $count) || ($count == 0)) { - return Functions::NAN(); - } - sort($mArgs); - - return $mArgs[$entry]; - } - - return Functions::VALUE(); + return Statistical\Size::small(...$args); } /** @@ -3059,27 +1471,20 @@ public static function SMALL(...$args) * * Returns a normalized value from a distribution characterized by mean and standard_dev. * + * @Deprecated 1.18.0 + * + * @see Statistical\Standardize::execute() + * Use the execute() method in the Statistical\Standardize class instead + * * @param float $value Value to normalize * @param float $mean Mean Value * @param float $stdDev Standard Deviation * - * @return float|string Standardized value, or a string containing an error + * @return array|float|string Standardized value, or a string containing an error */ public static function STANDARDIZE($value, $mean, $stdDev) { - $value = Functions::flattenSingleValue($value); - $mean = Functions::flattenSingleValue($mean); - $stdDev = Functions::flattenSingleValue($stdDev); - - if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { - if ($stdDev <= 0) { - return Functions::NAN(); - } - - return ($value - $mean) / $stdDev; - } - - return Functions::VALUE(); + return Statistical\Standardize::execute($value, $mean, $stdDev); } /** @@ -3091,7 +1496,10 @@ public static function STANDARDIZE($value, $mean, $stdDev) * Excel Function: * STDEV(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEV() + * Use the STDEV() method in the Statistical\StandardDeviations class instead * * @param mixed ...$args Data values * @@ -3099,37 +1507,7 @@ public static function STANDARDIZE($value, $mean, $stdDev) */ public static function STDEV(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - // Return value - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean !== null) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = pow(($arg - $aMean), 2); - } else { - $returnValue += pow(($arg - $aMean), 2); - } - ++$aCount; - } - } - - // Return - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEV(...$args); } /** @@ -3140,7 +1518,10 @@ public static function STDEV(...$args) * Excel Function: * STDEVA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVA() + * Use the STDEVA() method in the Statistical\StandardDeviations class instead * * @param mixed ...$args Data values * @@ -3148,40 +1529,7 @@ public static function STDEV(...$args) */ public static function STDEVA(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGEA($aArgs); - if ($aMean !== null) { - $aCount = -1; - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if ($returnValue === null) { - $returnValue = pow(($arg - $aMean), 2); - } else { - $returnValue += pow(($arg - $aMean), 2); - } - ++$aCount; - } - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVA(...$args); } /** @@ -3192,7 +1540,10 @@ public static function STDEVA(...$args) * Excel Function: * STDEVP(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVP() + * Use the STDEVP() method in the Statistical\StandardDeviations class instead * * @param mixed ...$args Data values * @@ -3200,35 +1551,7 @@ public static function STDEVA(...$args) */ public static function STDEVP(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGE($aArgs); - if ($aMean !== null) { - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - if ($returnValue === null) { - $returnValue = pow(($arg - $aMean), 2); - } else { - $returnValue += pow(($arg - $aMean), 2); - } - ++$aCount; - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVP(...$args); } /** @@ -3239,7 +1562,10 @@ public static function STDEVP(...$args) * Excel Function: * STDEVPA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\StandardDeviations::STDEVPA() + * Use the STDEVPA() method in the Statistical\StandardDeviations class instead * * @param mixed ...$args Data values * @@ -3247,45 +1573,17 @@ public static function STDEVP(...$args) */ public static function STDEVPA(...$args) { - $aArgs = Functions::flattenArrayIndexed($args); - - $returnValue = null; - - $aMean = self::AVERAGEA($aArgs); - if ($aMean !== null) { - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ((is_bool($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - if ($returnValue === null) { - $returnValue = pow(($arg - $aMean), 2); - } else { - $returnValue += pow(($arg - $aMean), 2); - } - ++$aCount; - } - } - } - - if (($aCount > 0) && ($returnValue >= 0)) { - return sqrt($returnValue / $aCount); - } - } - - return Functions::DIV0(); + return StandardDeviations::STDEVPA(...$args); } /** * STEYX. * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::STEYX() + * Use the STEYX() method in the Statistical\Trends class instead + * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y @@ -3295,21 +1593,7 @@ public static function STDEVPA(...$args) */ public static function STEYX($yValues, $xValues) { - if (!self::checkTrendArrays($yValues, $xValues)) { - return Functions::VALUE(); - } - $yValueCount = count($yValues); - $xValueCount = count($xValues); - - if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { - return Functions::NA(); - } elseif ($yValueCount == 1) { - return Functions::DIV0(); - } - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); - - return $bestFitLinear->getStdevOfResiduals(); + return Trends::STEYX($yValues, $xValues); } /** @@ -3317,122 +1601,40 @@ public static function STEYX($yValues, $xValues) * * Returns the probability of Student's T distribution. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StudentT::distribution() + * Use the distribution() method in the Statistical\Distributions\StudentT class instead + * * @param float $value Value for the function * @param float $degrees degrees of freedom * @param float $tails number of tails (1 or 2) * - * @return float|string The result, or a string containing an error + * @return array|float|string The result, or a string containing an error */ public static function TDIST($value, $degrees, $tails) { - $value = Functions::flattenSingleValue($value); - $degrees = floor(Functions::flattenSingleValue($degrees)); - $tails = floor(Functions::flattenSingleValue($tails)); - - if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) { - if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { - return Functions::NAN(); - } - // tdist, which finds the probability that corresponds to a given value - // of t with k degrees of freedom. This algorithm is translated from a - // pascal function on p81 of "Statistical Computing in Pascal" by D - // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: - // London). The above Pascal algorithm is itself a translation of the - // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer - // Laboratory as reported in (among other places) "Applied Statistics - // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis - // Horwood Ltd.; W. Sussex, England). - $tterm = $degrees; - $ttheta = atan2($value, sqrt($tterm)); - $tc = cos($ttheta); - $ts = sin($ttheta); - $tsum = 0; - - if (($degrees % 2) == 1) { - $ti = 3; - $tterm = $tc; - } else { - $ti = 2; - $tterm = 1; - } - - $tsum = $tterm; - while ($ti < $degrees) { - $tterm *= $tc * $tc * ($ti - 1) / $ti; - $tsum += $tterm; - $ti += 2; - } - $tsum *= $ts; - if (($degrees % 2) == 1) { - $tsum = Functions::M_2DIVPI * ($tsum + $ttheta); - } - $tValue = 0.5 * (1 + $tsum); - if ($tails == 1) { - return 1 - abs($tValue); - } - - return 1 - abs((1 - $tValue) - $tValue); - } - - return Functions::VALUE(); + return Statistical\Distributions\StudentT::distribution($value, $degrees, $tails); } /** * TINV. * - * Returns the one-tailed probability of the chi-squared distribution. + * Returns the one-tailed probability of the Student-T distribution. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StudentT::inverse() + * Use the inverse() method in the Statistical\Distributions\StudentT class instead * * @param float $probability Probability for the function * @param float $degrees degrees of freedom * - * @return float|string The result, or a string containing an error + * @return array|float|string The result, or a string containing an error */ public static function TINV($probability, $degrees) { - $probability = Functions::flattenSingleValue($probability); - $degrees = floor(Functions::flattenSingleValue($degrees)); - - if ((is_numeric($probability)) && (is_numeric($degrees))) { - $xLo = 100; - $xHi = 0; - - $x = $xNew = 1; - $dx = 1; - $i = 0; - - while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { - // Apply Newton-Raphson step - $result = self::TDIST($x, $degrees, 2); - $error = $result - $probability; - if ($error == 0.0) { - $dx = 0; - } elseif ($error < 0.0) { - $xLo = $x; - } else { - $xHi = $x; - } - // Avoid division by zero - if ($result != 0.0) { - $dx = $error / $result; - $xNew = $x - $dx; - } - // If the NR fails to converge (which for example may be the - // case if the initial guess is too rough) we apply a bisection - // step to determine a more narrow interval around the root. - if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { - $xNew = ($xLo + $xHi) / 2; - $dx = $xNew - $x; - } - $x = $xNew; - } - if ($i == self::MAX_ITERATIONS) { - return Functions::NA(); - } - - return round($x, 12); - } - - return Functions::VALUE(); + return Statistical\Distributions\StudentT::inverse($probability, $degrees); } /** @@ -3440,31 +1642,21 @@ public static function TINV($probability, $degrees) * * Returns values along a linear Trend * + * @Deprecated 1.18.0 + * + * @see Statistical\Trends::TREND() + * Use the TREND() method in the Statistical\Trends class instead + * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param bool $const a logical value specifying whether to force the intersect to equal 0 * - * @return array of float + * @return float[] */ public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) { - $yValues = Functions::flattenArray($yValues); - $xValues = Functions::flattenArray($xValues); - $newValues = Functions::flattenArray($newValues); - $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); - - $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); - if (empty($newValues)) { - $newValues = $bestFitLinear->getXValues(); - } - - $returnArray = []; - foreach ($newValues as $xValue) { - $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue); - } - - return $returnArray; + return Trends::TREND($yValues, $xValues, $newValues, $const); } /** @@ -3477,42 +1669,18 @@ public static function TREND($yValues, $xValues = [], $newValues = [], $const = * Excel Function: * TRIMEAN(value1[,value2[, ...]], $discard) * - * @category Statistical Functions + * @Deprecated 1.18.0 + * + *@see Statistical\Averages\Mean::trim() + * Use the trim() method in the Statistical\Averages\Mean class instead * * @param mixed $args Data values - * @param float $discard Percentage to discard * * @return float|string */ public static function TRIMMEAN(...$args) { - $aArgs = Functions::flattenArray($args); - - // Calculate - $percent = array_pop($aArgs); - - if ((is_numeric($percent)) && (!is_string($percent))) { - if (($percent < 0) || ($percent > 1)) { - return Functions::NAN(); - } - $mArgs = []; - foreach ($aArgs as $arg) { - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $mArgs[] = $arg; - } - } - $discard = floor(self::COUNT($mArgs) * $percent / 2); - sort($mArgs); - for ($i = 0; $i < $discard; ++$i) { - array_pop($mArgs); - array_shift($mArgs); - } - - return self::AVERAGE($mArgs); - } - - return Functions::VALUE(); + return Statistical\Averages\Mean::trim(...$args); } /** @@ -3523,40 +1691,18 @@ public static function TRIMMEAN(...$args) * Excel Function: * VAR(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + *@see Statistical\Variances::VAR() + * Use the VAR() method in the Statistical\Variances class instead * * @param mixed ...$args Data values * - * @return float + * @return float|string (string if result is an error) */ public static function VARFunc(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - $aCount = 0; - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - - if ($aCount > 1) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); - } - - return $returnValue; + return Variances::VAR(...$args); } /** @@ -3567,49 +1713,18 @@ public static function VARFunc(...$args) * Excel Function: * VARA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARA() + * Use the VARA() method in the Statistical\Variances class instead * * @param mixed ...$args Data values * - * @return float + * @return float|string (string if result is an error) */ public static function VARA(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ((is_string($arg)) && - (Functions::isValue($k))) { - return Functions::VALUE(); - } elseif ((is_string($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - } - - if ($aCount > 1) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); - } - - return $returnValue; + return Variances::VARA(...$args); } /** @@ -3620,41 +1735,18 @@ public static function VARA(...$args) * Excel Function: * VARP(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARP() + * Use the VARP() method in the Statistical\Variances class instead * * @param mixed ...$args Data values * - * @return float + * @return float|string (string if result is an error) */ public static function VARP(...$args) { - // Return value - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - $aCount = 0; - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = (int) $arg; - } - // Is it a numeric value? - if ((is_numeric($arg)) && (!is_string($arg))) { - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - - if ($aCount > 0) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * $aCount); - } - - return $returnValue; + return Variances::VARP(...$args); } /** @@ -3665,49 +1757,18 @@ public static function VARP(...$args) * Excel Function: * VARPA(value1[,value2[, ...]]) * - * @category Statistical Functions + * @Deprecated 1.17.0 + * + * @see Statistical\Variances::VARPA() + * Use the VARPA() method in the Statistical\Variances class instead * * @param mixed ...$args Data values * - * @return float + * @return float|string (string if result is an error) */ public static function VARPA(...$args) { - $returnValue = Functions::DIV0(); - - $summerA = $summerB = 0; - - // Loop through arguments - $aArgs = Functions::flattenArrayIndexed($args); - $aCount = 0; - foreach ($aArgs as $k => $arg) { - if ((is_string($arg)) && - (Functions::isValue($k))) { - return Functions::VALUE(); - } elseif ((is_string($arg)) && - (!Functions::isMatrixValue($k))) { - } else { - // Is it a numeric value? - if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { - if (is_bool($arg)) { - $arg = (int) $arg; - } elseif (is_string($arg)) { - $arg = 0; - } - $summerA += ($arg * $arg); - $summerB += $arg; - ++$aCount; - } - } - } - - if ($aCount > 0) { - $summerA *= $aCount; - $summerB *= $summerB; - $returnValue = ($summerA - $summerB) / ($aCount * $aCount); - } - - return $returnValue; + return Variances::VARPA(...$args); } /** @@ -3716,58 +1777,44 @@ public static function VARPA(...$args) * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\Weibull::distribution() + * Use the distribution() method in the Statistical\Distributions\Weibull class instead + * * @param float $value * @param float $alpha Alpha Parameter * @param float $beta Beta Parameter * @param bool $cumulative * - * @return float + * @return array|float|string (string if result is an error) */ public static function WEIBULL($value, $alpha, $beta, $cumulative) { - $value = Functions::flattenSingleValue($value); - $alpha = Functions::flattenSingleValue($alpha); - $beta = Functions::flattenSingleValue($beta); - - if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) { - if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { - return Functions::NAN(); - } - if ((is_numeric($cumulative)) || (is_bool($cumulative))) { - if ($cumulative) { - return 1 - exp(0 - pow($value / $beta, $alpha)); - } - - return ($alpha / pow($beta, $alpha)) * pow($value, $alpha - 1) * exp(0 - pow($value / $beta, $alpha)); - } - } - - return Functions::VALUE(); + return Statistical\Distributions\Weibull::distribution($value, $alpha, $beta, $cumulative); } /** * ZTEST. * - * Returns the Weibull distribution. Use this distribution in reliability - * analysis, such as calculating a device's mean time to failure. + * Returns the one-tailed P-value of a z-test. + * + * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be + * greater than the average of observations in the data set (array) — that is, the observed sample mean. + * + * @Deprecated 1.18.0 + * + * @see Statistical\Distributions\StandardNormal::zTest() + * Use the zTest() method in the Statistical\Distributions\StandardNormal class instead * * @param float $dataSet * @param float $m0 Alpha Parameter * @param float $sigma Beta Parameter * - * @return float|string + * @return array|float|string (string if result is an error) */ public static function ZTEST($dataSet, $m0, $sigma = null) { - $dataSet = Functions::flattenArrayIndexed($dataSet); - $m0 = Functions::flattenSingleValue($m0); - $sigma = Functions::flattenSingleValue($sigma); - - if ($sigma === null) { - $sigma = self::STDEV($dataSet); - } - $n = count($dataSet); - - return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0) / ($sigma / sqrt($n))); + return Statistical\Distributions\StandardNormal::zTest($dataSet, $m0, $sigma); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php new file mode 100644 index 00000000..75c012dc --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php @@ -0,0 +1,50 @@ + $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { + return ExcelError::VALUE(); + } + if (self::isAcceptedCountable($arg, $k)) { + $returnValue += abs($arg - $aMean); + ++$aCount; + } + } + + // Return + if ($aCount === 0) { + return ExcelError::DIV0(); + } + + return $returnValue / $aCount; + } + + /** + * AVERAGE. + * + * Returns the average (arithmetic mean) of the arguments + * + * Excel Function: + * AVERAGE(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function average(...$args) + { + $returnValue = $aCount = 0; + + // Loop through arguments + foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { + return ExcelError::VALUE(); + } + if (self::isAcceptedCountable($arg, $k)) { + $returnValue += $arg; + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } + + return ExcelError::DIV0(); + } + + /** + * AVERAGEA. + * + * Returns the average of its arguments, including numbers, text, and logical values + * + * Excel Function: + * AVERAGEA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function averageA(...$args) + { + $returnValue = null; + + $aCount = 0; + // Loop through arguments + foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } else { + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (int) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $returnValue += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + return $returnValue / $aCount; + } + + return ExcelError::DIV0(); + } + + /** + * MEDIAN. + * + * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. + * + * Excel Function: + * MEDIAN(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function median(...$args) + { + $aArgs = Functions::flattenArray($args); + + $returnValue = ExcelError::NAN(); + + $aArgs = self::filterArguments($aArgs); + $valueCount = count($aArgs); + if ($valueCount > 0) { + sort($aArgs, SORT_NUMERIC); + $valueCount = $valueCount / 2; + if ($valueCount == floor($valueCount)) { + $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; + } else { + $valueCount = floor($valueCount); + $returnValue = $aArgs[$valueCount]; + } + } + + return $returnValue; + } + + /** + * MODE. + * + * Returns the most frequently occurring, or repetitive, value in an array or range of data + * + * Excel Function: + * MODE(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function mode(...$args) + { + $returnValue = ExcelError::NA(); + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + $aArgs = self::filterArguments($aArgs); + + if (!empty($aArgs)) { + return self::modeCalc($aArgs); + } + + return $returnValue; + } + + protected static function filterArguments($args) + { + return array_filter( + $args, + function ($value) { + // Is it a numeric value? + return (is_numeric($value)) && (!is_string($value)); + } + ); + } + + // + // Special variant of array_count_values that isn't limited to strings and integers, + // but can work with floating point numbers as values + // + private static function modeCalc($data) + { + $frequencyArray = []; + $index = 0; + $maxfreq = 0; + $maxfreqkey = ''; + $maxfreqdatum = ''; + foreach ($data as $datum) { + $found = false; + ++$index; + foreach ($frequencyArray as $key => $value) { + if ((string) $value['value'] == (string) $datum) { + ++$frequencyArray[$key]['frequency']; + $freq = $frequencyArray[$key]['frequency']; + if ($freq > $maxfreq) { + $maxfreq = $freq; + $maxfreqkey = $key; + $maxfreqdatum = $datum; + } elseif ($freq == $maxfreq) { + if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { + $maxfreqkey = $key; + $maxfreqdatum = $datum; + } + } + $found = true; + + break; + } + } + + if ($found === false) { + $frequencyArray[] = [ + 'value' => $datum, + 'frequency' => 1, + 'index' => $index, + ]; + } + } + + if ($maxfreq <= 1) { + return ExcelError::NA(); + } + + return $maxfreqdatum; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php new file mode 100644 index 00000000..001c91eb --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Averages/Mean.php @@ -0,0 +1,132 @@ + 0)) { + $aCount = Counts::COUNT($aArgs); + if (Minimum::min($aArgs) > 0) { + return $aMean ** (1 / $aCount); + } + } + + return ExcelError::NAN(); + } + + /** + * HARMEAN. + * + * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the + * arithmetic mean of reciprocals. + * + * Excel Function: + * HARMEAN(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string + */ + public static function harmonic(...$args) + { + // Loop through arguments + $aArgs = Functions::flattenArray($args); + if (Minimum::min($aArgs) < 0) { + return ExcelError::NAN(); + } + + $returnValue = 0; + $aCount = 0; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ($arg <= 0) { + return ExcelError::NAN(); + } + $returnValue += (1 / $arg); + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return 1 / ($returnValue / $aCount); + } + + return ExcelError::NA(); + } + + /** + * TRIMMEAN. + * + * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean + * taken by excluding a percentage of data points from the top and bottom tails + * of a data set. + * + * Excel Function: + * TRIMEAN(value1[,value2[, ...]], $discard) + * + * @param mixed $args Data values + * + * @return float|string + */ + public static function trim(...$args) + { + $aArgs = Functions::flattenArray($args); + + // Calculate + $percent = array_pop($aArgs); + + if ((is_numeric($percent)) && (!is_string($percent))) { + if (($percent < 0) || ($percent > 1)) { + return ExcelError::NAN(); + } + + $mArgs = []; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + $discard = floor(Counts::COUNT($mArgs) * $percent / 2); + sort($mArgs); + + for ($i = 0; $i < $discard; ++$i) { + array_pop($mArgs); + array_shift($mArgs); + } + + return Averages::average($mArgs); + } + + return ExcelError::VALUE(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php new file mode 100644 index 00000000..51e6b004 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php @@ -0,0 +1,304 @@ +getMessage(); + } + + if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { + return ExcelError::NAN(); + } + /** @var float */ + $temp = Distributions\StandardNormal::inverse(1 - $alpha / 2); + + return Functions::scalar($temp * $stdDev / sqrt($size)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php new file mode 100644 index 00000000..13e7af79 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Counts.php @@ -0,0 +1,95 @@ + $arg) { + $arg = self::testAcceptedBoolean($arg, $k); + // Is it a numeric value? + // Strings containing numeric values are only counted if they are string literals (not cell values) + // and then only in MS Excel and in Open Office, not in Gnumeric + if (self::isAcceptedCountable($arg, $k)) { + ++$returnValue; + } + } + + return $returnValue; + } + + /** + * COUNTA. + * + * Counts the number of cells that are not empty within the list of arguments + * + * Excel Function: + * COUNTA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int + */ + public static function COUNTA(...$args) + { + $returnValue = 0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + foreach ($aArgs as $k => $arg) { + // Nulls are counted if literals, but not if cell values + if ($arg !== null || (!Functions::isCellValue($k))) { + ++$returnValue; + } + } + + return $returnValue; + } + + /** + * COUNTBLANK. + * + * Counts the number of empty cells within the list of arguments + * + * Excel Function: + * COUNTBLANK(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return int + */ + public static function COUNTBLANK(...$args) + { + $returnValue = 0; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + foreach ($aArgs as $arg) { + // Is it a blank cell? + if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { + ++$returnValue; + } + } + + return $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php new file mode 100644 index 00000000..6b1db3a4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php @@ -0,0 +1,142 @@ + $arg) { + // Is it a numeric value? + if ( + (is_bool($arg)) && + ((!Functions::isCellValue($k)) || + (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) + ) { + $arg = (int) $arg; + } + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += ($arg - $aMean) ** 2; + ++$aCount; + } + } + + return $aCount === 0 ? ExcelError::VALUE() : $returnValue; + } + + /** + * KURT. + * + * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness + * or flatness of a distribution compared with the normal distribution. Positive + * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a + * relatively flat distribution. + * + * @param array ...$args Data Series + * + * @return float|string + */ + public static function kurtosis(...$args) + { + $aArgs = Functions::flattenArrayIndexed($args); + $mean = Averages::average($aArgs); + if (!is_numeric($mean)) { + return ExcelError::DIV0(); + } + $stdDev = StandardDeviations::STDEV($aArgs); + + if ($stdDev > 0) { + $count = $summer = 0; + + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += (($arg - $mean) / $stdDev) ** 4; + ++$count; + } + } + } + + if ($count > 3) { + return $summer * ($count * ($count + 1) / + (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / + (($count - 2) * ($count - 3))); + } + } + + return ExcelError::DIV0(); + } + + /** + * SKEW. + * + * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry + * of a distribution around its mean. Positive skewness indicates a distribution with an + * asymmetric tail extending toward more positive values. Negative skewness indicates a + * distribution with an asymmetric tail extending toward more negative values. + * + * @param array ...$args Data Series + * + * @return float|int|string The result, or a string containing an error + */ + public static function skew(...$args) + { + $aArgs = Functions::flattenArrayIndexed($args); + $mean = Averages::average($aArgs); + if (!is_numeric($mean)) { + return ExcelError::DIV0(); + } + $stdDev = StandardDeviations::STDEV($aArgs); + if ($stdDev === 0.0 || is_string($stdDev)) { + return ExcelError::DIV0(); + } + + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { + } elseif (!is_numeric($arg)) { + return ExcelError::VALUE(); + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += (($arg - $mean) / $stdDev) ** 3; + ++$count; + } + } + } + + if ($count > 2) { + return $summer * ($count / (($count - 1) * ($count - 2))); + } + + return ExcelError::DIV0(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php new file mode 100644 index 00000000..224872bf --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Beta.php @@ -0,0 +1,280 @@ +getMessage(); + } + + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { + return ExcelError::NAN(); + } + + $value -= $rMin; + $value /= ($rMax - $rMin); + + return self::incompleteBeta($value, $alpha, $beta); + } + + /** + * BETAINV. + * + * Returns the inverse of the Beta distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * Or can be an array of values + * @param mixed $alpha Parameter to the distribution as a float + * Or can be an array of values + * @param mixed $beta Parameter to the distribution as a float + * Or can be an array of values + * @param mixed $rMin Minimum value as a float + * Or can be an array of values + * @param mixed $rMax Maximum value as a float + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($probability, $alpha, $beta, $rMin = 0.0, $rMax = 1.0) + { + if (is_array($probability) || is_array($alpha) || is_array($beta) || is_array($rMin) || is_array($rMax)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta, $rMin, $rMax); + } + + $rMin = $rMin ?? 0.0; + $rMax = $rMax ?? 1.0; + + try { + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + $beta = DistributionValidations::validateFloat($beta); + $rMax = DistributionValidations::validateFloat($rMax); + $rMin = DistributionValidations::validateFloat($rMin); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0.0)) { + return ExcelError::NAN(); + } + + return self::calculateInverse($probability, $alpha, $beta, $rMin, $rMax); + } + + /** + * @return float|string + */ + private static function calculateInverse(float $probability, float $alpha, float $beta, float $rMin, float $rMax) + { + $a = 0; + $b = 2; + + $i = 0; + while ((($b - $a) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { + $guess = ($a + $b) / 2; + $result = self::distribution($guess, $alpha, $beta); + if (($result === $probability) || ($result === 0.0)) { + $b = $a; + } elseif ($result > $probability) { + $b = $guess; + } else { + $a = $guess; + } + } + + if ($i === self::MAX_ITERATIONS) { + return ExcelError::NA(); + } + + return round($rMin + $guess * ($rMax - $rMin), 12); + } + + /** + * Incomplete beta function. + * + * @author Jaco van Kooten + * @author Paul Meagher + * + * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). + * + * @param float $x require 0<=x<=1 + * @param float $p require p>0 + * @param float $q require q>0 + * + * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow + */ + public static function incompleteBeta(float $x, float $p, float $q): float + { + if ($x <= 0.0) { + return 0.0; + } elseif ($x >= 1.0) { + return 1.0; + } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { + return 0.0; + } + + $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); + if ($x < ($p + 1.0) / ($p + $q + 2.0)) { + return $beta_gam * self::betaFraction($x, $p, $q) / $p; + } + + return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); + } + + // Function cache for logBeta function + private static $logBetaCacheP = 0.0; + + private static $logBetaCacheQ = 0.0; + + private static $logBetaCacheResult = 0.0; + + /** + * The natural logarithm of the beta function. + * + * @param float $p require p>0 + * @param float $q require q>0 + * + * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + * + * @author Jaco van Kooten + */ + private static function logBeta(float $p, float $q): float + { + if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { + self::$logBetaCacheP = $p; + self::$logBetaCacheQ = $q; + if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) { + self::$logBetaCacheResult = 0.0; + } else { + self::$logBetaCacheResult = Gamma::logGamma($p) + Gamma::logGamma($q) - Gamma::logGamma($p + $q); + } + } + + return self::$logBetaCacheResult; + } + + /** + * Evaluates of continued fraction part of incomplete beta function. + * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). + * + * @author Jaco van Kooten + */ + private static function betaFraction(float $x, float $p, float $q): float + { + $c = 1.0; + $sum_pq = $p + $q; + $p_plus = $p + 1.0; + $p_minus = $p - 1.0; + $h = 1.0 - $sum_pq * $x / $p_plus; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $frac = $h; + $m = 1; + $delta = 0.0; + while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) { + $m2 = 2 * $m; + // even index for d + $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < self::XMININ) { + $c = self::XMININ; + } + $frac *= $h * $c; + // odd index for d + $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < self::XMININ) { + $h = self::XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < self::XMININ) { + $c = self::XMININ; + } + $delta = $h * $c; + $frac *= $delta; + ++$m; + } + + return $frac; + } + + private static function betaValue(float $a, float $b): float + { + return (Gamma::gammaValue($a) * Gamma::gammaValue($b)) / + Gamma::gammaValue($a + $b); + } + + private static function regularizedIncompleteBeta(float $value, float $a, float $b): float + { + return self::incompleteBeta($value, $a, $b) / self::betaValue($a, $b); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php new file mode 100644 index 00000000..02b53e88 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php @@ -0,0 +1,237 @@ +getMessage(); + } + + if (($value < 0) || ($value > $trials)) { + return ExcelError::NAN(); + } + + if ($cumulative) { + return self::calculateCumulativeBinomial($value, $trials, $probability); + } + /** @var float */ + $comb = Combinations::withoutRepetition($trials, $value); + + return $comb * $probability ** $value + * (1 - $probability) ** ($trials - $value); + } + + /** + * BINOM.DIST.RANGE. + * + * Returns returns the Binomial Distribution probability for the number of successes from a specified number + * of trials falling into a specified range. + * + * @param mixed $trials Integer number of trials + * Or can be an array of values + * @param mixed $probability Probability of success on each trial as a float + * Or can be an array of values + * @param mixed $successes The integer number of successes in trials + * Or can be an array of values + * @param mixed $limit Upper limit for successes in trials as null, or an integer + * If null, then this will indicate the same as the number of Successes + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function range($trials, $probability, $successes, $limit = null) + { + if (is_array($trials) || is_array($probability) || is_array($successes) || is_array($limit)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $successes, $limit); + } + + $limit = $limit ?? $successes; + + try { + $trials = DistributionValidations::validateInt($trials); + $probability = DistributionValidations::validateProbability($probability); + $successes = DistributionValidations::validateInt($successes); + $limit = DistributionValidations::validateInt($limit); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($successes < 0) || ($successes > $trials)) { + return ExcelError::NAN(); + } + if (($limit < 0) || ($limit > $trials) || $limit < $successes) { + return ExcelError::NAN(); + } + + $summer = 0; + for ($i = $successes; $i <= $limit; ++$i) { + /** @var float */ + $comb = Combinations::withoutRepetition($trials, $i); + $summer += $comb * $probability ** $i + * (1 - $probability) ** ($trials - $i); + } + + return $summer; + } + + /** + * NEGBINOMDIST. + * + * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that + * there will be number_f failures before the number_s-th success, when the constant + * probability of a success is probability_s. This function is similar to the binomial + * distribution, except that the number of successes is fixed, and the number of trials is + * variable. Like the binomial, trials are assumed to be independent. + * + * @param mixed $failures Number of Failures as an integer + * Or can be an array of values + * @param mixed $successes Threshold number of Successes as an integer + * Or can be an array of values + * @param mixed $probability Probability of success on each trial as a float + * Or can be an array of values + * + * @return array|float|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + * + * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST + * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST + */ + public static function negative($failures, $successes, $probability) + { + if (is_array($failures) || is_array($successes) || is_array($probability)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $failures, $successes, $probability); + } + + try { + $failures = DistributionValidations::validateInt($failures); + $successes = DistributionValidations::validateInt($successes); + $probability = DistributionValidations::validateProbability($probability); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($failures < 0) || ($successes < 1)) { + return ExcelError::NAN(); + } + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + if (($failures + $successes - 1) <= 0) { + return ExcelError::NAN(); + } + } + /** @var float */ + $comb = Combinations::withoutRepetition($failures + $successes - 1, $successes - 1); + + return $comb + * ($probability ** $successes) * ((1 - $probability) ** $failures); + } + + /** + * BINOM.INV. + * + * Returns the smallest value for which the cumulative binomial distribution is greater + * than or equal to a criterion value + * + * @param mixed $trials number of Bernoulli trials as an integer + * Or can be an array of values + * @param mixed $probability probability of a success on each trial as a float + * Or can be an array of values + * @param mixed $alpha criterion value as a float + * Or can be an array of values + * + * @return array|int|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($trials, $probability, $alpha) + { + if (is_array($trials) || is_array($probability) || is_array($alpha)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $alpha); + } + + try { + $trials = DistributionValidations::validateInt($trials); + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($trials < 0) { + return ExcelError::NAN(); + } elseif (($alpha < 0.0) || ($alpha > 1.0)) { + return ExcelError::NAN(); + } + + $successes = 0; + while ($successes <= $trials) { + $result = self::calculateCumulativeBinomial($successes, $trials, $probability); + if ($result >= $alpha) { + break; + } + ++$successes; + } + + return $successes; + } + + /** + * @return float|int + */ + private static function calculateCumulativeBinomial(int $value, int $trials, float $probability) + { + $summer = 0; + for ($i = 0; $i <= $value; ++$i) { + /** @var float */ + $comb = Combinations::withoutRepetition($trials, $i); + $summer += $comb * $probability ** $i + * (1 - $probability) ** ($trials - $i); + } + + return $summer; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php new file mode 100644 index 00000000..8574d58d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php @@ -0,0 +1,337 @@ +getMessage(); + } + + if ($degrees < 1) { + return ExcelError::NAN(); + } + if ($value < 0) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + + return ExcelError::NAN(); + } + + return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); + } + + /** + * CHIDIST. + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param mixed $value Float value for which we want the probability + * Or can be an array of values + * @param mixed $degrees Integer degrees of freedom + * Or can be an array of values + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function distributionLeftTail($value, $degrees, $cumulative) + { + if (is_array($value) || is_array($degrees) || is_array($cumulative)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $cumulative); + } + + try { + $value = DistributionValidations::validateFloat($value); + $degrees = DistributionValidations::validateInt($degrees); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return ExcelError::NAN(); + } + if ($value < 0) { + if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + + return ExcelError::NAN(); + } + + if ($cumulative === true) { + return 1 - self::distributionRightTail($value, $degrees); + } + + return (($value ** (($degrees / 2) - 1) * exp(-$value / 2))) / + ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); + } + + /** + * CHIINV. + * + * Returns the inverse of the right-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * Or can be an array of values + * @param mixed $degrees Integer degrees of freedom + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverseRightTail($probability, $degrees) + { + if (is_array($probability) || is_array($degrees)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return ExcelError::NAN(); + } + + $callback = function ($value) use ($degrees) { + return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) + / Gamma::gammaValue($degrees / 2)); + }; + + $newtonRaphson = new NewtonRaphson($callback); + + return $newtonRaphson->execute($probability); + } + + /** + * CHIINV. + * + * Returns the inverse of the left-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * Or can be an array of values + * @param mixed $degrees Integer degrees of freedom + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverseLeftTail($probability, $degrees) + { + if (is_array($probability) || is_array($degrees)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees < 1) { + return ExcelError::NAN(); + } + + return self::inverseLeftTailCalculation($probability, $degrees); + } + + /** + * CHITEST. + * + * Uses the chi-square test to calculate the probability that the differences between two supplied data sets + * (of observed and expected frequencies), are likely to be simply due to sampling error, + * or if they are likely to be real. + * + * @param mixed $actual an array of observed frequencies + * @param mixed $expected an array of expected frequencies + * + * @return float|string + */ + public static function test($actual, $expected) + { + $rows = count($actual); + $actual = Functions::flattenArray($actual); + $expected = Functions::flattenArray($expected); + $columns = count($actual) / $rows; + + $countActuals = count($actual); + $countExpected = count($expected); + if ($countActuals !== $countExpected || $countActuals === 1) { + return ExcelError::NAN(); + } + + $result = 0.0; + for ($i = 0; $i < $countActuals; ++$i) { + if ($expected[$i] == 0.0) { + return ExcelError::DIV0(); + } elseif ($expected[$i] < 0.0) { + return ExcelError::NAN(); + } + $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; + } + + $degrees = self::degrees($rows, $columns); + + $result = Functions::scalar(self::distributionRightTail($result, $degrees)); + + return $result; + } + + protected static function degrees(int $rows, int $columns): int + { + if ($rows === 1) { + return $columns - 1; + } elseif ($columns === 1) { + return $rows - 1; + } + + return ($columns - 1) * ($rows - 1); + } + + private static function inverseLeftTailCalculation(float $probability, int $degrees): float + { + // bracket the root + $min = 0; + $sd = sqrt(2.0 * $degrees); + $max = 2 * $sd; + $s = -1; + + while ($s * self::pchisq($max, $degrees) > $probability * $s) { + $min = $max; + $max += 2 * $sd; + } + + // Find root using bisection + $chi2 = 0.5 * ($min + $max); + + while (($max - $min) > self::EPS * $chi2) { + if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { + $min = $chi2; + } else { + $max = $chi2; + } + $chi2 = 0.5 * ($min + $max); + } + + return $chi2; + } + + private static function pchisq($chi2, $degrees) + { + return self::gammp($degrees, 0.5 * $chi2); + } + + private static function gammp($n, $x) + { + if ($x < 0.5 * $n + 1) { + return self::gser($n, $x); + } + + return 1 - self::gcf($n, $x); + } + + // Return the incomplete gamma function P(n/2,x) evaluated by + // series representation. Algorithm from numerical recipe. + // Assume that n is a positive integer and x>0, won't check arguments. + // Relative error controlled by the eps parameter + private static function gser($n, $x) + { + /** @var float */ + $gln = Gamma::ln($n / 2); + $a = 0.5 * $n; + $ap = $a; + $sum = 1.0 / $a; + $del = $sum; + for ($i = 1; $i < 101; ++$i) { + ++$ap; + $del = $del * $x / $ap; + $sum += $del; + if ($del < $sum * self::EPS) { + break; + } + } + + return $sum * exp(-$x + $a * log($x) - $gln); + } + + // Return the incomplete gamma function Q(n/2,x) evaluated by + // its continued fraction representation. Algorithm from numerical recipe. + // Assume that n is a postive integer and x>0, won't check arguments. + // Relative error controlled by the eps parameter + private static function gcf($n, $x) + { + /** @var float */ + $gln = Gamma::ln($n / 2); + $a = 0.5 * $n; + $b = $x + 1 - $a; + $fpmin = 1.e-300; + $c = 1 / $fpmin; + $d = 1 / $b; + $h = $d; + for ($i = 1; $i < 101; ++$i) { + $an = -$i * ($i - $a); + $b += 2; + $d = $an * $d + $b; + if (abs($d) < $fpmin) { + $d = $fpmin; + } + $c = $b + $an / $c; + if (abs($c) < $fpmin) { + $c = $fpmin; + } + $d = 1 / $d; + $del = $d * $c; + $h = $h * $del; + if (abs($del - 1) < self::EPS) { + break; + } + } + + return $h * exp(-$x + $a * log($x) - $gln); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php new file mode 100644 index 00000000..bd45a229 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/DistributionValidations.php @@ -0,0 +1,24 @@ + 1.0) { + throw new Exception(ExcelError::NAN()); + } + + return $probability; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php new file mode 100644 index 00000000..a03671cc --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php @@ -0,0 +1,55 @@ +getMessage(); + } + + if (($value < 0) || ($lambda < 0)) { + return ExcelError::NAN(); + } + + if ($cumulative === true) { + return 1 - exp(0 - $value * $lambda); + } + + return $lambda * exp(0 - $value * $lambda); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php new file mode 100644 index 00000000..ff413b6b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/F.php @@ -0,0 +1,64 @@ +getMessage(); + } + + if ($value < 0 || $u < 1 || $v < 1) { + return ExcelError::NAN(); + } + + if ($cumulative) { + $adjustedValue = ($u * $value) / ($u * $value + $v); + + return Beta::incompleteBeta($adjustedValue, $u / 2, $v / 2); + } + + return (Gamma::gammaValue(($v + $u) / 2) / + (Gamma::gammaValue($u / 2) * Gamma::gammaValue($v / 2))) * + (($u / $v) ** ($u / 2)) * + (($value ** (($u - 2) / 2)) / ((1 + ($u / $v) * $value) ** (($u + $v) / 2))); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php new file mode 100644 index 00000000..df9906ea --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php @@ -0,0 +1,74 @@ +getMessage(); + } + + if (($value <= -1) || ($value >= 1)) { + return ExcelError::NAN(); + } + + return 0.5 * log((1 + $value) / (1 - $value)); + } + + /** + * FISHERINV. + * + * Returns the inverse of the Fisher transformation. Use this transformation when + * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then + * FISHERINV(y) = x. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($probability) + { + if (is_array($probability)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $probability); + } + + try { + DistributionValidations::validateFloat($probability); + } catch (Exception $e) { + return $e->getMessage(); + } + + return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php new file mode 100644 index 00000000..216f234c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php @@ -0,0 +1,151 @@ +getMessage(); + } + + if ((((int) $value) == ((float) $value)) && $value <= 0.0) { + return ExcelError::NAN(); + } + + return self::gammaValue($value); + } + + /** + * GAMMADIST. + * + * Returns the gamma distribution. + * + * @param mixed $value Float Value at which you want to evaluate the distribution + * Or can be an array of values + * @param mixed $a Parameter to the distribution as a float + * Or can be an array of values + * @param mixed $b Parameter to the distribution as a float + * Or can be an array of values + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function distribution($value, $a, $b, $cumulative) + { + if (is_array($value) || is_array($a) || is_array($b) || is_array($cumulative)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $a, $b, $cumulative); + } + + try { + $value = DistributionValidations::validateFloat($value); + $a = DistributionValidations::validateFloat($a); + $b = DistributionValidations::validateFloat($b); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($value < 0) || ($a <= 0) || ($b <= 0)) { + return ExcelError::NAN(); + } + + return self::calculateDistribution($value, $a, $b, $cumulative); + } + + /** + * GAMMAINV. + * + * Returns the inverse of the Gamma distribution. + * + * @param mixed $probability Float probability at which you want to evaluate the distribution + * Or can be an array of values + * @param mixed $alpha Parameter to the distribution as a float + * Or can be an array of values + * @param mixed $beta Parameter to the distribution as a float + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($probability, $alpha, $beta) + { + if (is_array($probability) || is_array($alpha) || is_array($beta)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $alpha = DistributionValidations::validateFloat($alpha); + $beta = DistributionValidations::validateFloat($beta); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($alpha <= 0.0) || ($beta <= 0.0)) { + return ExcelError::NAN(); + } + + return self::calculateInverse($probability, $alpha, $beta); + } + + /** + * GAMMALN. + * + * Returns the natural logarithm of the gamma function. + * + * @param mixed $value Float Value at which you want to evaluate the distribution + * Or can be an array of values + * + * @return array|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function ln($value) + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + try { + $value = DistributionValidations::validateFloat($value); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($value <= 0) { + return ExcelError::NAN(); + } + + return log(self::gammaValue($value)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php new file mode 100644 index 00000000..404230ba --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php @@ -0,0 +1,382 @@ + Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::calculateDistribution($x, $alpha, $beta, true); + $error = $result - $probability; + + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + + $pdf = self::calculateDistribution($x, $alpha, $beta, false); + // Avoid division by zero + if ($pdf !== 0.0) { + $dx = $error / $pdf; + $xNew = $x - $dx; + } + + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + + if ($i === self::MAX_ITERATIONS) { + return ExcelError::NA(); + } + + return $x; + } + + // + // Implementation of the incomplete Gamma function + // + public static function incompleteGamma(float $a, float $x): float + { + static $max = 32; + $summer = 0; + for ($n = 0; $n <= $max; ++$n) { + $divisor = $a; + for ($i = 1; $i <= $n; ++$i) { + $divisor *= ($a + $i); + } + $summer += ($x ** $n / $divisor); + } + + return $x ** $a * exp(0 - $x) * $summer; + } + + // + // Implementation of the Gamma function + // + public static function gammaValue(float $value): float + { + if ($value == 0.0) { + return 0; + } + + static $p0 = 1.000000000190015; + static $p = [ + 1 => 76.18009172947146, + 2 => -86.50532032941677, + 3 => 24.01409824083091, + 4 => -1.231739572450155, + 5 => 1.208650973866179e-3, + 6 => -5.395239384953e-6, + ]; + + $y = $x = $value; + $tmp = $x + 5.5; + $tmp -= ($x + 0.5) * log($tmp); + + $summer = $p0; + for ($j = 1; $j <= 6; ++$j) { + $summer += ($p[$j] / ++$y); + } + + return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); + } + + /** + * logGamma function. + * + * @version 1.1 + * + * @author Jaco van Kooten + * + * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. + * + * The natural logarithm of the gamma function.
        + * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
        + * Applied Mathematics Division
        + * Argonne National Laboratory
        + * Argonne, IL 60439
        + *

        + * References: + *

          + *
        1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural + * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
        2. + *
        3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
        4. + *
        5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
        6. + *
        + *

        + *

        + * From the original documentation: + *

        + *

        + * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + *

        + *

        + * Error returns:
        + * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. + * The computation is believed to be free of underflow and overflow. + *

        + * + * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 + */ + + // Log Gamma related constants + private const LG_D1 = -0.5772156649015328605195174; + + private const LG_D2 = 0.4227843350984671393993777; + + private const LG_D4 = 1.791759469228055000094023; + + private const LG_P1 = [ + 4.945235359296727046734888, + 201.8112620856775083915565, + 2290.838373831346393026739, + 11319.67205903380828685045, + 28557.24635671635335736389, + 38484.96228443793359990269, + 26377.48787624195437963534, + 7225.813979700288197698961, + ]; + + private const LG_P2 = [ + 4.974607845568932035012064, + 542.4138599891070494101986, + 15506.93864978364947665077, + 184793.2904445632425417223, + 1088204.76946882876749847, + 3338152.967987029735917223, + 5106661.678927352456275255, + 3074109.054850539556250927, + ]; + + private const LG_P4 = [ + 14745.02166059939948905062, + 2426813.369486704502836312, + 121475557.4045093227939592, + 2663432449.630976949898078, + 29403789566.34553899906876, + 170266573776.5398868392998, + 492612579337.743088758812, + 560625185622.3951465078242, + ]; + + private const LG_Q1 = [ + 67.48212550303777196073036, + 1113.332393857199323513008, + 7738.757056935398733233834, + 27639.87074403340708898585, + 54993.10206226157329794414, + 61611.22180066002127833352, + 36351.27591501940507276287, + 8785.536302431013170870835, + ]; + + private const LG_Q2 = [ + 183.0328399370592604055942, + 7765.049321445005871323047, + 133190.3827966074194402448, + 1136705.821321969608938755, + 5267964.117437946917577538, + 13467014.54311101692290052, + 17827365.30353274213975932, + 9533095.591844353613395747, + ]; + + private const LG_Q4 = [ + 2690.530175870899333379843, + 639388.5654300092398984238, + 41355999.30241388052042842, + 1120872109.61614794137657, + 14886137286.78813811542398, + 101680358627.2438228077304, + 341747634550.7377132798597, + 446315818741.9713286462081, + ]; + + private const LG_C = [ + -0.001910444077728, + 8.4171387781295e-4, + -5.952379913043012e-4, + 7.93650793500350248e-4, + -0.002777777777777681622553, + 0.08333333333333333331554247, + 0.0057083835261, + ]; + + // Rough estimate of the fourth root of logGamma_xBig + private const LG_FRTBIG = 2.25e76; + + private const PNT68 = 0.6796875; + + // Function cache for logGamma + private static $logGammaCacheResult = 0.0; + + private static $logGammaCacheX = 0.0; + + public static function logGamma(float $x): float + { + if ($x == self::$logGammaCacheX) { + return self::$logGammaCacheResult; + } + + $y = $x; + if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { + if ($y <= self::EPS) { + $res = -log($y); + } elseif ($y <= 1.5) { + $res = self::logGamma1($y); + } elseif ($y <= 4.0) { + $res = self::logGamma2($y); + } elseif ($y <= 12.0) { + $res = self::logGamma3($y); + } else { + $res = self::logGamma4($y); + } + } else { + // -------------------------- + // Return for bad arguments + // -------------------------- + $res = self::MAX_VALUE; + } + + // ------------------------------ + // Final adjustments and return + // ------------------------------ + self::$logGammaCacheX = $x; + self::$logGammaCacheResult = $res; + + return $res; + } + + private static function logGamma1(float $y) + { + // --------------------- + // EPS .LT. X .LE. 1.5 + // --------------------- + if ($y < self::PNT68) { + $corr = -log($y); + $xm1 = $y; + } else { + $corr = 0.0; + $xm1 = $y - 1.0; + } + + $xden = 1.0; + $xnum = 0.0; + if ($y <= 0.5 || $y >= self::PNT68) { + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm1 + self::LG_P1[$i]; + $xden = $xden * $xm1 + self::LG_Q1[$i]; + } + + return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); + } + + $xm2 = $y - 1.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + self::LG_P2[$i]; + $xden = $xden * $xm2 + self::LG_Q2[$i]; + } + + return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); + } + + private static function logGamma2(float $y) + { + // --------------------- + // 1.5 .LT. X .LE. 4.0 + // --------------------- + $xm2 = $y - 2.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + self::LG_P2[$i]; + $xden = $xden * $xm2 + self::LG_Q2[$i]; + } + + return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); + } + + protected static function logGamma3(float $y) + { + // ---------------------- + // 4.0 .LT. X .LE. 12.0 + // ---------------------- + $xm4 = $y - 4.0; + $xden = -1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm4 + self::LG_P4[$i]; + $xden = $xden * $xm4 + self::LG_Q4[$i]; + } + + return self::LG_D4 + $xm4 * ($xnum / $xden); + } + + protected static function logGamma4(float $y) + { + // --------------------------------- + // Evaluate for argument .GE. 12.0 + // --------------------------------- + $res = 0.0; + if ($y <= self::LG_FRTBIG) { + $res = self::LG_C[6]; + $ysq = $y * $y; + for ($i = 0; $i < 6; ++$i) { + $res = $res / $ysq + self::LG_C[$i]; + } + $res /= $y; + $corr = log($y); + $res = $res + log(self::SQRT2PI) - 0.5 * $corr; + $res += $y * ($corr - 1.0); + } + + return $res; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php new file mode 100644 index 00000000..b3ad69d1 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php @@ -0,0 +1,76 @@ +getMessage(); + } + + if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { + return ExcelError::NAN(); + } + if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { + return ExcelError::NAN(); + } + if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { + return ExcelError::NAN(); + } + + $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); + $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); + $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( + $populationNumber - $populationSuccesses, + $sampleNumber - $sampleSuccesses + ); + + return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php new file mode 100644 index 00000000..d572d234 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/LogNormal.php @@ -0,0 +1,139 @@ +getMessage(); + } + + if (($value <= 0) || ($stdDev <= 0)) { + return ExcelError::NAN(); + } + + return StandardNormal::cumulative((log($value) - $mean) / $stdDev); + } + + /** + * LOGNORM.DIST. + * + * Returns the lognormal distribution of x, where ln(x) is normally distributed + * with parameters mean and standard_dev. + * + * @param mixed $value Float value for which we want the probability + * Or can be an array of values + * @param mixed $mean Mean value as a float + * Or can be an array of values + * @param mixed $stdDev Standard Deviation as a float + * Or can be an array of values + * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) + * Or can be an array of values + * + * @return array|float|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function distribution($value, $mean, $stdDev, $cumulative = false) + { + if (is_array($value) || is_array($mean) || is_array($stdDev) || is_array($cumulative)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev, $cumulative); + } + + try { + $value = DistributionValidations::validateFloat($value); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + $cumulative = DistributionValidations::validateBool($cumulative); + } catch (Exception $e) { + return $e->getMessage(); + } + + if (($value <= 0) || ($stdDev <= 0)) { + return ExcelError::NAN(); + } + + if ($cumulative === true) { + return StandardNormal::distribution((log($value) - $mean) / $stdDev, true); + } + + return (1 / (sqrt(2 * M_PI) * $stdDev * $value)) * + exp(0 - ((log($value) - $mean) ** 2 / (2 * $stdDev ** 2))); + } + + /** + * LOGINV. + * + * Returns the inverse of the lognormal cumulative distribution + * + * @param mixed $probability Float probability for which we want the value + * Or can be an array of values + * @param mixed $mean Mean Value as a float + * Or can be an array of values + * @param mixed $stdDev Standard Deviation as a float + * Or can be an array of values + * + * @return array|float|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + * + * @TODO Try implementing P J Acklam's refinement algorithm for greater + * accuracy if I can get my head round the mathematics + * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ + */ + public static function inverse($probability, $mean, $stdDev) + { + if (is_array($probability) || is_array($mean) || is_array($stdDev)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($stdDev <= 0) { + return ExcelError::NAN(); + } + /** @var float */ + $inverse = StandardNormal::inverse($probability); + + return exp($mean + $stdDev * $inverse); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php new file mode 100644 index 00000000..b994864e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/NewtonRaphson.php @@ -0,0 +1,63 @@ +callback = $callback; + } + + public function execute(float $probability) + { + $xLo = 100; + $xHi = 0; + + $dx = 1; + $x = $xNew = 1; + $i = 0; + + while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = call_user_func($this->callback, $x); + $error = $result - $probability; + + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + + if ($i == self::MAX_ITERATIONS) { + return ExcelError::NA(); + } + + return $x; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php new file mode 100644 index 00000000..67533c49 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Normal.php @@ -0,0 +1,180 @@ +getMessage(); + } + + if ($stdDev < 0) { + return ExcelError::NAN(); + } + + if ($cumulative) { + return 0.5 * (1 + Engineering\Erf::erfValue(($value - $mean) / ($stdDev * sqrt(2)))); + } + + return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (($value - $mean) ** 2 / (2 * ($stdDev * $stdDev)))); + } + + /** + * NORMINV. + * + * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. + * + * @param mixed $probability Float probability for which we want the value + * Or can be an array of values + * @param mixed $mean Mean Value as a float + * Or can be an array of values + * @param mixed $stdDev Standard Deviation as a float + * Or can be an array of values + * + * @return array|float|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($probability, $mean, $stdDev) + { + if (is_array($probability) || is_array($mean) || is_array($stdDev)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $mean, $stdDev); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $mean = DistributionValidations::validateFloat($mean); + $stdDev = DistributionValidations::validateFloat($stdDev); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($stdDev < 0) { + return ExcelError::NAN(); + } + + return (self::inverseNcdf($probability) * $stdDev) + $mean; + } + + /* + * inverse_ncdf.php + * ------------------- + * begin : Friday, January 16, 2004 + * copyright : (C) 2004 Michael Nickerson + * email : nickersonm@yahoo.com + * + */ + private static function inverseNcdf($p) + { + // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to + // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as + // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html + // I have not checked the accuracy of this implementation. Be aware that PHP + // will truncate the coeficcients to 14 digits. + + // You have permission to use and distribute this function freely for + // whatever purpose you want, but please show common courtesy and give credit + // where credit is due. + + // Input paramater is $p - probability - where 0 < p < 1. + + // Coefficients in rational approximations + static $a = [ + 1 => -3.969683028665376e+01, + 2 => 2.209460984245205e+02, + 3 => -2.759285104469687e+02, + 4 => 1.383577518672690e+02, + 5 => -3.066479806614716e+01, + 6 => 2.506628277459239e+00, + ]; + + static $b = [ + 1 => -5.447609879822406e+01, + 2 => 1.615858368580409e+02, + 3 => -1.556989798598866e+02, + 4 => 6.680131188771972e+01, + 5 => -1.328068155288572e+01, + ]; + + static $c = [ + 1 => -7.784894002430293e-03, + 2 => -3.223964580411365e-01, + 3 => -2.400758277161838e+00, + 4 => -2.549732539343734e+00, + 5 => 4.374664141464968e+00, + 6 => 2.938163982698783e+00, + ]; + + static $d = [ + 1 => 7.784695709041462e-03, + 2 => 3.224671290700398e-01, + 3 => 2.445134137142996e+00, + 4 => 3.754408661907416e+00, + ]; + + // Define lower and upper region break-points. + $p_low = 0.02425; //Use lower region approx. below this + $p_high = 1 - $p_low; //Use upper region approx. above this + + if (0 < $p && $p < $p_low) { + // Rational approximation for lower region. + $q = sqrt(-2 * log($p)); + + return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } elseif ($p_high < $p && $p < 1) { + // Rational approximation for upper region. + $q = sqrt(-2 * log(1 - $p)); + + return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } + + // Rational approximation for central region. + $q = $p - 0.5; + $r = $q * $q; + + return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / + ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php new file mode 100644 index 00000000..041c34a0 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php @@ -0,0 +1,66 @@ +getMessage(); + } + + if (($value < 0) || ($mean < 0)) { + return ExcelError::NAN(); + } + + if ($cumulative) { + $summer = 0; + $floor = floor($value); + for ($i = 0; $i <= $floor; ++$i) { + /** @var float */ + $fact = MathTrig\Factorial::fact($i); + $summer += $mean ** $i / $fact; + } + + return exp(0 - $mean) * $summer; + } + /** @var float */ + $fact = MathTrig\Factorial::fact($value); + + return (exp(0 - $mean) * $mean ** $value) / $fact; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php new file mode 100644 index 00000000..a655fa74 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php @@ -0,0 +1,151 @@ +getMessage(); + } + + if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { + return ExcelError::NAN(); + } + + return self::calculateDistribution($value, $degrees, $tails); + } + + /** + * TINV. + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param mixed $probability Float probability for the function + * Or can be an array of values + * @param mixed $degrees Integer value for degrees of freedom + * Or can be an array of values + * + * @return array|float|string The result, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function inverse($probability, $degrees) + { + if (is_array($probability) || is_array($degrees)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); + } + + try { + $probability = DistributionValidations::validateProbability($probability); + $degrees = DistributionValidations::validateInt($degrees); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($degrees <= 0) { + return ExcelError::NAN(); + } + + $callback = function ($value) use ($degrees) { + return self::distribution($value, $degrees, 2); + }; + + $newtonRaphson = new NewtonRaphson($callback); + + return $newtonRaphson->execute($probability); + } + + /** + * @return float + */ + private static function calculateDistribution(float $value, int $degrees, int $tails) + { + // tdist, which finds the probability that corresponds to a given value + // of t with k degrees of freedom. This algorithm is translated from a + // pascal function on p81 of "Statistical Computing in Pascal" by D + // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: + // London). The above Pascal algorithm is itself a translation of the + // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer + // Laboratory as reported in (among other places) "Applied Statistics + // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis + // Horwood Ltd.; W. Sussex, England). + $tterm = $degrees; + $ttheta = atan2($value, sqrt($tterm)); + $tc = cos($ttheta); + $ts = sin($ttheta); + + if (($degrees % 2) === 1) { + $ti = 3; + $tterm = $tc; + } else { + $ti = 2; + $tterm = 1; + } + + $tsum = $tterm; + while ($ti < $degrees) { + $tterm *= $tc * $tc * ($ti - 1) / $ti; + $tsum += $tterm; + $ti += 2; + } + + $tsum *= $ts; + if (($degrees % 2) == 1) { + $tsum = Functions::M_2DIVPI * ($tsum + $ttheta); + } + + $tValue = 0.5 * (1 + $tsum); + if ($tails == 1) { + return 1 - abs($tValue); + } + + return 1 - abs((1 - $tValue) - $tValue); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php new file mode 100644 index 00000000..51392c41 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php @@ -0,0 +1,57 @@ +getMessage(); + } + + if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { + return ExcelError::NAN(); + } + + if ($cumulative) { + return 1 - exp(0 - ($value / $beta) ** $alpha); + } + + return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php new file mode 100644 index 00000000..bd17b062 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php @@ -0,0 +1,17 @@ + $returnValue)) { + $returnValue = $arg; + } + } + } + + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } + + /** + * MAXA. + * + * Returns the greatest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MAXA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float + */ + public static function maxA(...$args) + { + $returnValue = null; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + if (($returnValue === null) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + if ($returnValue === null) { + return 0; + } + + return $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php new file mode 100644 index 00000000..596aad78 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php @@ -0,0 +1,78 @@ +getMessage(); + } + + if (($entry < 0) || ($entry > 1)) { + return ExcelError::NAN(); + } + + $mArgs = self::percentileFilterValues($aArgs); + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs); + $count = Counts::COUNT($mArgs); + $index = $entry * ($count - 1); + $iBase = floor($index); + if ($index == $iBase) { + return $mArgs[$index]; + } + $iNext = $iBase + 1; + $iProportion = $index - $iBase; + + return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); + } + + return ExcelError::NAN(); + } + + /** + * PERCENTRANK. + * + * Returns the rank of a value in a data set as a percentage of the data set. + * Note that the returned rank is simply rounded to the appropriate significant digits, + * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return + * 0.667 rather than 0.666 + * + * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers + * @param mixed $value The number whose rank you want to find + * @param mixed $significance The (integer) number of significant digits for the returned percentage value + * + * @return float|string (string if result is an error) + */ + public static function PERCENTRANK($valueSet, $value, $significance = 3) + { + $valueSet = Functions::flattenArray($valueSet); + $value = Functions::flattenSingleValue($value); + $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); + + try { + $value = StatisticalValidations::validateFloat($value); + $significance = StatisticalValidations::validateInt($significance); + } catch (Exception $e) { + return $e->getMessage(); + } + + $valueSet = self::rankFilterValues($valueSet); + $valueCount = count($valueSet); + if ($valueCount == 0) { + return ExcelError::NA(); + } + sort($valueSet, SORT_NUMERIC); + + $valueAdjustor = $valueCount - 1; + if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { + return ExcelError::NA(); + } + + $pos = array_search($value, $valueSet); + if ($pos === false) { + $pos = 0; + $testValue = $valueSet[0]; + while ($testValue < $value) { + $testValue = $valueSet[++$pos]; + } + --$pos; + $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); + } + + return round($pos / $valueAdjustor, $significance); + } + + /** + * QUARTILE. + * + * Returns the quartile of a data set. + * + * Excel Function: + * QUARTILE(value1[,value2[, ...]],entry) + * + * @param mixed $args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function QUARTILE(...$args) + { + $aArgs = Functions::flattenArray($args); + $entry = array_pop($aArgs); + + try { + $entry = StatisticalValidations::validateFloat($entry); + } catch (Exception $e) { + return $e->getMessage(); + } + + $entry = floor($entry); + $entry /= 4; + if (($entry < 0) || ($entry > 1)) { + return ExcelError::NAN(); + } + + return self::PERCENTILE($aArgs, $entry); + } + + /** + * RANK. + * + * Returns the rank of a number in a list of numbers. + * + * @param mixed $value The number whose rank you want to find + * @param mixed $valueSet An array of float values, or a reference to, a list of numbers + * @param mixed $order Order to sort the values in the value set + * + * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) + */ + public static function RANK($value, $valueSet, $order = self::RANK_SORT_DESCENDING) + { + $value = Functions::flattenSingleValue($value); + $valueSet = Functions::flattenArray($valueSet); + $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); + + try { + $value = StatisticalValidations::validateFloat($value); + $order = StatisticalValidations::validateInt($order); + } catch (Exception $e) { + return $e->getMessage(); + } + + $valueSet = self::rankFilterValues($valueSet); + if ($order === self::RANK_SORT_DESCENDING) { + rsort($valueSet, SORT_NUMERIC); + } else { + sort($valueSet, SORT_NUMERIC); + } + + $pos = array_search($value, $valueSet); + if ($pos === false) { + return ExcelError::NA(); + } + + return ++$pos; + } + + protected static function percentileFilterValues(array $dataSet) + { + return array_filter( + $dataSet, + function ($value): bool { + return is_numeric($value) && !is_string($value); + } + ); + } + + protected static function rankFilterValues(array $dataSet) + { + return array_filter( + $dataSet, + function ($value): bool { + return is_numeric($value); + } + ); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php new file mode 100644 index 00000000..5d9d3048 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php @@ -0,0 +1,90 @@ +getMessage(); + } + + if ($numObjs < $numInSet) { + return ExcelError::NAN(); + } + $result = round(MathTrig\Factorial::fact($numObjs) / MathTrig\Factorial::fact($numObjs - $numInSet)); + + return IntOrFloat::evaluate($result); + } + + /** + * PERMUTATIONA. + * + * Returns the number of permutations for a given number of objects (with repetitions) + * that can be selected from the total objects. + * + * @param mixed $numObjs Integer number of different objects + * Or can be an array of values + * @param mixed $numInSet Integer number of objects in each permutation + * Or can be an array of values + * + * @return array|float|int|string Number of permutations, or a string containing an error + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function PERMUTATIONA($numObjs, $numInSet) + { + if (is_array($numObjs) || is_array($numInSet)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); + } + + try { + $numObjs = StatisticalValidations::validateInt($numObjs); + $numInSet = StatisticalValidations::validateInt($numInSet); + } catch (Exception $e) { + return $e->getMessage(); + } + + if ($numObjs < 0 || $numInSet < 0) { + return ExcelError::NAN(); + } + + $result = $numObjs ** $numInSet; + + return IntOrFloat::evaluate($result); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php new file mode 100644 index 00000000..2eef5fc7 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/Size.php @@ -0,0 +1,97 @@ += $count) { + return ExcelError::NAN(); + } + rsort($mArgs); + + return $mArgs[$entry]; + } + + return ExcelError::VALUE(); + } + + /** + * SMALL. + * + * Returns the nth smallest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * SMALL(value1[,value2[, ...]],entry) + * + * @param mixed $args Data values + * + * @return float|string The result, or a string containing an error + */ + public static function small(...$args) + { + $aArgs = Functions::flattenArray($args); + + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $entry = (int) floor($entry); + + $mArgs = self::filter($aArgs); + $count = Counts::COUNT($mArgs); + --$entry; + if ($count === 0 || $entry < 0 || $entry >= $count) { + return ExcelError::NAN(); + } + sort($mArgs); + + return $mArgs[$entry]; + } + + return ExcelError::VALUE(); + } + + /** + * @param mixed[] $args Data values + */ + protected static function filter(array $args): array + { + $mArgs = []; + + foreach ($args as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + return $mArgs; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php new file mode 100644 index 00000000..af271205 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php @@ -0,0 +1,95 @@ +getMessage(); + } + + if ($stdDev <= 0) { + return ExcelError::NAN(); + } + + return ($value - $mean) / $stdDev; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php new file mode 100644 index 00000000..e23a52cc --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php @@ -0,0 +1,45 @@ + $value) { + if ((is_bool($value)) || (is_string($value)) || ($value === null)) { + unset($array1[$key], $array2[$key]); + } + } + } + + private static function checkTrendArrays(&$array1, &$array2): void + { + if (!is_array($array1)) { + $array1 = [$array1]; + } + if (!is_array($array2)) { + $array2 = [$array2]; + } + + $array1 = Functions::flattenArray($array1); + $array2 = Functions::flattenArray($array2); + + self::filterTrendValues($array1, $array2); + self::filterTrendValues($array2, $array1); + + // Reset the array indexes + $array1 = array_merge($array1); + $array2 = array_merge($array2); + } + + protected static function validateTrendArrays(array $yValues, array $xValues): void + { + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { + throw new Exception(ExcelError::NA()); + } elseif ($yValueCount === 1) { + throw new Exception(ExcelError::DIV0()); + } + } + + /** + * CORREL. + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param mixed $yValues array of mixed Data Series Y + * @param null|mixed $xValues array of mixed Data Series X + * + * @return float|string + */ + public static function CORREL($yValues, $xValues = null) + { + if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { + return ExcelError::VALUE(); + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getCorrelation(); + } + + /** + * COVAR. + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param mixed $yValues array of mixed Data Series Y + * @param mixed $xValues array of mixed Data Series X + * + * @return float|string + */ + public static function COVAR($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getCovariance(); + } + + /** + * FORECAST. + * + * Calculates, or predicts, a future value by using existing values. + * The predicted value is a y-value for a given x-value. + * + * @param mixed $xValue Float value of X for which we want to find Y + * Or can be an array of values + * @param mixed $yValues array of mixed Data Series Y + * @param mixed $xValues of mixed Data Series X + * + * @return array|bool|float|string + * If an array of numbers is passed as an argument, then the returned result will also be an array + * with the same dimensions + */ + public static function FORECAST($xValue, $yValues, $xValues) + { + if (is_array($xValue)) { + return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $xValue, $yValues, $xValues); + } + + try { + $xValue = StatisticalValidations::validateFloat($xValue); + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getValueOfYForX($xValue); + } + + /** + * GROWTH. + * + * Returns values along a predicted exponential Trend + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * @param mixed[] $newValues Values of X for which we want to find Y + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * + * @return float[] + */ + public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true) + { + $yValues = Functions::flattenArray($yValues); + $xValues = Functions::flattenArray($xValues); + $newValues = Functions::flattenArray($newValues); + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + + $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitExponential->getXValues(); + } + + $returnArray = []; + foreach ($newValues as $xValue) { + $returnArray[0][] = [$bestFitExponential->getValueOfYForX($xValue)]; + } + + return $returnArray; + } + + /** + * INTERCEPT. + * + * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string + */ + public static function INTERCEPT($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getIntersect(); + } + + /** + * LINEST. + * + * Calculates the statistics for a line by using the "least squares" method to calculate a straight line + * that best fits your data, and then returns an array that describes the line. + * + * @param mixed[] $yValues Data Series Y + * @param null|mixed[] $xValues Data Series X + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics + * + * @return array|int|string The result, or a string containing an error + */ + public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); + if ($xValues === null) { + $xValues = $yValues; + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); + + if ($stats === true) { + return [ + [ + $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect(), + ], + [ + $bestFitLinear->getSlopeSE(), + ($const === false) ? ExcelError::NA() : $bestFitLinear->getIntersectSE(), + ], + [ + $bestFitLinear->getGoodnessOfFit(), + $bestFitLinear->getStdevOfResiduals(), + ], + [ + $bestFitLinear->getF(), + $bestFitLinear->getDFResiduals(), + ], + [ + $bestFitLinear->getSSRegression(), + $bestFitLinear->getSSResiduals(), + ], + ]; + } + + return [ + $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect(), + ]; + } + + /** + * LOGEST. + * + * Calculates an exponential curve that best fits the X and Y data series, + * and then returns an array that describes the line. + * + * @param mixed[] $yValues Data Series Y + * @param null|mixed[] $xValues Data Series X + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics + * + * @return array|int|string The result, or a string containing an error + */ + public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); + if ($xValues === null) { + $xValues = $yValues; + } + + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + foreach ($yValues as $value) { + if ($value < 0.0) { + return ExcelError::NAN(); + } + } + + $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); + + if ($stats === true) { + return [ + [ + $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect(), + ], + [ + $bestFitExponential->getSlopeSE(), + ($const === false) ? ExcelError::NA() : $bestFitExponential->getIntersectSE(), + ], + [ + $bestFitExponential->getGoodnessOfFit(), + $bestFitExponential->getStdevOfResiduals(), + ], + [ + $bestFitExponential->getF(), + $bestFitExponential->getDFResiduals(), + ], + [ + $bestFitExponential->getSSRegression(), + $bestFitExponential->getSSResiduals(), + ], + ]; + } + + return [ + $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect(), + ]; + } + + /** + * RSQ. + * + * Returns the square of the Pearson product moment correlation coefficient through data points + * in known_y's and known_x's. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string The result, or a string containing an error + */ + public static function RSQ($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getGoodnessOfFit(); + } + + /** + * SLOPE. + * + * Returns the slope of the linear regression line through data points in known_y's and known_x's. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string The result, or a string containing an error + */ + public static function SLOPE($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getSlope(); + } + + /** + * STEYX. + * + * Returns the standard error of the predicted y-value for each x in the regression. + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * + * @return float|string + */ + public static function STEYX($yValues, $xValues) + { + try { + self::checkTrendArrays($yValues, $xValues); + self::validateTrendArrays($yValues, $xValues); + } catch (Exception $e) { + return $e->getMessage(); + } + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); + + return $bestFitLinear->getStdevOfResiduals(); + } + + /** + * TREND. + * + * Returns values along a linear Trend + * + * @param mixed[] $yValues Data Series Y + * @param mixed[] $xValues Data Series X + * @param mixed[] $newValues Values of X for which we want to find Y + * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not + * + * @return float[] + */ + public static function TREND($yValues, $xValues = [], $newValues = [], $const = true) + { + $yValues = Functions::flattenArray($yValues); + $xValues = Functions::flattenArray($xValues); + $newValues = Functions::flattenArray($newValues); + $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); + + $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitLinear->getXValues(); + } + + $returnArray = []; + foreach ($newValues as $xValue) { + $returnArray[0][] = [$bestFitLinear->getValueOfYForX($xValue)]; + } + + return $returnArray; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php new file mode 100644 index 00000000..e5334671 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php @@ -0,0 +1,28 @@ + 1) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + + return $returnValue; + } + + /** + * VARA. + * + * Estimates variance based on a sample, including numbers, text, and logical values + * + * Excel Function: + * VARA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARA(...$args) + { + $returnValue = ExcelError::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && (Functions::isValue($k))) { + return ExcelError::VALUE(); + } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + + return $returnValue; + } + + /** + * VARP. + * + * Calculates variance based on the entire population + * + * Excel Function: + * VARP(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARP(...$args) + { + // Return value + $returnValue = ExcelError::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArray($args); + $aCount = 0; + foreach ($aArgs as $arg) { + $arg = self::datatypeAdjustmentBooleans($arg); + + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * $aCount); + } + + return $returnValue; + } + + /** + * VARPA. + * + * Calculates variance based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * VARPA(value1[,value2[, ...]]) + * + * @param mixed ...$args Data values + * + * @return float|string (string if result is an error) + */ + public static function VARPA(...$args) + { + $returnValue = ExcelError::DIV0(); + + $summerA = $summerB = 0.0; + + // Loop through arguments + $aArgs = Functions::flattenArrayIndexed($args); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && (Functions::isValue($k))) { + return ExcelError::VALUE(); + } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + $arg = self::datatypeAdjustmentAllowStrings($arg); + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + + return ($summerA - $summerB) / ($aCount * $aCount); + } + + return $returnValue; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php index bbb03926..6757a8d8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData.php @@ -2,141 +2,89 @@ namespace PhpOffice\PhpSpreadsheet\Calculation; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; -use PhpOffice\PhpSpreadsheet\Style\NumberFormat; +use DateTimeInterface; +/** + * @deprecated 1.18.0 + */ class TextData { - private static $invalidChars; - - private static function unicodeToOrd($character) - { - return unpack('V', iconv('UTF-8', 'UCS-4LE', $character))[1]; - } - /** * CHARACTER. * + * @Deprecated 1.18.0 + * + * @see Use the character() method in the TextData\CharacterConvert class instead + * * @param string $character Value * - * @return string + * @return array|string */ public static function CHARACTER($character) { - $character = Functions::flattenSingleValue($character); - - if ((!is_numeric($character)) || ($character < 0)) { - return Functions::VALUE(); - } - - if (function_exists('iconv')) { - return iconv('UCS-4LE', 'UTF-8', pack('V', $character)); - } - - return mb_convert_encoding('&#' . (int) $character . ';', 'UTF-8', 'HTML-ENTITIES'); + return TextData\CharacterConvert::character($character); } /** * TRIMNONPRINTABLE. * + * @Deprecated 1.18.0 + * + * @see Use the nonPrintable() method in the TextData\Trim class instead + * * @param mixed $stringValue Value to check * - * @return string + * @return null|array|string */ public static function TRIMNONPRINTABLE($stringValue = '') { - $stringValue = Functions::flattenSingleValue($stringValue); - - if (is_bool($stringValue)) { - return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (self::$invalidChars === null) { - self::$invalidChars = range(chr(0), chr(31)); - } - - if (is_string($stringValue) || is_numeric($stringValue)) { - return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F")); - } - - return null; + return TextData\Trim::nonPrintable($stringValue); } /** * TRIMSPACES. * + * @Deprecated 1.18.0 + * + * @see Use the spaces() method in the TextData\Trim class instead + * * @param mixed $stringValue Value to check * - * @return string + * @return array|string */ public static function TRIMSPACES($stringValue = '') { - $stringValue = Functions::flattenSingleValue($stringValue); - if (is_bool($stringValue)) { - return ($stringValue) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (is_string($stringValue) || is_numeric($stringValue)) { - return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' '); - } - - return null; - } - - private static function convertBooleanValue($value) - { - if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE) { - return (int) $value; - } - - return ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); + return TextData\Trim::spaces($stringValue); } /** * ASCIICODE. * - * @param string $characters Value + * @Deprecated 1.18.0 * - * @return int + * @see Use the code() method in the TextData\CharacterConvert class instead + * + * @param array|string $characters Value + * + * @return array|int|string A string if arguments are invalid */ public static function ASCIICODE($characters) { - if (($characters === null) || ($characters === '')) { - return Functions::VALUE(); - } - $characters = Functions::flattenSingleValue($characters); - if (is_bool($characters)) { - $characters = self::convertBooleanValue($characters); - } - - $character = $characters; - if (mb_strlen($characters, 'UTF-8') > 1) { - $character = mb_substr($characters, 0, 1, 'UTF-8'); - } - - return self::unicodeToOrd($character); + return TextData\CharacterConvert::code($characters); } /** * CONCATENATE. * + * @Deprecated 1.18.0 + * + * @see Use the CONCATENATE() method in the TextData\Concatenate class instead + * * @return string */ public static function CONCATENATE(...$args) { - $returnValue = ''; - - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $arg) { - if (is_bool($arg)) { - $arg = self::convertBooleanValue($arg); - } - $returnValue .= $arg; - } - - return $returnValue; + return TextData\Concatenate::CONCATENATE(...$args); } /** @@ -145,259 +93,160 @@ public static function CONCATENATE(...$args) * This function converts a number to text using currency format, with the decimals rounded to the specified place. * The format used is $#,##0.00_);($#,##0.00).. * + * @Deprecated 1.18.0 + * + * @see Use the DOLLAR() method in the TextData\Format class instead + * * @param float $value The value to format * @param int $decimals The number of digits to display to the right of the decimal point. * If decimals is negative, number is rounded to the left of the decimal point. * If you omit decimals, it is assumed to be 2 * - * @return string + * @return array|string */ public static function DOLLAR($value = 0, $decimals = 2) { - $value = Functions::flattenSingleValue($value); - $decimals = $decimals === null ? 0 : Functions::flattenSingleValue($decimals); - - // Validate parameters - if (!is_numeric($value) || !is_numeric($decimals)) { - return Functions::NAN(); - } - $decimals = floor($decimals); - - $mask = '$#,##0'; - if ($decimals > 0) { - $mask .= '.' . str_repeat('0', $decimals); - } else { - $round = pow(10, abs($decimals)); - if ($value < 0) { - $round = 0 - $round; - } - $value = MathTrig::MROUND($value, $round); - } - - return NumberFormat::toFormattedString($value, $mask); + return TextData\Format::DOLLAR($value, $decimals); } /** - * SEARCHSENSITIVE. + * FIND. * - * @param string $needle The string to look for - * @param string $haystack The string in which to look - * @param int $offset Offset within $haystack + * @Deprecated 1.18.0 * - * @return string + * @see Use the sensitive() method in the TextData\Search class instead + * + * @param array|string $needle The string to look for + * @param array|string $haystack The string in which to look + * @param array|int $offset Offset within $haystack + * + * @return array|int|string */ public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); - $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); - - if (!is_bool($needle)) { - if (is_bool($haystack)) { - $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) { - if (StringHelper::countCharacters($needle) === 0) { - return $offset; - } - - $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); - if ($pos !== false) { - return ++$pos; - } - } - } - - return Functions::VALUE(); + return TextData\Search::sensitive($needle, $haystack, $offset); } /** - * SEARCHINSENSITIVE. + * SEARCH. * - * @param string $needle The string to look for - * @param string $haystack The string in which to look - * @param int $offset Offset within $haystack + * @Deprecated 1.18.0 * - * @return string + * @see Use the insensitive() method in the TextData\Search class instead + * + * @param array|string $needle The string to look for + * @param array|string $haystack The string in which to look + * @param array|int $offset Offset within $haystack + * + * @return array|int|string */ public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) { - $needle = Functions::flattenSingleValue($needle); - $haystack = Functions::flattenSingleValue($haystack); - $offset = Functions::flattenSingleValue($offset); - - if (!is_bool($needle)) { - if (is_bool($haystack)) { - $haystack = ($haystack) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (($offset > 0) && (StringHelper::countCharacters($haystack) > $offset)) { - if (StringHelper::countCharacters($needle) === 0) { - return $offset; - } - - $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); - if ($pos !== false) { - return ++$pos; - } - } - } - - return Functions::VALUE(); + return TextData\Search::insensitive($needle, $haystack, $offset); } /** * FIXEDFORMAT. * + * @Deprecated 1.18.0 + * + * @see Use the FIXEDFORMAT() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param int $decimals * @param bool $no_commas * - * @return string + * @return array|string */ public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) { - $value = Functions::flattenSingleValue($value); - $decimals = Functions::flattenSingleValue($decimals); - $no_commas = Functions::flattenSingleValue($no_commas); - - // Validate parameters - if (!is_numeric($value) || !is_numeric($decimals)) { - return Functions::NAN(); - } - $decimals = (int) floor($decimals); - - $valueResult = round($value, $decimals); - if ($decimals < 0) { - $decimals = 0; - } - if (!$no_commas) { - $valueResult = number_format( - $valueResult, - $decimals, - StringHelper::getDecimalSeparator(), - StringHelper::getThousandsSeparator() - ); - } - - return (string) $valueResult; + return TextData\Format::FIXEDFORMAT($value, $decimals, $no_commas); } /** * LEFT. * - * @param string $value Value - * @param int $chars Number of characters + * @Deprecated 1.18.0 * - * @return string + * @see Use the left() method in the TextData\Extract class instead + * + * @param array|string $value Value + * @param array|int $chars Number of characters + * + * @return array|string */ public static function LEFT($value = '', $chars = 1) { - $value = Functions::flattenSingleValue($value); - $chars = Functions::flattenSingleValue($chars); - - if ($chars < 0) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_substr($value, 0, $chars, 'UTF-8'); + return TextData\Extract::left($value, $chars); } /** * MID. * - * @param string $value Value - * @param int $start Start character - * @param int $chars Number of characters + * @Deprecated 1.18.0 * - * @return string + * @see Use the mid() method in the TextData\Extract class instead + * + * @param array|string $value Value + * @param array|int $start Start character + * @param array|int $chars Number of characters + * + * @return array|string */ public static function MID($value = '', $start = 1, $chars = null) { - $value = Functions::flattenSingleValue($value); - $start = Functions::flattenSingleValue($start); - $chars = Functions::flattenSingleValue($chars); - - if (($start < 1) || ($chars < 0)) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - if (empty($chars)) { - return ''; - } - - return mb_substr($value, --$start, $chars, 'UTF-8'); + return TextData\Extract::mid($value, $start, $chars); } /** * RIGHT. * - * @param string $value Value - * @param int $chars Number of characters + * @Deprecated 1.18.0 * - * @return string + * @see Use the right() method in the TextData\Extract class instead + * + * @param array|string $value Value + * @param array|int $chars Number of characters + * + * @return array|string */ public static function RIGHT($value = '', $chars = 1) { - $value = Functions::flattenSingleValue($value); - $chars = Functions::flattenSingleValue($chars); - - if ($chars < 0) { - return Functions::VALUE(); - } - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); + return TextData\Extract::right($value, $chars); } /** * STRINGLENGTH. * + * @Deprecated 1.18.0 + * + * @see Use the length() method in the TextData\Text class instead + * * @param string $value Value * - * @return int + * @return array|int */ public static function STRINGLENGTH($value = '') { - $value = Functions::flattenSingleValue($value); - - if (is_bool($value)) { - $value = ($value) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return mb_strlen($value, 'UTF-8'); + return TextData\Text::length($value); } /** * LOWERCASE. * - * Converts a string value to upper case. + * Converts a string value to lower case. * - * @param string $mixedCaseString + * @Deprecated 1.18.0 * - * @return string + * @see Use the lower() method in the TextData\CaseConvert class instead + * + * @param array|string $mixedCaseString + * + * @return array|string */ public static function LOWERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToLower($mixedCaseString); + return TextData\CaseConvert::lower($mixedCaseString); } /** @@ -405,229 +254,140 @@ public static function LOWERCASE($mixedCaseString) * * Converts a string value to upper case. * + * @Deprecated 1.18.0 + * + * @see Use the upper() method in the TextData\CaseConvert class instead + * * @param string $mixedCaseString * - * @return string + * @return array|string */ public static function UPPERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToUpper($mixedCaseString); + return TextData\CaseConvert::upper($mixedCaseString); } /** * PROPERCASE. * - * Converts a string value to upper case. + * Converts a string value to proper/title case. * - * @param string $mixedCaseString + * @Deprecated 1.18.0 * - * @return string + * @see Use the proper() method in the TextData\CaseConvert class instead + * + * @param array|string $mixedCaseString + * + * @return array|string */ public static function PROPERCASE($mixedCaseString) { - $mixedCaseString = Functions::flattenSingleValue($mixedCaseString); - - if (is_bool($mixedCaseString)) { - $mixedCaseString = ($mixedCaseString) ? Calculation::getTRUE() : Calculation::getFALSE(); - } - - return StringHelper::strToTitle($mixedCaseString); + return TextData\CaseConvert::proper($mixedCaseString); } /** * REPLACE. * + * @Deprecated 1.18.0 + * + * @see Use the replace() method in the TextData\Replace class instead + * * @param string $oldText String to modify * @param int $start Start character * @param int $chars Number of characters * @param string $newText String to replace in defined position * - * @return string + * @return array|string */ public static function REPLACE($oldText, $start, $chars, $newText) { - $oldText = Functions::flattenSingleValue($oldText); - $start = Functions::flattenSingleValue($start); - $chars = Functions::flattenSingleValue($chars); - $newText = Functions::flattenSingleValue($newText); - - $left = self::LEFT($oldText, $start - 1); - $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText) - ($start + $chars) + 1); - - return $left . $newText . $right; + return TextData\Replace::replace($oldText, $start, $chars, $newText); } /** * SUBSTITUTE. * + * @Deprecated 1.18.0 + * + * @see Use the substitute() method in the TextData\Replace class instead + * * @param string $text Value * @param string $fromText From Value * @param string $toText To Value * @param int $instance Instance Number * - * @return string + * @return array|string */ public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) { - $text = Functions::flattenSingleValue($text); - $fromText = Functions::flattenSingleValue($fromText); - $toText = Functions::flattenSingleValue($toText); - $instance = floor(Functions::flattenSingleValue($instance)); - - if ($instance == 0) { - return str_replace($fromText, $toText, $text); - } - - $pos = -1; - while ($instance > 0) { - $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); - if ($pos === false) { - break; - } - --$instance; - } - - if ($pos !== false) { - return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText); - } - - return $text; + return TextData\Replace::substitute($text, $fromText, $toText, $instance); } /** * RETURNSTRING. * + * @Deprecated 1.18.0 + * + * @see Use the test() method in the TextData\Text class instead + * * @param mixed $testValue Value to check * - * @return null|string + * @return null|array|string */ public static function RETURNSTRING($testValue = '') { - $testValue = Functions::flattenSingleValue($testValue); - - if (is_string($testValue)) { - return $testValue; - } - - return null; + return TextData\Text::test($testValue); } /** * TEXTFORMAT. * + * @Deprecated 1.18.0 + * + * @see Use the TEXTFORMAT() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param string $format Format mask to use * - * @return string + * @return array|string */ public static function TEXTFORMAT($value, $format) { - $value = Functions::flattenSingleValue($value); - $format = Functions::flattenSingleValue($format); - - if ((is_string($value)) && (!is_numeric($value)) && Date::isDateTimeFormatCode($format)) { - $value = DateTime::DATEVALUE($value); - } - - return (string) NumberFormat::toFormattedString($value, $format); + return TextData\Format::TEXTFORMAT($value, $format); } /** * VALUE. * + * @Deprecated 1.18.0 + * + * @see Use the VALUE() method in the TextData\Format class instead + * * @param mixed $value Value to check * - * @return bool + * @return array|DateTimeInterface|float|int|string A string if arguments are invalid */ public static function VALUE($value = '') { - $value = Functions::flattenSingleValue($value); - - if (!is_numeric($value)) { - $numberValue = str_replace( - StringHelper::getThousandsSeparator(), - '', - trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) - ); - if (is_numeric($numberValue)) { - return (float) $numberValue; - } - - $dateSetting = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); - - if (strpos($value, ':') !== false) { - $timeValue = DateTime::TIMEVALUE($value); - if ($timeValue !== Functions::VALUE()) { - Functions::setReturnDateType($dateSetting); - - return $timeValue; - } - } - $dateValue = DateTime::DATEVALUE($value); - if ($dateValue !== Functions::VALUE()) { - Functions::setReturnDateType($dateSetting); - - return $dateValue; - } - Functions::setReturnDateType($dateSetting); - - return Functions::VALUE(); - } - - return (float) $value; + return TextData\Format::VALUE($value); } /** * NUMBERVALUE. * + * @Deprecated 1.18.0 + * + * @see Use the NUMBERVALUE() method in the TextData\Format class instead + * * @param mixed $value Value to check * @param string $decimalSeparator decimal separator, defaults to locale defined value * @param string $groupSeparator group/thosands separator, defaults to locale defined value * - * @return float|string + * @return array|float|string */ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) { - $value = Functions::flattenSingleValue($value); - $decimalSeparator = Functions::flattenSingleValue($decimalSeparator); - $groupSeparator = Functions::flattenSingleValue($groupSeparator); - - if (!is_numeric($value)) { - $decimalSeparator = empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : $decimalSeparator; - $groupSeparator = empty($groupSeparator) ? StringHelper::getThousandsSeparator() : $groupSeparator; - - $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator) . '/', $value, $matches, PREG_OFFSET_CAPTURE); - if ($decimalPositions > 1) { - return Functions::VALUE(); - } - $decimalOffset = array_pop($matches[0])[1]; - if (strpos($value, $groupSeparator, $decimalOffset) !== false) { - return Functions::VALUE(); - } - - $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); - - // Handle the special case of trailing % signs - $percentageString = rtrim($value, '%'); - if (!is_numeric($percentageString)) { - return Functions::VALUE(); - } - - $percentageAdjustment = strlen($value) - strlen($percentageString); - if ($percentageAdjustment) { - $value = (float) $percentageString; - $value /= pow(10, $percentageAdjustment * 2); - } - } - - return (float) $value; + return TextData\Format::NUMBERVALUE($value, $decimalSeparator, $groupSeparator); } /** @@ -635,40 +395,54 @@ public static function NUMBERVALUE($value = '', $decimalSeparator = null, $group * EXACT is case-sensitive but ignores formatting differences. * Use EXACT to test text being entered into a document. * - * @param $value1 - * @param $value2 + * @Deprecated 1.18.0 * - * @return bool + * @see Use the exact() method in the TextData\Text class instead + * + * @param mixed $value1 + * @param mixed $value2 + * + * @return array|bool */ public static function EXACT($value1, $value2) { - $value1 = Functions::flattenSingleValue($value1); - $value2 = Functions::flattenSingleValue($value2); - - return (string) $value2 === (string) $value1; + return TextData\Text::exact($value1, $value2); } /** * TEXTJOIN. * + * @Deprecated 1.18.0 + * + * @see Use the TEXTJOIN() method in the TextData\Concatenate class instead + * * @param mixed $delimiter * @param mixed $ignoreEmpty * @param mixed $args * - * @return string + * @return array|string */ public static function TEXTJOIN($delimiter, $ignoreEmpty, ...$args) { - // Loop through arguments - $aArgs = Functions::flattenArray($args); - foreach ($aArgs as $key => &$arg) { - if ($ignoreEmpty && trim($arg) == '') { - unset($aArgs[$key]); - } elseif (is_bool($arg)) { - $arg = self::convertBooleanValue($arg); - } - } + return TextData\Concatenate::TEXTJOIN($delimiter, $ignoreEmpty, ...$args); + } - return implode($delimiter, $aArgs); + /** + * REPT. + * + * Returns the result of builtin function repeat after validating args. + * + * @Deprecated 1.18.0 + * + * @see Use the builtinREPT() method in the TextData\Concatenate class instead + * + * @param array|string $str Should be numeric + * @param mixed $number Should be int + * + * @return array|string + */ + public static function builtinREPT($str, $number) + { + return TextData\Concatenate::builtinREPT($str, $number); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php new file mode 100644 index 00000000..f1aea169 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/CaseConvert.php @@ -0,0 +1,80 @@ + 255) { + return ExcelError::VALUE(); + } + $result = iconv('UCS-4LE', 'UTF-8', pack('V', $character)); + + return ($result === false) ? '' : $result; + } + + /** + * CODE. + * + * @param mixed $characters String character to convert to its ASCII value + * Or can be an array of values + * + * @return array|int|string A string if arguments are invalid + * If an array of values is passed as the argument, then the returned result will also be an array + * with the same dimensions + */ + public static function code($characters) + { + if (is_array($characters)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $characters); + } + + $characters = Helpers::extractString($characters); + if ($characters === '') { + return ExcelError::VALUE(); + } + + $character = $characters; + if (mb_strlen($characters, 'UTF-8') > 1) { + $character = mb_substr($characters, 0, 1, 'UTF-8'); + } + + return self::unicodeToOrd($character); + } + + private static function unicodeToOrd(string $character): int + { + $retVal = 0; + $iconv = iconv('UTF-8', 'UCS-4LE', $character); + if ($iconv !== false) { + $result = unpack('V', $iconv); + if (is_array($result) && isset($result[1])) { + $retVal = $result[1]; + } + } + + return $retVal; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php new file mode 100644 index 00000000..4413b4a4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Concatenate.php @@ -0,0 +1,98 @@ + &$arg) { + if ($ignoreEmpty === true && is_string($arg) && trim($arg) === '') { + unset($aArgs[$key]); + } elseif (is_bool($arg)) { + $arg = Helpers::convertBooleanValue($arg); + } + } + + return implode($delimiter, $aArgs); + } + + /** + * REPT. + * + * Returns the result of builtin function round after validating args. + * + * @param mixed $stringValue The value to repeat + * Or can be an array of values + * @param mixed $repeatCount The number of times the string value should be repeated + * Or can be an array of values + * + * @return array|string The repeated string + * If an array of values is passed for the $stringValue or $repeatCount arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function builtinREPT($stringValue, $repeatCount) + { + if (is_array($stringValue) || is_array($repeatCount)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $stringValue, $repeatCount); + } + + $stringValue = Helpers::extractString($stringValue); + + if (!is_numeric($repeatCount) || $repeatCount < 0) { + return ExcelError::VALUE(); + } + + return str_repeat($stringValue, (int) $repeatCount); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php new file mode 100644 index 00000000..d29f80ca --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Extract.php @@ -0,0 +1,98 @@ +getMessage(); + } + + return mb_substr($value ?? '', 0, $chars, 'UTF-8'); + } + + /** + * MID. + * + * @param mixed $value String value from which to extract characters + * Or can be an array of values + * @param mixed $start Integer offset of the first character that we want to extract + * Or can be an array of values + * @param mixed $chars The number of characters to extract (as an integer) + * Or can be an array of values + * + * @return array|string The joined string + * If an array of values is passed for the $value, $start or $chars arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function mid($value, $start, $chars) + { + if (is_array($value) || is_array($start) || is_array($chars)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $start, $chars); + } + + try { + $value = Helpers::extractString($value); + $start = Helpers::extractInt($start, 1); + $chars = Helpers::extractInt($chars, 0); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + return mb_substr($value ?? '', --$start, $chars, 'UTF-8'); + } + + /** + * RIGHT. + * + * @param mixed $value String value from which to extract characters + * Or can be an array of values + * @param mixed $chars The number of characters to extract (as an integer) + * Or can be an array of values + * + * @return array|string The joined string + * If an array of values is passed for the $value or $chars arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function right($value, $chars = 1) + { + if (is_array($value) || is_array($chars)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $chars); + } + + try { + $value = Helpers::extractString($value); + $chars = Helpers::extractInt($chars, 0, 1); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + return mb_substr($value ?? '', mb_strlen($value ?? '', 'UTF-8') - $chars, $chars, 'UTF-8'); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php new file mode 100644 index 00000000..bec11496 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Format.php @@ -0,0 +1,280 @@ +getMessage(); + } + + $mask = '$#,##0'; + if ($decimals > 0) { + $mask .= '.' . str_repeat('0', $decimals); + } else { + $round = 10 ** abs($decimals); + if ($value < 0) { + $round = 0 - $round; + } + $value = MathTrig\Round::multiple($value, $round); + } + $mask = "{$mask};-{$mask}"; + + return NumberFormat::toFormattedString($value, $mask); + } + + /** + * FIXED. + * + * @param mixed $value The value to format + * Or can be an array of values + * @param mixed $decimals Integer value for the number of decimal places that should be formatted + * Or can be an array of values + * @param mixed $noCommas Boolean value indicating whether the value should have thousands separators or not + * Or can be an array of values + * + * @return array|string + * If an array of values is passed for either of the arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function FIXEDFORMAT($value, $decimals = 2, $noCommas = false) + { + if (is_array($value) || is_array($decimals) || is_array($noCommas)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimals, $noCommas); + } + + try { + $value = Helpers::extractFloat($value); + $decimals = Helpers::extractInt($decimals, -100, 0, true); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + $valueResult = round($value, $decimals); + if ($decimals < 0) { + $decimals = 0; + } + if ($noCommas === false) { + $valueResult = number_format( + $valueResult, + $decimals, + StringHelper::getDecimalSeparator(), + StringHelper::getThousandsSeparator() + ); + } + + return (string) $valueResult; + } + + /** + * TEXT. + * + * @param mixed $value The value to format + * Or can be an array of values + * @param mixed $format A string with the Format mask that should be used + * Or can be an array of values + * + * @return array|string + * If an array of values is passed for either of the arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function TEXTFORMAT($value, $format) + { + if (is_array($value) || is_array($format)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $format); + } + + $value = Helpers::extractString($value); + $format = Helpers::extractString($format); + + if (!is_numeric($value) && Date::isDateTimeFormatCode($format)) { + $value = DateTimeExcel\DateValue::fromString($value); + } + + return (string) NumberFormat::toFormattedString($value, $format); + } + + /** + * @param mixed $value Value to check + * + * @return mixed + */ + private static function convertValue($value) + { + $value = $value ?? 0; + if (is_bool($value)) { + if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { + $value = (int) $value; + } else { + throw new CalcExp(ExcelError::VALUE()); + } + } + + return $value; + } + + /** + * VALUE. + * + * @param mixed $value Value to check + * Or can be an array of values + * + * @return array|DateTimeInterface|float|int|string A string if arguments are invalid + * If an array of values is passed for the argument, then the returned result + * will also be an array with matching dimensions + */ + public static function VALUE($value = '') + { + if (is_array($value)) { + return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); + } + + try { + $value = self::convertValue($value); + } catch (CalcExp $e) { + return $e->getMessage(); + } + if (!is_numeric($value)) { + $numberValue = str_replace( + StringHelper::getThousandsSeparator(), + '', + trim($value, " \t\n\r\0\x0B" . StringHelper::getCurrencyCode()) + ); + if (is_numeric($numberValue)) { + return (float) $numberValue; + } + + $dateSetting = Functions::getReturnDateType(); + Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); + + if (strpos($value, ':') !== false) { + $timeValue = Functions::scalar(DateTimeExcel\TimeValue::fromString($value)); + if ($timeValue !== ExcelError::VALUE()) { + Functions::setReturnDateType($dateSetting); + + return $timeValue; + } + } + $dateValue = Functions::scalar(DateTimeExcel\DateValue::fromString($value)); + if ($dateValue !== ExcelError::VALUE()) { + Functions::setReturnDateType($dateSetting); + + return $dateValue; + } + Functions::setReturnDateType($dateSetting); + + return ExcelError::VALUE(); + } + + return (float) $value; + } + + /** + * @param mixed $decimalSeparator + */ + private static function getDecimalSeparator($decimalSeparator): string + { + return empty($decimalSeparator) ? StringHelper::getDecimalSeparator() : (string) $decimalSeparator; + } + + /** + * @param mixed $groupSeparator + */ + private static function getGroupSeparator($groupSeparator): string + { + return empty($groupSeparator) ? StringHelper::getThousandsSeparator() : (string) $groupSeparator; + } + + /** + * NUMBERVALUE. + * + * @param mixed $value The value to format + * Or can be an array of values + * @param mixed $decimalSeparator A string with the decimal separator to use, defaults to locale defined value + * Or can be an array of values + * @param mixed $groupSeparator A string with the group/thousands separator to use, defaults to locale defined value + * Or can be an array of values + * + * @return array|float|string + */ + public static function NUMBERVALUE($value = '', $decimalSeparator = null, $groupSeparator = null) + { + if (is_array($value) || is_array($decimalSeparator) || is_array($groupSeparator)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $decimalSeparator, $groupSeparator); + } + + try { + $value = self::convertValue($value); + $decimalSeparator = self::getDecimalSeparator($decimalSeparator); + $groupSeparator = self::getGroupSeparator($groupSeparator); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + if (!is_numeric($value)) { + $decimalPositions = preg_match_all('/' . preg_quote($decimalSeparator) . '/', $value, $matches, PREG_OFFSET_CAPTURE); + if ($decimalPositions > 1) { + return ExcelError::VALUE(); + } + $decimalOffset = array_pop($matches[0])[1]; + if (strpos($value, $groupSeparator, $decimalOffset) !== false) { + return ExcelError::VALUE(); + } + + $value = str_replace([$groupSeparator, $decimalSeparator], ['', '.'], $value); + + // Handle the special case of trailing % signs + $percentageString = rtrim($value, '%'); + if (!is_numeric($percentageString)) { + return ExcelError::VALUE(); + } + + $percentageAdjustment = strlen($value) - strlen($percentageString); + if ($percentageAdjustment) { + $value = (float) $percentageString; + $value /= 10 ** ($percentageAdjustment * 2); + } + } + + return is_array($value) ? ExcelError::VALUE() : (float) $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php new file mode 100644 index 00000000..0fdf6af8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Helpers.php @@ -0,0 +1,87 @@ +getMessage(); + } + + return $left . $newText . $right; + } + + /** + * SUBSTITUTE. + * + * @param mixed $text The text string value to modify + * Or can be an array of values + * @param mixed $fromText The string value that we want to replace in $text + * Or can be an array of values + * @param mixed $toText The string value that we want to replace with in $text + * Or can be an array of values + * @param mixed $instance Integer instance Number for the occurrence of frmText to change + * Or can be an array of values + * + * @return array|string + * If an array of values is passed for either of the arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function substitute($text = '', $fromText = '', $toText = '', $instance = null) + { + if (is_array($text) || is_array($fromText) || is_array($toText) || is_array($instance)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $text, $fromText, $toText, $instance); + } + + try { + $text = Helpers::extractString($text); + $fromText = Helpers::extractString($fromText); + $toText = Helpers::extractString($toText); + if ($instance === null) { + return str_replace($fromText, $toText, $text); + } + if (is_bool($instance)) { + if ($instance === false || Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_OPENOFFICE) { + return ExcelError::Value(); + } + $instance = 1; + } + $instance = Helpers::extractInt($instance, 1, 0, true); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + return self::executeSubstitution($text, $fromText, $toText, $instance); + } + + /** + * @return string + */ + private static function executeSubstitution(string $text, string $fromText, string $toText, int $instance) + { + $pos = -1; + while ($instance > 0) { + $pos = mb_strpos($text, $fromText, $pos + 1, 'UTF-8'); + if ($pos === false) { + break; + } + --$instance; + } + + if ($pos !== false) { + return Functions::scalar(self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText)); + } + + return $text; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php new file mode 100644 index 00000000..10b6a1aa --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Search.php @@ -0,0 +1,97 @@ +getMessage(); + } + + if (StringHelper::countCharacters($haystack) >= $offset) { + if (StringHelper::countCharacters($needle) === 0) { + return $offset; + } + + $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); + if ($pos !== false) { + return ++$pos; + } + } + + return ExcelError::VALUE(); + } + + /** + * SEARCH (case insensitive search). + * + * @param mixed $needle The string to look for + * Or can be an array of values + * @param mixed $haystack The string in which to look + * Or can be an array of values + * @param mixed $offset Integer offset within $haystack to start searching from + * Or can be an array of values + * + * @return array|int|string The offset where the first occurrence of needle was found in the haystack + * If an array of values is passed for the $value or $chars arguments, then the returned result + * will also be an array with matching dimensions + */ + public static function insensitive($needle, $haystack, $offset = 1) + { + if (is_array($needle) || is_array($haystack) || is_array($offset)) { + return self::evaluateArrayArguments([self::class, __FUNCTION__], $needle, $haystack, $offset); + } + + try { + $needle = Helpers::extractString($needle); + $haystack = Helpers::extractString($haystack); + $offset = Helpers::extractInt($offset, 1, 0, true); + } catch (CalcExp $e) { + return $e->getMessage(); + } + + if (StringHelper::countCharacters($haystack) >= $offset) { + if (StringHelper::countCharacters($needle) === 0) { + return $offset; + } + + $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); + if ($pos !== false) { + return ++$pos; + } + } + + return ExcelError::VALUE(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php new file mode 100644 index 00000000..490c43c2 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/TextData/Text.php @@ -0,0 +1,80 @@ +branchPruner = $branchPruner; + } + /** * Return the number of entries on the stack. - * - * @return int */ - public function count() + public function count(): int { return $this->count; } @@ -33,25 +42,11 @@ public function count() /** * Push a new entry onto the stack. * - * @param mixed $type * @param mixed $value - * @param mixed $reference - * @param null|string $storeKey will store the result under this alias - * @param null|string $onlyIf will only run computation if the matching - * store key is true - * @param null|string $onlyIfNot will only run computation if the matching - * store key is false */ - public function push( - $type, - $value, - $reference = null, - $storeKey = null, - $onlyIf = null, - $onlyIfNot = null - ) { - $stackItem = $this->getStackItem($type, $value, $reference, $storeKey, $onlyIf, $onlyIfNot); - + public function push(string $type, $value, ?string $reference = null): void + { + $stackItem = $this->getStackItem($type, $value, $reference); $this->stack[$this->count++] = $stackItem; if ($type == 'Function') { @@ -62,29 +57,37 @@ public function push( } } - public function getStackItem( - $type, - $value, - $reference = null, - $storeKey = null, - $onlyIf = null, - $onlyIfNot = null - ) { + public function pushStackItem(array $stackItem): void + { + $this->stack[$this->count++] = $stackItem; + } + + /** + * @param mixed $value + */ + public function getStackItem(string $type, $value, ?string $reference = null): array + { $stackItem = [ 'type' => $type, 'value' => $value, 'reference' => $reference, ]; - if (isset($storeKey)) { + // will store the result under this alias + $storeKey = $this->branchPruner->currentCondition(); + if (isset($storeKey) || $reference === 'NULL') { $stackItem['storeKey'] = $storeKey; } - if (isset($onlyIf)) { + // will only run computation if the matching store key is true + $onlyIf = $this->branchPruner->currentOnlyIf(); + if (isset($onlyIf) || $reference === 'NULL') { $stackItem['onlyIf'] = $onlyIf; } - if (isset($onlyIfNot)) { + // will only run computation if the matching store key is false + $onlyIfNot = $this->branchPruner->currentOnlyIfNot(); + if (isset($onlyIfNot) || $reference === 'NULL') { $stackItem['onlyIfNot'] = $onlyIfNot; } @@ -93,10 +96,8 @@ public function getStackItem( /** * Pop the last entry from the stack. - * - * @return mixed */ - public function pop() + public function pop(): ?array { if ($this->count > 0) { return $this->stack[--$this->count]; @@ -107,12 +108,8 @@ public function pop() /** * Return an entry from the stack without removing it. - * - * @param int $n number indicating how far back in the stack we want to look - * - * @return mixed */ - public function last($n = 1) + public function last(int $n = 1): ?array { if ($this->count - $n < 0) { return null; @@ -124,26 +121,9 @@ public function last($n = 1) /** * Clear the stack. */ - public function clear() + public function clear(): void { $this->stack = []; $this->count = 0; } - - public function __toString() - { - $str = 'Stack: '; - foreach ($this->stack as $index => $item) { - if ($index > $this->count - 1) { - break; - } - $value = $item['value'] ?? 'no value'; - while (is_array($value)) { - $value = array_pop($value); - } - $str .= $value . ' |> '; - } - - return $str; - } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web.php new file mode 100644 index 00000000..3f3d945d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Web.php @@ -0,0 +1,27 @@ + 2048) { + return ExcelError::VALUE(); // Invalid URL length + } + + if (!preg_match('/^http[s]?:\/\//', $url)) { + return ExcelError::VALUE(); // Invalid protocol + } + + // Get results from the the webservice + $client = Settings::getHttpClient(); + $requestFactory = Settings::getRequestFactory(); + $request = $requestFactory->createRequest('GET', $url); + + try { + $response = $client->sendRequest($request); + } catch (ClientExceptionInterface $e) { + return ExcelError::VALUE(); // cURL error + } + + if ($response->getStatusCode() != 200) { + return ExcelError::VALUE(); // cURL error + } + + $output = $response->getBody()->getContents(); + if (strlen($output) > 32767) { + return ExcelError::VALUE(); // Output not a string or too long + } + + return $output; + } + + /** + * URLENCODE. + * + * Returns data from a web service on the Internet or Intranet. + * + * Excel Function: + * urlEncode(text) + * + * @param mixed $text + * + * @return string the url encoded output + */ + public static function urlEncode($text) + { + if (!is_string($text)) { + return ExcelError::VALUE(); + } + + return str_replace('+', '%20', urlencode($text)); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt index 77fd4ee0..270715cd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/functionlist.txt @@ -40,6 +40,8 @@ BITOR BITRSHIFT BITXOR CEILING +CEILING.MATH +CEILING.PRECISE CELL CHAR CHIDIST @@ -51,6 +53,7 @@ CODE COLUMN COLUMNS COMBIN +COMBINA COMPLEX CONCAT CONCATENATE @@ -163,6 +166,7 @@ HYPERLINK HYPGEOMDIST IF IFERROR +IFS IMABS IMAGINARY IMARGUMENT @@ -246,6 +250,7 @@ MODE MONTH MROUND MULTINOMIAL +MUNIT N NA NEGBINOMDIST @@ -275,6 +280,7 @@ PEARSON PERCENTILE PERCENTRANK PERMUT +PERMUTATIONA PHONETIC PI PMT @@ -316,6 +322,8 @@ SEC SECH SECOND SERIESSUM +SHEET +SHEETS SIGN SIN SINH diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx new file mode 100644 index 00000000..6f758b9c Binary files /dev/null and b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/Translations.xlsx differ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config index df513734..49f40fcb 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/config @@ -1,23 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - -## -## (For future use) +## Ceština (Czech) ## -currencySymbol = Kč +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) +## Error Codes ## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #HODNOTA! -REF = #REF! -NAME = #NÁZEV? -NUM = #NUM! -NA = #N/A +NULL +DIV0 = #DĚLENÍ_NULOU! +VALUE = #HODNOTA! +REF = #ODKAZ! +NAME = #NÁZEV? +NUM = #ČÍSLO! +NA = #NENÍ_K_DISPOZICI diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions index 733d406f..49c4945c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/cs/functions @@ -1,416 +1,520 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Ceština (Czech) ## +############################################################ ## -## Add-in and Automation functions Funkce doplňků a automatizace +## Funkce pro práci s datovými krychlemi (Cube Functions) ## -GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena. - +CUBEKPIMEMBER = CUBEKPIMEMBER +CUBEMEMBER = CUBEMEMBER +CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY +CUBERANKEDMEMBER = CUBERANKEDMEMBER +CUBESET = CUBESET +CUBESETCOUNT = CUBESETCOUNT +CUBEVALUE = CUBEVALUE ## -## Cube functions Funkce pro práci s krychlemi +## Funkce databáze (Database Functions) ## -CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace. -CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice. -CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena. -CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů. -CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel. -CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině -CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle. - +DAVERAGE = DPRŮMĚR +DCOUNT = DPOČET +DCOUNTA = DPOČET2 +DGET = DZÍSKAT +DMAX = DMAX +DMIN = DMIN +DPRODUCT = DSOUČIN +DSTDEV = DSMODCH.VÝBĚR +DSTDEVP = DSMODCH +DSUM = DSUMA +DVAR = DVAR.VÝBĚR +DVARP = DVAR ## -## Database functions Funkce databáze +## Funkce data a času (Date & Time Functions) ## -DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze. -DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla. -DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné. -DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria. -DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze. -DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze. -DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria. -DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze. -DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze. -DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria. -DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze. -DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze. - +DATE = DATUM +DATEVALUE = DATUMHODN +DAY = DEN +DAYS = DAYS +DAYS360 = ROK360 +EDATE = EDATE +EOMONTH = EOMONTH +HOUR = HODINA +ISOWEEKNUM = ISOWEEKNUM +MINUTE = MINUTA +MONTH = MĚSÍC +NETWORKDAYS = NETWORKDAYS +NETWORKDAYS.INTL = NETWORKDAYS.INTL +NOW = NYNÍ +SECOND = SEKUNDA +TIME = ČAS +TIMEVALUE = ČASHODN +TODAY = DNES +WEEKDAY = DENTÝDNE +WEEKNUM = WEEKNUM +WORKDAY = WORKDAY +WORKDAY.INTL = WORKDAY.INTL +YEAR = ROK +YEARFRAC = YEARFRAC ## -## Date and time functions Funkce data a času +## Inženýrské funkce (Engineering Functions) ## -DATE = DATUM ## Vrátí pořadové číslo určitého data. -DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo. -DAY = DEN ## Převede pořadové číslo na den v měsíci. -DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny. -EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu. -EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců. -HOUR = HODINA ## Převede pořadové číslo na hodinu. -MINUTE = MINUTA ## Převede pořadové číslo na minutu. -MONTH = MĚSÍC ## Převede pořadové číslo na měsíc. -NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty. -NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času. -SECOND = SEKUNDA ## Převede pořadové číslo na sekundu. -TIME = ČAS ## Vrátí pořadové číslo určitého času. -TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo. -TODAY = DNES ## Vrátí pořadové číslo dnešního data. -WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu. -WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce. -WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní. -YEAR = ROK ## Převede pořadové číslo na rok. -YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN2DEC +BIN2HEX = BIN2HEX +BIN2OCT = BIN2OCT +BITAND = BITAND +BITLSHIFT = BITLSHIFT +BITOR = BITOR +BITRSHIFT = BITRSHIFT +BITXOR = BITXOR +COMPLEX = COMPLEX +CONVERT = CONVERT +DEC2BIN = DEC2BIN +DEC2HEX = DEC2HEX +DEC2OCT = DEC2OCT +DELTA = DELTA +ERF = ERF +ERF.PRECISE = ERF.PRECISE +ERFC = ERFC +ERFC.PRECISE = ERFC.PRECISE +GESTEP = GESTEP +HEX2BIN = HEX2BIN +HEX2DEC = HEX2DEC +HEX2OCT = HEX2OCT +IMABS = IMABS +IMAGINARY = IMAGINARY +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMCONJUGATE +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOWER +IMPRODUCT = IMPRODUCT +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMSQRT +IMSUB = IMSUB +IMSUM = IMSUM +IMTAN = IMTAN +OCT2BIN = OCT2BIN +OCT2DEC = OCT2DEC +OCT2HEX = OCT2HEX ## -## Engineering functions Inženýrské funkce (Technické funkce) +## Finanční funkce (Financial Functions) ## -BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x). -BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x). -BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x). -BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x). -BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové. -BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové. -BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové. -COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo. -CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému. -DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové -DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové. -DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové. -DELTA = DELTA ## Testuje rovnost dvou hodnot. -ERF = ERF ## Vrátí chybovou funkci. -ERFC = ERFC ## Vrátí doplňkovou chybovou funkci. -GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota. -HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární. -HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové. -HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové. -IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla. -IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla. -IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech. -IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu. -IMCOS = IMCOS ## Vrátí kosinus komplexního čísla. -IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel. -IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla. -IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla. -IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla. -IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2. -IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo. -IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel. -IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla. -IMSIN = IMSIN ## Vrátí sinus komplexního čísla. -IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla. -IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly. -IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel. -OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární. -OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové. -OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové. - +ACCRINT = ACCRINT +ACCRINTM = ACCRINTM +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = COUPDAYBS +COUPDAYS = COUPDAYS +COUPDAYSNC = COUPDAYSNC +COUPNCD = COUPNCD +COUPNUM = COUPNUM +COUPPCD = COUPPCD +CUMIPMT = CUMIPMT +CUMPRINC = CUMPRINC +DB = ODPIS.ZRYCH +DDB = ODPIS.ZRYCH2 +DISC = DISC +DOLLARDE = DOLLARDE +DOLLARFR = DOLLARFR +DURATION = DURATION +EFFECT = EFFECT +FV = BUDHODNOTA +FVSCHEDULE = FVSCHEDULE +INTRATE = INTRATE +IPMT = PLATBA.ÚROK +IRR = MÍRA.VÝNOSNOSTI +ISPMT = ISPMT +MDURATION = MDURATION +MIRR = MOD.MÍRA.VÝNOSNOSTI +NOMINAL = NOMINAL +NPER = POČET.OBDOBÍ +NPV = ČISTÁ.SOUČHODNOTA +ODDFPRICE = ODDFPRICE +ODDFYIELD = ODDFYIELD +ODDLPRICE = ODDLPRICE +ODDLYIELD = ODDLYIELD +PDURATION = PDURATION +PMT = PLATBA +PPMT = PLATBA.ZÁKLAD +PRICE = PRICE +PRICEDISC = PRICEDISC +PRICEMAT = PRICEMAT +PV = SOUČHODNOTA +RATE = ÚROKOVÁ.MÍRA +RECEIVED = RECEIVED +RRI = RRI +SLN = ODPIS.LIN +SYD = ODPIS.NELIN +TBILLEQ = TBILLEQ +TBILLPRICE = TBILLPRICE +TBILLYIELD = TBILLYIELD +VDB = ODPIS.ZA.INT +XIRR = XIRR +XNPV = XNPV +YIELD = YIELD +YIELDDISC = YIELDDISC +YIELDMAT = YIELDMAT ## -## Financial functions Finanční funkce +## Informační funkce (Information Functions) ## -ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech. -ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti. -AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace. -AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období. -COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti. -COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování. -COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu. -COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování. -COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti. -COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování. -CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími. -CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky. -DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem. -DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte. -DISC = DISC ## Vrátí diskontní sazbu cenného papíru. -DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem. -DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem. -DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami. -EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu. -FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice. -FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku. -INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru. -IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období. -IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků. -ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období. -MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč. -MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb. -NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu. -NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici. -NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby. -ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím. -ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím. -ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím. -ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím. -PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity. -PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období. -PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech. -PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč. -PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti. -PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice. -RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity. -RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru. -SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období. -SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období. -TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace. -TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč. -TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny. -VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu. -XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický. -XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický. -YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech. -YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny. -YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti. - +CELL = POLÍČKO +ERROR.TYPE = CHYBA.TYP +INFO = O.PROSTŘEDÍ +ISBLANK = JE.PRÁZDNÉ +ISERR = JE.CHYBA +ISERROR = JE.CHYBHODN +ISEVEN = ISEVEN +ISFORMULA = ISFORMULA +ISLOGICAL = JE.LOGHODN +ISNA = JE.NEDEF +ISNONTEXT = JE.NETEXT +ISNUMBER = JE.ČISLO +ISODD = ISODD +ISREF = JE.ODKAZ +ISTEXT = JE.TEXT +N = N +NA = NEDEF +SHEET = SHEET +SHEETS = SHEETS +TYPE = TYP ## -## Information functions Informační funkce +## Logické funkce (Logical Functions) ## -CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky. -ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby. -INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí. -ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku. -ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A). -ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota. -ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé. -ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota. -ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A. -ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text. -ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo. -ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché. -ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz. -ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text. -N = N ## Vrátí hodnotu převedenou na číslo. -NA = NEDEF ## Vrátí chybovou hodnotu #N/A. -TYPE = TYP ## Vrátí číslo označující datový typ hodnoty. - +AND = A +FALSE = NEPRAVDA +IF = KDYŽ +IFERROR = IFERROR +IFNA = IFNA +IFS = IFS +NOT = NE +OR = NEBO +SWITCH = SWITCH +TRUE = PRAVDA +XOR = XOR ## -## Logical functions Logické funkce +## Vyhledávací funkce a funkce pro odkazy (Lookup & Reference Functions) ## -AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA. -FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA. -IF = KDYŽ ## Určí, který logický test má proběhnout. -IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce. -NOT = NE ## Provede logickou negaci argumentu funkce. -OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA. -TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA. - +ADDRESS = ODKAZ +AREAS = POČET.BLOKŮ +CHOOSE = ZVOLIT +COLUMN = SLOUPEC +COLUMNS = SLOUPCE +FORMULATEXT = FORMULATEXT +GETPIVOTDATA = ZÍSKATKONTDATA +HLOOKUP = VVYHLEDAT +HYPERLINK = HYPERTEXTOVÝ.ODKAZ +INDEX = INDEX +INDIRECT = NEPŘÍMÝ.ODKAZ +LOOKUP = VYHLEDAT +MATCH = POZVYHLEDAT +OFFSET = POSUN +ROW = ŘÁDEK +ROWS = ŘÁDKY +RTD = RTD +TRANSPOSE = TRANSPOZICE +VLOOKUP = SVYHLEDAT ## -## Lookup and reference functions Vyhledávací funkce +## Matematické a trigonometrické funkce (Math & Trig Functions) ## -ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu. -AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu. -CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot. -COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu. -COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu. -HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky. -HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet. -INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice. -INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou. -LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici. -MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici. -OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu. -ROW = ŘÁDEK ## Vrátí číslo řádku odkazu. -ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu. -RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).). -TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici. -VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky. - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGGREGATE +ARABIC = ARABIC +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTG +ATAN2 = ARCTG2 +ATANH = ARCTGH +BASE = BASE +CEILING.MATH = CEILING.MATH +COMBIN = KOMBINACE +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = DEGREES +EVEN = ZAOKROUHLIT.NA.SUDÉ +EXP = EXP +FACT = FAKTORIÁL +FACTDOUBLE = FACTDOUBLE +FLOOR.MATH = FLOOR.MATH +GCD = GCD +INT = CELÁ.ČÁST +LCM = LCM +LN = LN +LOG = LOGZ +LOG10 = LOG +MDETERM = DETERMINANT +MINVERSE = INVERZE +MMULT = SOUČIN.MATIC +MOD = MOD +MROUND = MROUND +MULTINOMIAL = MULTINOMIAL +MUNIT = MUNIT +ODD = ZAOKROUHLIT.NA.LICHÉ +PI = PI +POWER = POWER +PRODUCT = SOUČIN +QUOTIENT = QUOTIENT +RADIANS = RADIANS +RAND = NÁHČÍSLO +RANDBETWEEN = RANDBETWEEN +ROMAN = ROMAN +ROUND = ZAOKROUHLIT +ROUNDDOWN = ROUNDDOWN +ROUNDUP = ROUNDUP +SEC = SEC +SECH = SECH +SERIESSUM = SERIESSUM +SIGN = SIGN +SIN = SIN +SINH = SINH +SQRT = ODMOCNINA +SQRTPI = SQRTPI +SUBTOTAL = SUBTOTAL +SUM = SUMA +SUMIF = SUMIF +SUMIFS = SUMIFS +SUMPRODUCT = SOUČIN.SKALÁRNÍ +SUMSQ = SUMA.ČTVERCŮ +SUMX2MY2 = SUMX2MY2 +SUMX2PY2 = SUMX2PY2 +SUMXMY2 = SUMXMY2 +TAN = TG +TANH = TGH +TRUNC = USEKNOUT ## -## Math and trigonometry functions Matematické a trigonometrické funkce +## Statistické funkce (Statistical Functions) ## -ABS = ABS ## Vrátí absolutní hodnotu čísla. -ACOS = ARCCOS ## Vrátí arkuskosinus čísla. -ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla. -ASIN = ARCSIN ## Vrátí arkussinus čísla. -ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla. -ATAN = ARCTG ## Vrátí arkustangens čísla. -ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice. -ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla. -CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty. -COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek. -COS = COS ## Vrátí kosinus čísla. -COSH = COSH ## Vrátí hyperbolický kosinus čísla. -DEGREES = DEGREES ## Převede radiány na stupně. -EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo. -EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo. -FACT = FAKTORIÁL ## Vrátí faktoriál čísla. -FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla. -FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule. -GCD = GCD ## Vrátí největší společný dělitel. -INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo. -LCM = LCM ## Vrátí nejmenší společný násobek. -LN = LN ## Vrátí přirozený logaritmus čísla. -LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu. -LOG10 = LOG ## Vrátí dekadický logaritmus čísla. -MDETERM = DETERMINANT ## Vrátí determinant matice. -MINVERSE = INVERZE ## Vrátí inverzní matici. -MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic. -MOD = MOD ## Vrátí zbytek po dělení. -MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek. -MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel. -ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo. -PI = PI ## Vrátí hodnotu čísla pí. -POWER = POWER ## Umocní číslo na zadanou mocninu. -PRODUCT = SOUČIN ## Vynásobí argumenty funkce. -QUOTIENT = QUOTIENT ## Vrátí celou část dělení. -RADIANS = RADIANS ## Převede stupně na radiány. -RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1. -RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly. -ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu. -ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic. -ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule. -ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly. -SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce. -SIGN = SIGN ## Vrátí znaménko čísla. -SIN = SIN ## Vrátí sinus daného úhlu. -SINH = SINH ## Vrátí hyperbolický sinus čísla. -SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu. -SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí). -SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi. -SUM = SUMA ## Sečte argumenty funkce. -SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií. -SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami. -SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic. -SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů. -SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích. -SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích. -SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích. -TAN = TGTG ## Vrátí tangens čísla. -TANH = TGH ## Vrátí hyperbolický tangens čísla. -TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo. - +AVEDEV = PRŮMODCHYLKA +AVERAGE = PRŮMĚR +AVERAGEA = AVERAGEA +AVERAGEIF = AVERAGEIF +AVERAGEIFS = AVERAGEIFS +BETA.DIST = BETA.DIST +BETA.INV = BETA.INV +BINOM.DIST = BINOM.DIST +BINOM.DIST.RANGE = BINOM.DIST.RANGE +BINOM.INV = BINOM.INV +CHISQ.DIST = CHISQ.DIST +CHISQ.DIST.RT = CHISQ.DIST.RT +CHISQ.INV = CHISQ.INV +CHISQ.INV.RT = CHISQ.INV.RT +CHISQ.TEST = CHISQ.TEST +CONFIDENCE.NORM = CONFIDENCE.NORM +CONFIDENCE.T = CONFIDENCE.T +CORREL = CORREL +COUNT = POČET +COUNTA = POČET2 +COUNTBLANK = COUNTBLANK +COUNTIF = COUNTIF +COUNTIFS = COUNTIFS +COVARIANCE.P = COVARIANCE.P +COVARIANCE.S = COVARIANCE.S +DEVSQ = DEVSQ +EXPON.DIST = EXPON.DIST +F.DIST = F.DIST +F.DIST.RT = F.DIST.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = FORECAST.ETS +FORECAST.ETS.CONFINT = FORECAST.ETS.CONFINT +FORECAST.ETS.SEASONALITY = FORECAST.ETS.SEASONALITY +FORECAST.ETS.STAT = FORECAST.ETS.STAT +FORECAST.LINEAR = FORECAST.LINEAR +FREQUENCY = ČETNOSTI +GAMMA = GAMMA +GAMMA.DIST = GAMMA.DIST +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRECISE +GAUSS = GAUSS +GEOMEAN = GEOMEAN +GROWTH = LOGLINTREND +HARMEAN = HARMEAN +HYPGEOM.DIST = HYPGEOM.DIST +INTERCEPT = INTERCEPT +KURT = KURT +LARGE = LARGE +LINEST = LINREGRESE +LOGEST = LOGLINREGRESE +LOGNORM.DIST = LOGNORM.DIST +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXIFS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINIFS +MODE.MULT = MODE.MULT +MODE.SNGL = MODE.SNGL +NEGBINOM.DIST = NEGBINOM.DIST +NORM.DIST = NORM.DIST +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.DIST +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = PERCENTRANK.EXC +PERCENTRANK.INC = PERCENTRANK.INC +PERMUT = PERMUTACE +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.DIST +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = RANK.AVG +RANK.EQ = RANK.EQ +RSQ = RKQ +SKEW = SKEW +SKEW.P = SKEW.P +SLOPE = SLOPE +SMALL = SMALL +STANDARDIZE = STANDARDIZE +STDEV.P = SMODCH.P +STDEV.S = SMODCH.VÝBĚR.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STEYX +T.DIST = T.DIST +T.DIST.2T = T.DIST.2T +T.DIST.RT = T.DIST.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = LINTREND +TRIMMEAN = TRIMMEAN +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.DIST +Z.TEST = Z.TEST ## -## Statistical functions Statistické funkce +## Textové funkce (Text Functions) ## -AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty. -AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů. -AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot. -AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce. -AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám. -BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta. -BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta. -BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin. -CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát. -CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát. -CHITEST = CHITEST ## Vrátí test nezávislosti. -CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru. -CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat. -COUNT = POČET ## Vrátí počet čísel v seznamu argumentů. -COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů. -COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti. -COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím. -COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím. -COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek -CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria. -DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek. -EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení. -FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F. -FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F. -FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace. -FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci. -FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu. -FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici. -FTEST = FTEST ## Vrátí výsledek F-testu. -GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama. -GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama. -GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x). -GEOMEAN = GEOMEAN ## Vrátí geometrický průměr. -GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu. -HARMEAN = HARMEAN ## Vrátí harmonický průměr. -HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení. -INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry. -KURT = KURT ## Vrátí hodnotu excesu množiny dat. -LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat. -LINEST = LINREGRESE ## Vrátí parametry lineárního trendu. -LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu. -LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení. -LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení. -MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů. -MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot. -MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel. -MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů. -MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot. -MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji. -NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení. -NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení. -NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení. -NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení. -NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení. -PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient. -PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti. -PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat. -PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů. -POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení. -PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami. -QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat. -RANK = RANK ## Vrátí pořadí čísla v seznamu čísel. -RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu. -SKEW = SKEW ## Vrátí zešikmení rozdělení. -SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry. -SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat. -STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu. -STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru. -STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot. -STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru. -STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot. -STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi. -TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení. -TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení. -TREND = LINTREND ## Vrátí hodnoty lineárního trendu. -TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat. -TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem. -VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru. -VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot. -VARP = VAR ## Vypočte rozptyl základního souboru. -VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot. -WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení. -ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu. +BAHTTEXT = BAHTTEXT +CHAR = ZNAK +CLEAN = VYČISTIT +CODE = KÓD +CONCAT = CONCAT +DOLLAR = KČ +EXACT = STEJNÉ +FIND = NAJÍT +FIXED = ZAOKROUHLIT.NA.TEXT +LEFT = ZLEVA +LEN = DÉLKA +LOWER = MALÁ +MID = ČÁST +NUMBERVALUE = NUMBERVALUE +PHONETIC = ZVUKOVÉ +PROPER = VELKÁ2 +REPLACE = NAHRADIT +REPT = OPAKOVAT +RIGHT = ZPRAVA +SEARCH = HLEDAT +SUBSTITUTE = DOSADIT +T = T +TEXT = HODNOTA.NA.TEXT +TEXTJOIN = TEXTJOIN +TRIM = PROČISTIT +UNICHAR = UNICHAR +UNICODE = UNICODE +UPPER = VELKÁ +VALUE = HODNOTA +## +## Webové funkce (Web Functions) +## +ENCODEURL = ENCODEURL +FILTERXML = FILTERXML +WEBSERVICE = WEBSERVICE ## -## Text functions Textové funkce +## Funkce pro kompatibilitu (Compatibility Functions) ## -ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové). -BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht). -CHAR = ZNAK ## Vrátí znak určený číslem kódu. -CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky. -CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce. -CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné. -DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna). -EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné. -FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). -FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). -FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst. -JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové). -LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. -LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. -LEN = DÉLKA ## Vrátí počet znaků textového řetězce. -LENB = LENB ## Vrátí počet znaků textového řetězce. -LOWER = MALÁ ## Převede text na malá písmena. -MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. -MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. -PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce. -PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké. -REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu. -REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu. -REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování. -RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. -RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. -SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). -SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). -SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým. -T = T ## Převede argumenty na text. -TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text. -TRIM = PROČISTIT ## Odstraní z textu mezery. -UPPER = VELKÁ ## Převede text na velká písmena. -VALUE = HODNOTA ## Převede textový argument na číslo. +BETADIST = BETADIST +BETAINV = BETAINV +BINOMDIST = BINOMDIST +CEILING = ZAOKR.NAHORU +CHIDIST = CHIDIST +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = CONCATENATE +CONFIDENCE = CONFIDENCE +COVAR = COVAR +CRITBINOM = CRITBINOM +EXPONDIST = EXPONDIST +FDIST = FDIST +FINV = FINV +FLOOR = ZAOKR.DOLŮ +FORECAST = FORECAST +FTEST = FTEST +GAMMADIST = GAMMADIST +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMDIST +LOGINV = LOGINV +LOGNORMDIST = LOGNORMDIST +MODE = MODE +NEGBINOMDIST = NEGBINOMDIST +NORMDIST = NORMDIST +NORMINV = NORMINV +NORMSDIST = NORMSDIST +NORMSINV = NORMSINV +PERCENTILE = PERCENTIL +PERCENTRANK = PERCENTRANK +POISSON = POISSON +QUARTILE = QUARTIL +RANK = RANK +STDEV = SMODCH.VÝBĚR +STDEVP = SMODCH +TDIST = TDIST +TINV = TINV +TTEST = TTEST +VAR = VAR.VÝBĚR +VARP = VAR +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config index a7aa8fee..284b2490 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/config @@ -1,25 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Dansk (Danish) ## -## (For future use) -## -currencySymbol = kr - +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NUL! -DIV0 = #DIVISION/0! -VALUE = #VÆRDI! -REF = #REFERENCE! -NAME = #NAVN? -NUM = #NUM! -NA = #I/T +NULL = #NUL! +DIV0 +VALUE = #VÆRDI! +REF = #REFERENCE! +NAME = #NAVN? +NUM +NA = #I/T diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions index d02aa2ec..6260760b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/da/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Dansk (Danish) ## +############################################################ ## -## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner +## Kubefunktioner (Cube Functions) ## -GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport - +CUBEKPIMEMBER = KUBE.KPI.MEDLEM +CUBEMEMBER = KUBEMEDLEM +CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB +CUBERANKEDMEMBER = KUBERANGERET.MEDLEM +CUBESET = KUBESÆT +CUBESETCOUNT = KUBESÆT.ANTAL +CUBEVALUE = KUBEVÆRDI ## -## Cube functions Kubefunktioner +## Databasefunktioner (Database Functions) ## -CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer. -CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben. -CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet. -CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever. -CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel. -CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt. -CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube. - +DAVERAGE = DMIDDEL +DCOUNT = DTÆL +DCOUNTA = DTÆLV +DGET = DHENT +DMAX = DMAKS +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAFV +DSTDEVP = DSTDAFVP +DSUM = DSUM +DVAR = DVARIANS +DVARP = DVARIANSP ## -## Database functions Databasefunktioner +## Dato- og klokkeslætfunktioner (Date & Time Functions) ## -DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter -DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database -DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database -DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database -DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter -DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter -DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database -DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter -DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter -DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne -DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter -DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter - +DATE = DATO +DATEDIF = DATO.FORSKEL +DATESTRING = DATOSTRENG +DATEVALUE = DATOVÆRDI +DAY = DAG +DAYS = DAGE +DAYS360 = DAGE360 +EDATE = EDATO +EOMONTH = SLUT.PÅ.MÅNED +HOUR = TIME +ISOWEEKNUM = ISOUGE.NR +MINUTE = MINUT +MONTH = MÅNED +NETWORKDAYS = ANTAL.ARBEJDSDAGE +NETWORKDAYS.INTL = ANTAL.ARBEJDSDAGE.INTL +NOW = NU +SECOND = SEKUND +THAIDAYOFWEEK = THAILANDSKUGEDAG +THAIMONTHOFYEAR = THAILANDSKMÅNED +THAIYEAR = THAILANDSKÅR +TIME = TID +TIMEVALUE = TIDSVÆRDI +TODAY = IDAG +WEEKDAY = UGEDAG +WEEKNUM = UGE.NR +WORKDAY = ARBEJDSDAG +WORKDAY.INTL = ARBEJDSDAG.INTL +YEAR = ÅR +YEARFRAC = ÅR.BRØK ## -## Date and time functions Dato- og klokkeslætsfunktioner +## Tekniske funktioner (Engineering Functions) ## -DATE = DATO ## Returnerer serienummeret for en bestemt dato -DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer -DAY = DAG ## Konverterer et serienummer til en dag i måneden -DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage -EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen -EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder -HOUR = TIME ## Konverterer et serienummer til en time -MINUTE = MINUT ## Konverterer et serienummer til et minut -MONTH = MÅNED ## Konverterer et serienummer til en måned -NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer -NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt -SECOND = SEKUND ## Konverterer et serienummer til et sekund -TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt -TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer -TODAY = IDAG ## Returnerer serienummeret for dags dato -WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag -WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året -WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage -YEAR = ÅR ## Konverterer et serienummer til et år -YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.TIL.DEC +BIN2HEX = BIN.TIL.HEX +BIN2OCT = BIN.TIL.OKT +BITAND = BITOG +BITLSHIFT = BITLSKIFT +BITOR = BITELLER +BITRSHIFT = BITRSKIFT +BITXOR = BITXELLER +COMPLEX = KOMPLEKS +CONVERT = KONVERTER +DEC2BIN = DEC.TIL.BIN +DEC2HEX = DEC.TIL.HEX +DEC2OCT = DEC.TIL.OKT +DELTA = DELTA +ERF = FEJLFUNK +ERF.PRECISE = ERF.PRECISE +ERFC = FEJLFUNK.KOMP +ERFC.PRECISE = ERFC.PRECISE +GESTEP = GETRIN +HEX2BIN = HEX.TIL.BIN +HEX2DEC = HEX.TIL.DEC +HEX2OCT = HEX.TIL.OKT +IMABS = IMAGABS +IMAGINARY = IMAGINÆR +IMARGUMENT = IMAGARGUMENT +IMCONJUGATE = IMAGKONJUGERE +IMCOS = IMAGCOS +IMCOSH = IMAGCOSH +IMCOT = IMAGCOT +IMCSC = IMAGCSC +IMCSCH = IMAGCSCH +IMDIV = IMAGDIV +IMEXP = IMAGEKSP +IMLN = IMAGLN +IMLOG10 = IMAGLOG10 +IMLOG2 = IMAGLOG2 +IMPOWER = IMAGPOTENS +IMPRODUCT = IMAGPRODUKT +IMREAL = IMAGREELT +IMSEC = IMAGSEC +IMSECH = IMAGSECH +IMSIN = IMAGSIN +IMSINH = IMAGSINH +IMSQRT = IMAGKVROD +IMSUB = IMAGSUB +IMSUM = IMAGSUM +IMTAN = IMAGTAN +OCT2BIN = OKT.TIL.BIN +OCT2DEC = OKT.TIL.DEC +OCT2HEX = OKT.TIL.HEX ## -## Engineering functions Tekniske funktioner +## Finansielle funktioner (Financial Functions) ## -BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x) -BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x) -BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x) -BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x) -BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal -BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal -BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal. -COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal -CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden -DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal -DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal -DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal -DELTA = DELTA ## Tester, om to værdier er ens -ERF = FEJLFUNK ## Returner fejlfunktionen -ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion -GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi -HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal -HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal -HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal -IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal -IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal -IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer -IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal -IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus -IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal -IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion -IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme -IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme) -IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme) -IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens -IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal -IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal -IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus -IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod -IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal -IMSUM = IMAGSUM ## Returnerer summen af komplekse tal -OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal -OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal -OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal - +ACCRINT = PÅLØBRENTE +ACCRINTM = PÅLØBRENTE.UDLØB +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPONDAGE.SA +COUPDAYS = KUPONDAGE.A +COUPDAYSNC = KUPONDAGE.ANK +COUPNCD = KUPONDAG.NÆSTE +COUPNUM = KUPONBETALINGER +COUPPCD = KUPONDAG.FORRIGE +CUMIPMT = AKKUM.RENTE +CUMPRINC = AKKUM.HOVEDSTOL +DB = DB +DDB = DSA +DISC = DISKONTO +DOLLARDE = KR.DECIMAL +DOLLARFR = KR.BRØK +DURATION = VARIGHED +EFFECT = EFFEKTIV.RENTE +FV = FV +FVSCHEDULE = FVTABEL +INTRATE = RENTEFOD +IPMT = R.YDELSE +IRR = IA +ISPMT = ISPMT +MDURATION = MVARIGHED +MIRR = MIA +NOMINAL = NOMINEL +NPER = NPER +NPV = NUTIDSVÆRDI +ODDFPRICE = ULIGE.KURS.PÅLYDENDE +ODDFYIELD = ULIGE.FØRSTE.AFKAST +ODDLPRICE = ULIGE.SIDSTE.KURS +ODDLYIELD = ULIGE.SIDSTE.AFKAST +PDURATION = PVARIGHED +PMT = YDELSE +PPMT = H.YDELSE +PRICE = KURS +PRICEDISC = KURS.DISKONTO +PRICEMAT = KURS.UDLØB +PV = NV +RATE = RENTE +RECEIVED = MODTAGET.VED.UDLØB +RRI = RRI +SLN = LA +SYD = ÅRSAFSKRIVNING +TBILLEQ = STATSOBLIGATION +TBILLPRICE = STATSOBLIGATION.KURS +TBILLYIELD = STATSOBLIGATION.AFKAST +VDB = VSA +XIRR = INTERN.RENTE +XNPV = NETTO.NUTIDSVÆRDI +YIELD = AFKAST +YIELDDISC = AFKAST.DISKONTO +YIELDMAT = AFKAST.UDLØBSDATO ## -## Financial functions Finansielle funktioner +## Informationsfunktioner (Information Functions) ## -ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger -ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb -AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient -AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode -COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen -COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen -COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen -COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen -COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen -COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen -CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder -CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder -DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden -DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver -DISC = DISKONTO ## Returnerer et værdipapirs diskonto -DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal -DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk -DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger -EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente -FV = FV ## Returnerer fremtidsværdien af en investering -FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser -INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir -IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode -IRR = IA ## Returnerer den interne rente for en række pengestrømme -ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode -MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100 -MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente -NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente -NPER = NPER ## Returnerer antallet af perioder for en investering -NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats -ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode -ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode -ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode -ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode -PMT = YDELSE ## Returnerer renten fra en investering for en given periode -PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode -PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger -PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir -PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb -PV = NV ## Returnerer den nuværende værdi af en investering -RATE = RENTE ## Returnerer renten i hver periode for en annuitet -RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir -SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode -SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode -TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation -TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation -TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation -VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden -XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske -XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske -YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger -YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation -YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb - +CELL = CELLE +ERROR.TYPE = FEJLTYPE +INFO = INFO +ISBLANK = ER.TOM +ISERR = ER.FJL +ISERROR = ER.FEJL +ISEVEN = ER.LIGE +ISFORMULA = ER.FORMEL +ISLOGICAL = ER.LOGISK +ISNA = ER.IKKE.TILGÆNGELIG +ISNONTEXT = ER.IKKE.TEKST +ISNUMBER = ER.TAL +ISODD = ER.ULIGE +ISREF = ER.REFERENCE +ISTEXT = ER.TEKST +N = TAL +NA = IKKE.TILGÆNGELIG +SHEET = ARK +SHEETS = ARK.FLERE +TYPE = VÆRDITYPE ## -## Information functions Informationsfunktioner +## Logiske funktioner (Logical Functions) ## -CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle -ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype -INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø -ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom -ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T -ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi -ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige -ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi -ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T -ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst -ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal -ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige -ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference -ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst -N = TAL ## Returnerer en værdi konverteret til et tal -NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T -TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi - +AND = OG +FALSE = FALSK +IF = HVIS +IFERROR = HVIS.FEJL +IFNA = HVISIT +IFS = HVISER +NOT = IKKE +OR = ELLER +SWITCH = SKIFT +TRUE = SAND +XOR = XELLER ## -## Logical functions Logiske funktioner +## Opslags- og referencefunktioner (Lookup & Reference Functions) ## -AND = OG ## Returnerer SAND, hvis alle argumenterne er sande -FALSE = FALSK ## Returnerer den logiske værdi FALSK -IF = HVIS ## Angiver en logisk test, der skal udføres -IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen -NOT = IKKE ## Vender argumentets logik om -OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt -TRUE = SAND ## Returnerer den logiske værdi SAND - +ADDRESS = ADRESSE +AREAS = OMRÅDER +CHOOSE = VÆLG +COLUMN = KOLONNE +COLUMNS = KOLONNER +FORMULATEXT = FORMELTEKST +GETPIVOTDATA = GETPIVOTDATA +HLOOKUP = VOPSLAG +HYPERLINK = HYPERLINK +INDEX = INDEKS +INDIRECT = INDIREKTE +LOOKUP = SLÅ.OP +MATCH = SAMMENLIGN +OFFSET = FORSKYDNING +ROW = RÆKKE +ROWS = RÆKKER +RTD = RTD +TRANSPOSE = TRANSPONER +VLOOKUP = LOPSLAG ## -## Lookup and reference functions Opslags- og referencefunktioner +## Matematiske og trigonometriske funktioner (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark -AREAS = OMRÅDER ## Returnerer antallet af områder i en reference -CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier -COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference -COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference -HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle -HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet -INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix -INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi -LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix -MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix -OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference -ROW = RÆKKE ## Returnerer rækkenummeret for en reference -ROWS = RÆKKER ## Returnerer antallet af rækker i en reference -RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).) -TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix -VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = SAMLING +ARABIC = ARABISK +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = BASIS +CEILING.MATH = LOFT.MAT +CEILING.PRECISE = LOFT.PRECISE +COMBIN = KOMBIN +COMBINA = KOMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.LOFT +EVEN = LIGE +EXP = EKSP +FACT = FAKULTET +FACTDOUBLE = DOBBELT.FAKULTET +FLOOR.MATH = AFRUND.BUND.MAT +FLOOR.PRECISE = AFRUND.GULV.PRECISE +GCD = STØRSTE.FÆLLES.DIVISOR +INT = HELTAL +ISO.CEILING = ISO.LOFT +LCM = MINDSTE.FÆLLES.MULTIPLUM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERT +MMULT = MPRODUKT +MOD = REST +MROUND = MAFRUND +MULTINOMIAL = MULTINOMIAL +MUNIT = MENHED +ODD = ULIGE +PI = PI +POWER = POTENS +PRODUCT = PRODUKT +QUOTIENT = KVOTIENT +RADIANS = RADIANER +RAND = SLUMP +RANDBETWEEN = SLUMPMELLEM +ROMAN = ROMERTAL +ROUND = AFRUND +ROUNDBAHTDOWN = RUNDBAHTNED +ROUNDBAHTUP = RUNDBAHTOP +ROUNDDOWN = RUND.NED +ROUNDUP = RUND.OP +SEC = SEC +SECH = SECH +SERIESSUM = SERIESUM +SIGN = FORTEGN +SIN = SIN +SINH = SINH +SQRT = KVROD +SQRTPI = KVRODPI +SUBTOTAL = SUBTOTAL +SUM = SUM +SUMIF = SUM.HVIS +SUMIFS = SUM.HVISER +SUMPRODUCT = SUMPRODUKT +SUMSQ = SUMKV +SUMX2MY2 = SUMX2MY2 +SUMX2PY2 = SUMX2PY2 +SUMXMY2 = SUMXMY2 +TAN = TAN +TANH = TANH +TRUNC = AFKORT ## -## Math and trigonometry functions Matematiske og trigonometriske funktioner +## Statistiske funktioner (Statistical Functions) ## -ABS = ABS ## Returnerer den absolutte værdi af et tal -ACOS = ARCCOS ## Returnerer et tals arcus cosinus -ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal -ASIN = ARCSIN ## Returnerer et tals arcus sinus -ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal -ATAN = ARCTAN ## Returnerer et tals arcus tangens -ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens -ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens -CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning -COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter -COS = COS ## Returnerer et tals cosinus -COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal -DEGREES = GRADER ## Konverterer radianer til grader -EVEN = LIGE ## Runder et tal op til nærmeste lige heltal -EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal -FACT = FAKULTET ## Returnerer et tals fakultet -FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet -FLOOR = AFRUND.GULV ## Runder et tal ned mod nul -GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor -INT = HELTAL ## Nedrunder et tal til det nærmeste heltal -LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum -LN = LN ## Returnerer et tals naturlige logaritme -LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal -LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal -MDETERM = MDETERM ## Returnerer determinanten for en matrix -MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix -MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer -MOD = REST ## Returnerer restværdien fra division -MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum -MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt -ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal -PI = PI ## Returnerer værdien af pi -POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens -PRODUCT = PRODUKT ## Multiplicerer argumenterne -QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division -RADIANS = RADIANER ## Konverterer grader til radianer -RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1 -RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives -ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst -ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler -ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul -ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul) -SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel -SIGN = FORTEGN ## Returnerer et tals fortegn -SIN = SIN ## Returnerer en given vinkels sinusværdi -SINH = SINH ## Returnerer den hyperbolske sinus af et tal -SQRT = KVROD ## Returnerer en positiv kvadratrod -SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;) -SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database -SUM = SUM ## Lægger argumenterne sammen -SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium. -SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier. -SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter -SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater -SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer -SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer -SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer -TAN = TAN ## Returnerer et tals tangens -TANH = TANH ## Returnerer et tals hyperbolske tangens -TRUNC = AFKORT ## Afkorter et tal til et heltal - +AVEDEV = MAD +AVERAGE = MIDDEL +AVERAGEA = MIDDELV +AVERAGEIF = MIDDEL.HVIS +AVERAGEIFS = MIDDEL.HVISER +BETA.DIST = BETA.FORDELING +BETA.INV = BETA.INV +BINOM.DIST = BINOMIAL.FORDELING +BINOM.DIST.RANGE = BINOMIAL.DIST.INTERVAL +BINOM.INV = BINOMIAL.INV +CHISQ.DIST = CHI2.FORDELING +CHISQ.DIST.RT = CHI2.FORD.RT +CHISQ.INV = CHI2.INV +CHISQ.INV.RT = CHI2.INV.RT +CHISQ.TEST = CHI2.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENST +CORREL = KORRELATION +COUNT = TÆL +COUNTA = TÆLV +COUNTBLANK = ANTAL.BLANKE +COUNTIF = TÆL.HVIS +COUNTIFS = TÆL.HVISER +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = SAK +EXPON.DIST = EKSP.FORDELING +F.DIST = F.FORDELING +F.DIST.RT = F.FORDELING.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SÆSONUDSVING +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEÆR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FORDELING +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRECISE +GAUSS = GAUSS +GEOMEAN = GEOMIDDELVÆRDI +GROWTH = FORØGELSE +HARMEAN = HARMIDDELVÆRDI +HYPGEOM.DIST = HYPGEO.FORDELING +INTERCEPT = SKÆRING +KURT = TOPSTEJL +LARGE = STØRSTE +LINEST = LINREGR +LOGEST = LOGREGR +LOGNORM.DIST = LOGNORM.FORDELING +LOGNORM.INV = LOGNORM.INV +MAX = MAKS +MAXA = MAKSV +MAXIFS = MAKSHVISER +MEDIAN = MEDIAN +MIN = MIN +MINA = MINV +MINIFS = MINHVISER +MODE.MULT = HYPPIGST.FLERE +MODE.SNGL = HYPPIGST.ENKELT +NEGBINOM.DIST = NEGBINOM.FORDELING +NORM.DIST = NORMAL.FORDELING +NORM.INV = NORM.INV +NORM.S.DIST = STANDARD.NORM.FORDELING +NORM.S.INV = STANDARD.NORM.INV +PEARSON = PEARSON +PERCENTILE.EXC = FRAKTIL.UDELAD +PERCENTILE.INC = FRAKTIL.MEDTAG +PERCENTRANK.EXC = PROCENTPLADS.UDELAD +PERCENTRANK.INC = PROCENTPLADS.MEDTAG +PERMUT = PERMUT +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.FORDELING +PROB = SANDSYNLIGHED +QUARTILE.EXC = KVARTIL.UDELAD +QUARTILE.INC = KVARTIL.MEDTAG +RANK.AVG = PLADS.GNSN +RANK.EQ = PLADS.LIGE +RSQ = FORKLARINGSGRAD +SKEW = SKÆVHED +SKEW.P = SKÆVHED.P +SLOPE = STIGNING +SMALL = MINDSTE +STANDARDIZE = STANDARDISER +STDEV.P = STDAFV.P +STDEV.S = STDAFV.S +STDEVA = STDAFVV +STDEVPA = STDAFVPV +STEYX = STFYX +T.DIST = T.FORDELING +T.DIST.2T = T.FORDELING.2T +T.DIST.RT = T.FORDELING.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TENDENS +TRIMMEAN = TRIMMIDDELVÆRDI +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARIANSV +VARPA = VARIANSPV +WEIBULL.DIST = WEIBULL.FORDELING +Z.TEST = Z.TEST ## -## Statistical functions Statistiske funktioner +## Tekstfunktioner (Text Functions) ## -AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi -AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne -AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier -AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område -AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier. -BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion -BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling -BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen -CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling -CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling -CHITEST = CHITEST ## Foretager en test for uafhængighed -CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population -CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt -COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter -COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter -COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område -COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område -COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område -COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler -CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien. -DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien -EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen -FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen -FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen -FISHER = FISHER ## Returnerer Fisher-transformationen -FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation -FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens -FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor -FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians -GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen -GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen -GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x) -GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit -GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens -HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit -HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling -INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression -KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel -LARGE = STOR ## Returnerer den k'te største værdi i et datasæt -LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens -LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens -LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen -LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen -MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter. -MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier -MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal -MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter. -MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier -MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt -NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling -NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen -NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen -NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen -NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen -PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient -PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet -PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt -PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter -POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling -PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden -QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt -RANK = PLADS ## Returnerer rangen for et tal på en liste med tal -RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression -SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel -SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression -SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet -STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi -STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve -STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier -STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population -STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier -STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression -TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling -TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling -TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens -TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet -TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test -VAR = VARIANS ## Beregner variansen på basis af en prøve -VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier -VARP = VARIANSP ## Beregner variansen på basis af hele populationen -VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier -WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen -ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test +BAHTTEXT = BAHTTEKST +CHAR = TEGN +CLEAN = RENS +CODE = KODE +CONCAT = CONCAT +DOLLAR = KR +EXACT = EKSAKT +FIND = FIND +FIXED = FAST +ISTHAIDIGIT = ERTHAILANDSKCIFFER +LEFT = VENSTRE +LEN = LÆNGDE +LOWER = SMÅ.BOGSTAVER +MID = MIDT +NUMBERSTRING = TALSTRENG +NUMBERVALUE = TALVÆRDI +PHONETIC = FONETISK +PROPER = STORT.FORBOGSTAV +REPLACE = ERSTAT +REPT = GENTAG +RIGHT = HØJRE +SEARCH = SØG +SUBSTITUTE = UDSKIFT +T = T +TEXT = TEKST +TEXTJOIN = TEKST.KOMBINER +THAIDIGIT = THAILANDSKCIFFER +THAINUMSOUND = THAILANDSKNUMLYD +THAINUMSTRING = THAILANDSKNUMSTRENG +THAISTRINGLENGTH = THAILANDSKSTRENGLÆNGDE +TRIM = FJERN.OVERFLØDIGE.BLANKE +UNICHAR = UNICHAR +UNICODE = UNICODE +UPPER = STORE.BOGSTAVER +VALUE = VÆRDI +## +## Webfunktioner (Web Functions) +## +ENCODEURL = KODNINGSURL +FILTERXML = FILTRERXML +WEBSERVICE = WEBTJENESTE ## -## Text functions Tekstfunktioner +## Kompatibilitetsfunktioner (Compatibility Functions) ## -ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte) -BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht) -CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret -CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst -CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng -CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement -DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner) -EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske -FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) -FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) -FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler -JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte) -LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi -LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi -LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng -LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng -LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver -MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition -MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition -PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng -PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav -REPLACE = ERSTAT ## Erstatter tegn i tekst -REPLACEB = ERSTATB ## Erstatter tegn i tekst -REPT = GENTAG ## Gentager tekst et givet antal gange -RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi -RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi -SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) -SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) -SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng -T = T ## Konverterer argumenterne til tekst -TEXT = TEKST ## Formaterer et tal og konverterer det til tekst -TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst -UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver -VALUE = VÆRDI ## Konverterer et tekstargument til et tal +BETADIST = BETAFORDELING +BETAINV = BETAINV +BINOMDIST = BINOMIALFORDELING +CEILING = AFRUND.LOFT +CHIDIST = CHIFORDELING +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = SAMMENKÆDNING +CONFIDENCE = KONFIDENSINTERVAL +COVAR = KOVARIANS +CRITBINOM = KRITBINOM +EXPONDIST = EKSPFORDELING +FDIST = FFORDELING +FINV = FINV +FLOOR = AFRUND.GULV +FORECAST = PROGNOSE +FTEST = FTEST +GAMMADIST = GAMMAFORDELING +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOFORDELING +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFORDELING +MODE = HYPPIGST +NEGBINOMDIST = NEGBINOMFORDELING +NORMDIST = NORMFORDELING +NORMINV = NORMINV +NORMSDIST = STANDARDNORMFORDELING +NORMSINV = STANDARDNORMINV +PERCENTILE = FRAKTIL +PERCENTRANK = PROCENTPLADS +POISSON = POISSON +QUARTILE = KVARTIL +RANK = PLADS +STDEV = STDAFV +STDEVP = STDAFVP +TDIST = TFORDELING +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config index 9751c4b6..4ca2b82b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Deutsch (German) ## -## (For future use) -## -currencySymbol = € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #WERT! -REF = #BEZUG! -NAME = #NAME? -NUM = #ZAHL! -NA = #NV +NULL +DIV0 +VALUE = #WERT! +REF = #BEZUG! +NAME +NUM = #ZAHL! +NA = #NV diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions index 01df42f6..331232f7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/de/functions @@ -1,416 +1,533 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Deutsch (German) ## +############################################################ ## -## Add-in and Automation functions Add-In- und Automatisierungsfunktionen +## Cubefunktionen (Cube Functions) ## -GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben. - +CUBEKPIMEMBER = CUBEKPIELEMENT +CUBEMEMBER = CUBEELEMENT +CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT +CUBERANKEDMEMBER = CUBERANGELEMENT +CUBESET = CUBEMENGE +CUBESETCOUNT = CUBEMENGENANZAHL +CUBEVALUE = CUBEWERT ## -## Cube functions Cubefunktionen +## Datenbankfunktionen (Database Functions) ## -CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann. -CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist. -CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben. -CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer. -CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt. -CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück. -CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück. - +DAVERAGE = DBMITTELWERT +DCOUNT = DBANZAHL +DCOUNTA = DBANZAHL2 +DGET = DBAUSZUG +DMAX = DBMAX +DMIN = DBMIN +DPRODUCT = DBPRODUKT +DSTDEV = DBSTDABW +DSTDEVP = DBSTDABWN +DSUM = DBSUMME +DVAR = DBVARIANZ +DVARP = DBVARIANZEN ## -## Database functions Datenbankfunktionen +## Datums- und Uhrzeitfunktionen (Date & Time Functions) ## -DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück -DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank -DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank -DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht -DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück -DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück -DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen -DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen -DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge -DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen -DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge -DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge - +DATE = DATUM +DATEVALUE = DATWERT +DAY = TAG +DAYS = TAGE +DAYS360 = TAGE360 +EDATE = EDATUM +EOMONTH = MONATSENDE +HOUR = STUNDE +ISOWEEKNUM = ISOKALENDERWOCHE +MINUTE = MINUTE +MONTH = MONAT +NETWORKDAYS = NETTOARBEITSTAGE +NETWORKDAYS.INTL = NETTOARBEITSTAGE.INTL +NOW = JETZT +SECOND = SEKUNDE +THAIDAYOFWEEK = THAIWOCHENTAG +THAIMONTHOFYEAR = THAIMONATDESJAHRES +THAIYEAR = THAIJAHR +TIME = ZEIT +TIMEVALUE = ZEITWERT +TODAY = HEUTE +WEEKDAY = WOCHENTAG +WEEKNUM = KALENDERWOCHE +WORKDAY = ARBEITSTAG +WORKDAY.INTL = ARBEITSTAG.INTL +YEAR = JAHR +YEARFRAC = BRTEILJAHRE ## -## Date and time functions Datums- und Zeitfunktionen +## Technische Funktionen (Engineering Functions) ## -DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück -DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um -DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um -DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat -EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt -EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück -HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um -MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um -MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um -NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück -NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück -SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um -TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück -TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um -TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück -WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um -WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt -WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück -YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um -YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BININDEZ +BIN2HEX = BININHEX +BIN2OCT = BININOKT +BITAND = BITUND +BITLSHIFT = BITLVERSCHIEB +BITOR = BITODER +BITRSHIFT = BITRVERSCHIEB +BITXOR = BITXODER +COMPLEX = KOMPLEXE +CONVERT = UMWANDELN +DEC2BIN = DEZINBIN +DEC2HEX = DEZINHEX +DEC2OCT = DEZINOKT +DELTA = DELTA +ERF = GAUSSFEHLER +ERF.PRECISE = GAUSSF.GENAU +ERFC = GAUSSFKOMPL +ERFC.PRECISE = GAUSSFKOMPL.GENAU +GESTEP = GGANZZAHL +HEX2BIN = HEXINBIN +HEX2DEC = HEXINDEZ +HEX2OCT = HEXINOKT +IMABS = IMABS +IMAGINARY = IMAGINÄRTEIL +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGIERTE +IMCOS = IMCOS +IMCOSH = IMCOSHYP +IMCOT = IMCOT +IMCSC = IMCOSEC +IMCSCH = IMCOSECHYP +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMAPOTENZ +IMPRODUCT = IMPRODUKT +IMREAL = IMREALTEIL +IMSEC = IMSEC +IMSECH = IMSECHYP +IMSIN = IMSIN +IMSINH = IMSINHYP +IMSQRT = IMWURZEL +IMSUB = IMSUB +IMSUM = IMSUMME +IMTAN = IMTAN +OCT2BIN = OKTINBIN +OCT2DEC = OKTINDEZ +OCT2HEX = OKTINHEX ## -## Engineering functions Konstruktionsfunktionen +## Finanzmathematische Funktionen (Financial Functions) ## -BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück -BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück -BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück -BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück -BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um -BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um -BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um -COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um -CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um -DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um -DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um -DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um -DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind -ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück -ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück -GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist -HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um -HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um -HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um -IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück -IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück -IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird -IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück -IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück -IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück -IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück -IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück -IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück -IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück -IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl -IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück -IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück -IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück -IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück -IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück -IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück -OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um -OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um -OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um - +ACCRINT = AUFGELZINS +ACCRINTM = AUFGELZINSF +AMORDEGRC = AMORDEGRK +AMORLINC = AMORLINEARK +COUPDAYBS = ZINSTERMTAGVA +COUPDAYS = ZINSTERMTAGE +COUPDAYSNC = ZINSTERMTAGNZ +COUPNCD = ZINSTERMNZ +COUPNUM = ZINSTERMZAHL +COUPPCD = ZINSTERMVZ +CUMIPMT = KUMZINSZ +CUMPRINC = KUMKAPITAL +DB = GDA2 +DDB = GDA +DISC = DISAGIO +DOLLARDE = NOTIERUNGDEZ +DOLLARFR = NOTIERUNGBRU +DURATION = DURATION +EFFECT = EFFEKTIV +FV = ZW +FVSCHEDULE = ZW2 +INTRATE = ZINSSATZ +IPMT = ZINSZ +IRR = IKV +ISPMT = ISPMT +MDURATION = MDURATION +MIRR = QIKV +NOMINAL = NOMINAL +NPER = ZZR +NPV = NBW +ODDFPRICE = UNREGER.KURS +ODDFYIELD = UNREGER.REND +ODDLPRICE = UNREGLE.KURS +ODDLYIELD = UNREGLE.REND +PDURATION = PDURATION +PMT = RMZ +PPMT = KAPZ +PRICE = KURS +PRICEDISC = KURSDISAGIO +PRICEMAT = KURSFÄLLIG +PV = BW +RATE = ZINS +RECEIVED = AUSZAHLUNG +RRI = ZSATZINVEST +SLN = LIA +SYD = DIA +TBILLEQ = TBILLÄQUIV +TBILLPRICE = TBILLKURS +TBILLYIELD = TBILLRENDITE +VDB = VDB +XIRR = XINTZINSFUSS +XNPV = XKAPITALWERT +YIELD = RENDITE +YIELDDISC = RENDITEDIS +YIELDMAT = RENDITEFÄLL ## -## Financial functions Finanzmathematische Funktionen +## Informationsfunktionen (Information Functions) ## -ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück -ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden -AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück -AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück -COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück -COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt -COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück -COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück -COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück -COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück -CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind -CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist -DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück -DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück -DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück -DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um -DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um -DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück -EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück -FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück -FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück -INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück -IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück -IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück -ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen -MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück -MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden -NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück -NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück -NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück -ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück -ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück -ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück -ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück -PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück -PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück -PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt -PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück -PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt -PV = BW ## Gibt den Barwert einer Investition zurück -RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück -RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück -SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück -SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück -TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück -TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück -TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück -VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück -XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück -XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück -YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt -YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück -YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt - +CELL = ZELLE +ERROR.TYPE = FEHLER.TYP +INFO = INFO +ISBLANK = ISTLEER +ISERR = ISTFEHL +ISERROR = ISTFEHLER +ISEVEN = ISTGERADE +ISFORMULA = ISTFORMEL +ISLOGICAL = ISTLOG +ISNA = ISTNV +ISNONTEXT = ISTKTEXT +ISNUMBER = ISTZAHL +ISODD = ISTUNGERADE +ISREF = ISTBEZUG +ISTEXT = ISTTEXT +N = N +NA = NV +SHEET = BLATT +SHEETS = BLÄTTER +TYPE = TYP ## -## Information functions Informationsfunktionen +## Logische Funktionen (Logical Functions) ## -CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück -ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht -INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück -ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist -ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist -ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist -ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt -ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist -ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist -ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält -ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist -ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt -ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist -ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält -N = N ## Gibt den in eine Zahl umgewandelten Wert zurück -NA = NV ## Gibt den Fehlerwert #NV zurück -TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt - +AND = UND +FALSE = FALSCH +IF = WENN +IFERROR = WENNFEHLER +IFNA = WENNNV +IFS = WENNS +NOT = NICHT +OR = ODER +SWITCH = ERSTERWERT +TRUE = WAHR +XOR = XODER ## -## Logical functions Logische Funktionen +## Nachschlage- und Verweisfunktionen (Lookup & Reference Functions) ## -AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind -FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück -IF = WENN ## Gibt einen logischen Test zum Ausführen an -IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben -NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um -OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist -TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück - +ADDRESS = ADRESSE +AREAS = BEREICHE +CHOOSE = WAHL +COLUMN = SPALTE +COLUMNS = SPALTEN +FORMULATEXT = FORMELTEXT +GETPIVOTDATA = PIVOTDATENZUORDNEN +HLOOKUP = WVERWEIS +HYPERLINK = HYPERLINK +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = VERWEIS +MATCH = VERGLEICH +OFFSET = BEREICH.VERSCHIEBEN +ROW = ZEILE +ROWS = ZEILEN +RTD = RTD +TRANSPOSE = MTRANS +VLOOKUP = SVERWEIS ## -## Lookup and reference functions Nachschlage- und Verweisfunktionen +## Mathematische und trigonometrische Funktionen (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück -AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück -CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus -COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück -COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück -HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück -HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird -INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen -INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird -LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix -MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix -OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück -ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück -ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück -RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt -TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück -VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben - +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSHYP +ACOT = ARCCOT +ACOTH = ARCCOTHYP +AGGREGATE = AGGREGAT +ARABIC = ARABISCH +ASIN = ARCSIN +ASINH = ARCSINHYP +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANHYP +BASE = BASIS +CEILING.MATH = OBERGRENZE.MATHEMATIK +CEILING.PRECISE = OBERGRENZE.GENAU +COMBIN = KOMBINATIONEN +COMBINA = KOMBINATIONEN2 +COS = COS +COSH = COSHYP +COT = COT +COTH = COTHYP +CSC = COSEC +CSCH = COSECHYP +DECIMAL = DEZIMAL +DEGREES = GRAD +ECMA.CEILING = ECMA.OBERGRENZE +EVEN = GERADE +EXP = EXP +FACT = FAKULTÄT +FACTDOUBLE = ZWEIFAKULTÄT +FLOOR.MATH = UNTERGRENZE.MATHEMATIK +FLOOR.PRECISE = UNTERGRENZE.GENAU +GCD = GGT +INT = GANZZAHL +ISO.CEILING = ISO.OBERGRENZE +LCM = KGV +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDET +MINVERSE = MINV +MMULT = MMULT +MOD = REST +MROUND = VRUNDEN +MULTINOMIAL = POLYNOMIAL +MUNIT = MEINHEIT +ODD = UNGERADE +PI = PI +POWER = POTENZ +PRODUCT = PRODUKT +QUOTIENT = QUOTIENT +RADIANS = BOGENMASS +RAND = ZUFALLSZAHL +RANDBETWEEN = ZUFALLSBEREICH +ROMAN = RÖMISCH +ROUND = RUNDEN +ROUNDBAHTDOWN = RUNDBAHTNED +ROUNDBAHTUP = BAHTAUFRUNDEN +ROUNDDOWN = ABRUNDEN +ROUNDUP = AUFRUNDEN +SEC = SEC +SECH = SECHYP +SERIESSUM = POTENZREIHE +SIGN = VORZEICHEN +SIN = SIN +SINH = SINHYP +SQRT = WURZEL +SQRTPI = WURZELPI +SUBTOTAL = TEILERGEBNIS +SUM = SUMME +SUMIF = SUMMEWENN +SUMIFS = SUMMEWENNS +SUMPRODUCT = SUMMENPRODUKT +SUMSQ = QUADRATESUMME +SUMX2MY2 = SUMMEX2MY2 +SUMX2PY2 = SUMMEX2PY2 +SUMXMY2 = SUMMEXMY2 +TAN = TAN +TANH = TANHYP +TRUNC = KÜRZEN ## -## Math and trigonometry functions Mathematische und trigonometrische Funktionen +## Statistische Funktionen (Statistical Functions) ## -ABS = ABS ## Gibt den Absolutwert einer Zahl zurück -ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück -ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück -ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück -ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück -ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück -ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück -ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück -CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt -COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück -COS = COS ## Gibt den Kosinus einer Zahl zurück -COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück -DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um -EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf -EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl -FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück -FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück -FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab -GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück -INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab -LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück -LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück -LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück -LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück -MDETERM = MDET ## Gibt die Determinante einer Matrix zurück -MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück -MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück -MOD = REST ## Gibt den Rest einer Division zurück -MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück -MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück -ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf -PI = PI ## Gibt den Wert Pi zurück -POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück -PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente -QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück -RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um -RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück -RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück -ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um -ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen -ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab -ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf -SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück -SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück -SIN = SIN ## Gibt den Sinus einer Zahl zurück -SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück -SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück -SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück -SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück -SUM = SUMME ## Addiert die zugehörigen Argumente -SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen -SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt -SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück -SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück -SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück -SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück -SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück -TAN = TAN ## Gibt den Tangens einer Zahl zurück -TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück -TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück - +AVEDEV = MITTELABW +AVERAGE = MITTELWERT +AVERAGEA = MITTELWERTA +AVERAGEIF = MITTELWERTWENN +AVERAGEIFS = MITTELWERTWENNS +BETA.DIST = BETA.VERT +BETA.INV = BETA.INV +BINOM.DIST = BINOM.VERT +BINOM.DIST.RANGE = BINOM.VERT.BEREICH +BINOM.INV = BINOM.INV +CHISQ.DIST = CHIQU.VERT +CHISQ.DIST.RT = CHIQU.VERT.RE +CHISQ.INV = CHIQU.INV +CHISQ.INV.RT = CHIQU.INV.RE +CHISQ.TEST = CHIQU.TEST +CONFIDENCE.NORM = KONFIDENZ.NORM +CONFIDENCE.T = KONFIDENZ.T +CORREL = KORREL +COUNT = ANZAHL +COUNTA = ANZAHL2 +COUNTBLANK = ANZAHLLEEREZELLEN +COUNTIF = ZÄHLENWENN +COUNTIFS = ZÄHLENWENNS +COVARIANCE.P = KOVARIANZ.P +COVARIANCE.S = KOVARIANZ.S +DEVSQ = SUMQUADABW +EXPON.DIST = EXPON.VERT +F.DIST = F.VERT +F.DIST.RT = F.VERT.RE +F.INV = F.INV +F.INV.RT = F.INV.RE +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.KONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SAISONALITÄT +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEAR +FREQUENCY = HÄUFIGKEIT +GAMMA = GAMMA +GAMMA.DIST = GAMMA.VERT +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.GENAU +GAUSS = GAUSS +GEOMEAN = GEOMITTEL +GROWTH = VARIATION +HARMEAN = HARMITTEL +HYPGEOM.DIST = HYPGEOM.VERT +INTERCEPT = ACHSENABSCHNITT +KURT = KURT +LARGE = KGRÖSSTE +LINEST = RGP +LOGEST = RKP +LOGNORM.DIST = LOGNORM.VERT +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXWENNS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINWENNS +MODE.MULT = MODUS.VIELF +MODE.SNGL = MODUS.EINF +NEGBINOM.DIST = NEGBINOM.VERT +NORM.DIST = NORM.VERT +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.VERT +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = QUANTIL.EXKL +PERCENTILE.INC = QUANTIL.INKL +PERCENTRANK.EXC = QUANTILSRANG.EXKL +PERCENTRANK.INC = QUANTILSRANG.INKL +PERMUT = VARIATIONEN +PERMUTATIONA = VARIATIONEN2 +PHI = PHI +POISSON.DIST = POISSON.VERT +PROB = WAHRSCHBEREICH +QUARTILE.EXC = QUARTILE.EXKL +QUARTILE.INC = QUARTILE.INKL +RANK.AVG = RANG.MITTELW +RANK.EQ = RANG.GLEICH +RSQ = BESTIMMTHEITSMASS +SKEW = SCHIEFE +SKEW.P = SCHIEFE.P +SLOPE = STEIGUNG +SMALL = KKLEINSTE +STANDARDIZE = STANDARDISIERUNG +STDEV.P = STABW.N +STDEV.S = STABW.S +STDEVA = STABWA +STDEVPA = STABWNA +STEYX = STFEHLERYX +T.DIST = T.VERT +T.DIST.2T = T.VERT.2S +T.DIST.RT = T.VERT.RE +T.INV = T.INV +T.INV.2T = T.INV.2S +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = GESTUTZTMITTEL +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARIANZA +VARPA = VARIANZENA +WEIBULL.DIST = WEIBULL.VERT +Z.TEST = G.TEST ## -## Statistical functions Statistische Funktionen +## Textfunktionen (Text Functions) ## -AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück -AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück -AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück -AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben -AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen -BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück -BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück -BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück -CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück -CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück -CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück -CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen -CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück -COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an -COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an -COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an -COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen -COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen -COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen -CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind -DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück -EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück -FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück -FINV = FINV ## Gibt Quantile der F-Verteilung zurück -FISHER = FISHER ## Gibt die Fisher-Transformation zurück -FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück -FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt -FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück -FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück -GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück -GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück -GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x) -GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück -GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben -HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück -HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück -INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück -KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück -LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück -LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück -LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück -LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück -LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück -MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück -MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten -MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück -MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück -MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten -MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück -NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück -NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück -NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück -NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück -NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück -PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück -PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück -PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück -PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen -POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück -PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück -QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück -RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt -RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück -SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück -SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück -SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück -STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück -STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe -STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält -STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit -STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält -STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück -TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück -TINV = TINV ## Gibt Quantile der t-Verteilung zurück -TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben -TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen -TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück -VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe -VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält -VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit -VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält -WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück -ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück +BAHTTEXT = BAHTTEXT +CHAR = ZEICHEN +CLEAN = SÄUBERN +CODE = CODE +CONCAT = TEXTKETTE +DOLLAR = DM +EXACT = IDENTISCH +FIND = FINDEN +FIXED = FEST +ISTHAIDIGIT = ISTTHAIZAHLENWORT +LEFT = LINKS +LEN = LÄNGE +LOWER = KLEIN +MID = TEIL +NUMBERVALUE = ZAHLENWERT +PROPER = GROSS2 +REPLACE = ERSETZEN +REPT = WIEDERHOLEN +RIGHT = RECHTS +SEARCH = SUCHEN +SUBSTITUTE = WECHSELN +T = T +TEXT = TEXT +TEXTJOIN = TEXTVERKETTEN +THAIDIGIT = THAIZAHLENWORT +THAINUMSOUND = THAIZAHLSOUND +THAINUMSTRING = THAILANDSKNUMSTRENG +THAISTRINGLENGTH = THAIZEICHENFOLGENLÄNGE +TRIM = GLÄTTEN +UNICHAR = UNIZEICHEN +UNICODE = UNICODE +UPPER = GROSS +VALUE = WERT +## +## Webfunktionen (Web Functions) +## +ENCODEURL = URLCODIEREN +FILTERXML = XMLFILTERN +WEBSERVICE = WEBDIENST ## -## Text functions Textfunktionen +## Kompatibilitätsfunktionen (Compatibility Functions) ## -ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text -BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um -CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück -CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text -CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück -CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement -DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um -EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind -FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) -FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) -FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen -JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text -LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück -LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück -LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück -LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück -LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um -MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück -MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück -PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge -PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um -REPLACE = ERSETZEN ## Ersetzt Zeichen in Text -REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text -REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben -RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück -RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück -SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) -SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) -SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten -T = T ## Wandelt die zugehörigen Argumente in Text um -TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um -TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text -UPPER = GROSS ## Wandelt Text in Großbuchstaben um -VALUE = WERT ## Wandelt ein Textargument in eine Zahl um +BETADIST = BETAVERT +BETAINV = BETAINV +BINOMDIST = BINOMVERT +CEILING = OBERGRENZE +CHIDIST = CHIVERT +CHIINV = CHIINV +CHITEST = CHITEST +CONCATENATE = VERKETTEN +CONFIDENCE = KONFIDENZ +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXPONVERT +FDIST = FVERT +FINV = FINV +FLOOR = UNTERGRENZE +FORECAST = SCHÄTZER +FTEST = FTEST +GAMMADIST = GAMMAVERT +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMVERT +LOGINV = LOGINV +LOGNORMDIST = LOGNORMVERT +MODE = MODALWERT +NEGBINOMDIST = NEGBINOMVERT +NORMDIST = NORMVERT +NORMINV = NORMINV +NORMSDIST = STANDNORMVERT +NORMSINV = STANDNORMINV +PERCENTILE = QUANTIL +PERCENTRANK = QUANTILSRANG +POISSON = POISSON +QUARTILE = QUARTILE +RANK = RANG +STDEV = STABW +STDEVP = STABWN +TDIST = TVERT +TINV = TINV +TTEST = TTEST +VAR = VARIANZ +VARP = VARIANZEN +WEIBULL = WEIBULL +ZTEST = GTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config index 5b9b9488..fe044efa 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Español (Spanish) ## -## (For future use) -## -currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #¡NULO! -DIV0 = #¡DIV/0! -VALUE = #¡VALOR! -REF = #¡REF! -NAME = #¿NOMBRE? -NUM = #¡NÚM! -NA = #N/A +NULL = #¡NULO! +DIV0 = #¡DIV/0! +VALUE = #¡VALOR! +REF = #¡REF! +NAME = #¿NOMBRE? +NUM = #¡NUM! +NA diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions index ac1ac86a..1f9f2891 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/es/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Español (Spanish) ## +############################################################ ## -## Add-in and Automation functions Funciones de complementos y automatización +## Funciones de cubo (Cube Functions) ## -GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica. - +CUBEKPIMEMBER = MIEMBROKPICUBO +CUBEMEMBER = MIEMBROCUBO +CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO +CUBERANKEDMEMBER = MIEMBRORANGOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = RECUENTOCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Cube functions Funciones de cubo +## Funciones de base de datos (Database Functions) ## -CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización. -CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo. -CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro. -CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos. -CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel. -CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto. -CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo. - +DAVERAGE = BDPROMEDIO +DCOUNT = BDCONTAR +DCOUNTA = BDCONTARA +DGET = BDEXTRAER +DMAX = BDMAX +DMIN = BDMIN +DPRODUCT = BDPRODUCTO +DSTDEV = BDDESVEST +DSTDEVP = BDDESVESTP +DSUM = BDSUMA +DVAR = BDVAR +DVARP = BDVARP ## -## Database functions Funciones de base de datos +## Funciones de fecha y hora (Date & Time Functions) ## -DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos. -DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos. -DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos. -DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados. -DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos. -DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos. -DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados. -DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos. -DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos. -DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios. -DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos. -DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos. - +DATE = FECHA +DATEDIF = SIFECHA +DATESTRING = CADENA.FECHA +DATEVALUE = FECHANUMERO +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = FECHA.MES +EOMONTH = FIN.MES +HOUR = HORA +ISOWEEKNUM = ISO.NUM.DE.SEMANA +MINUTE = MINUTO +MONTH = MES +NETWORKDAYS = DIAS.LAB +NETWORKDAYS.INTL = DIAS.LAB.INTL +NOW = AHORA +SECOND = SEGUNDO +THAIDAYOFWEEK = DIASEMTAI +THAIMONTHOFYEAR = MESAÑOTAI +THAIYEAR = AÑOTAI +TIME = NSHORA +TIMEVALUE = HORANUMERO +TODAY = HOY +WEEKDAY = DIASEM +WEEKNUM = NUM.DE.SEMANA +WORKDAY = DIA.LAB +WORKDAY.INTL = DIA.LAB.INTL +YEAR = AÑO +YEARFRAC = FRAC.AÑO ## -## Date and time functions Funciones de fecha y hora +## Funciones de ingeniería (Engineering Functions) ## -DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada. -DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie. -DAY = DIA ## Convierte un número de serie en un valor de día del mes. -DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días. -EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial. -EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado. -HOUR = HORA ## Convierte un número de serie en un valor de hora. -MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto. -MONTH = MES ## Convierte un número de serie en un valor de mes. -NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas. -NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales. -SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo. -TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada. -TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie. -TODAY = HOY ## Devuelve el número de serie correspondiente al día actual. -WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana. -WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año. -WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables. -YEAR = AÑO ## Convierte un número de serie en un valor de año. -YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.A.DEC +BIN2HEX = BIN.A.HEX +BIN2OCT = BIN.A.OCT +BITAND = BIT.Y +BITLSHIFT = BIT.DESPLIZQDA +BITOR = BIT.O +BITRSHIFT = BIT.DESPLDCHA +BITXOR = BIT.XO +COMPLEX = COMPLEJO +CONVERT = CONVERTIR +DEC2BIN = DEC.A.BIN +DEC2HEX = DEC.A.HEX +DEC2OCT = DEC.A.OCT +DELTA = DELTA +ERF = FUN.ERROR +ERF.PRECISE = FUN.ERROR.EXACTO +ERFC = FUN.ERROR.COMPL +ERFC.PRECISE = FUN.ERROR.COMPL.EXACTO +GESTEP = MAYOR.O.IGUAL +HEX2BIN = HEX.A.BIN +HEX2DEC = HEX.A.DEC +HEX2OCT = HEX.A.OCT +IMABS = IM.ABS +IMAGINARY = IMAGINARIO +IMARGUMENT = IM.ANGULO +IMCONJUGATE = IM.CONJUGADA +IMCOS = IM.COS +IMCOSH = IM.COSH +IMCOT = IM.COT +IMCSC = IM.CSC +IMCSCH = IM.CSCH +IMDIV = IM.DIV +IMEXP = IM.EXP +IMLN = IM.LN +IMLOG10 = IM.LOG10 +IMLOG2 = IM.LOG2 +IMPOWER = IM.POT +IMPRODUCT = IM.PRODUCT +IMREAL = IM.REAL +IMSEC = IM.SEC +IMSECH = IM.SECH +IMSIN = IM.SENO +IMSINH = IM.SENOH +IMSQRT = IM.RAIZ2 +IMSUB = IM.SUSTR +IMSUM = IM.SUM +IMTAN = IM.TAN +OCT2BIN = OCT.A.BIN +OCT2DEC = OCT.A.DEC +OCT2HEX = OCT.A.HEX ## -## Engineering functions Funciones de ingeniería +## Funciones financieras (Financial Functions) ## -BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada. -BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x). -BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada. -BESSELY = BESSELY ## Devuelve la función Bessel Yn(x). -BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal. -BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal. -BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal. -COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo. -CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro. -DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario. -DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal. -DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal. -DELTA = DELTA ## Comprueba si dos valores son iguales. -ERF = FUN.ERROR ## Devuelve la función de error. -ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario. -GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral. -HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario. -HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal. -HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal. -IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo. -IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo. -IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes. -IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo. -IMCOS = IM.COS ## Devuelve el coseno de un número complejo. -IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos. -IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo. -IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo. -IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo. -IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo. -IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera. -IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos. -IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo. -IMSIN = IM.SENO ## Devuelve el seno de un número complejo. -IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo. -IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos. -IMSUM = IM.SUM ## Devuelve la suma de números complejos. -OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario. -OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal. -OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal. - +ACCRINT = INT.ACUM +ACCRINTM = INT.ACUM.V +AMORDEGRC = AMORTIZ.PROGRE +AMORLINC = AMORTIZ.LIN +COUPDAYBS = CUPON.DIAS.L1 +COUPDAYS = CUPON.DIAS +COUPDAYSNC = CUPON.DIAS.L2 +COUPNCD = CUPON.FECHA.L2 +COUPNUM = CUPON.NUM +COUPPCD = CUPON.FECHA.L1 +CUMIPMT = PAGO.INT.ENTRE +CUMPRINC = PAGO.PRINC.ENTRE +DB = DB +DDB = DDB +DISC = TASA.DESC +DOLLARDE = MONEDA.DEC +DOLLARFR = MONEDA.FRAC +DURATION = DURACION +EFFECT = INT.EFECTIVO +FV = VF +FVSCHEDULE = VF.PLAN +INTRATE = TASA.INT +IPMT = PAGOINT +IRR = TIR +ISPMT = INT.PAGO.DIR +MDURATION = DURACION.MODIF +MIRR = TIRM +NOMINAL = TASA.NOMINAL +NPER = NPER +NPV = VNA +ODDFPRICE = PRECIO.PER.IRREGULAR.1 +ODDFYIELD = RENDTO.PER.IRREGULAR.1 +ODDLPRICE = PRECIO.PER.IRREGULAR.2 +ODDLYIELD = RENDTO.PER.IRREGULAR.2 +PDURATION = P.DURACION +PMT = PAGO +PPMT = PAGOPRIN +PRICE = PRECIO +PRICEDISC = PRECIO.DESCUENTO +PRICEMAT = PRECIO.VENCIMIENTO +PV = VA +RATE = TASA +RECEIVED = CANTIDAD.RECIBIDA +RRI = RRI +SLN = SLN +SYD = SYD +TBILLEQ = LETRA.DE.TEST.EQV.A.BONO +TBILLPRICE = LETRA.DE.TES.PRECIO +TBILLYIELD = LETRA.DE.TES.RENDTO +VDB = DVS +XIRR = TIR.NO.PER +XNPV = VNA.NO.PER +YIELD = RENDTO +YIELDDISC = RENDTO.DESC +YIELDMAT = RENDTO.VENCTO ## -## Financial functions Funciones financieras +## Funciones de información (Information Functions) ## -ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos. -ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento. -AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización. -AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables. -COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación. -COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación. -COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón. -COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación. -COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento. -COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación. -CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos. -CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos. -DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo. -DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique. -DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil. -DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal. -DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria. -DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico. -EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva. -FV = VF ## Devuelve el valor futuro de una inversión. -FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto. -INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil. -IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado. -IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos. -ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión. -MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $. -MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes. -NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual. -NPER = NPER ## Devuelve el número de períodos de una inversión. -NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento. -ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar. -ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar. -ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar. -ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar. -PMT = PAGO ## Devuelve el pago periódico de una anualidad. -PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado. -PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico. -PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento. -PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento. -PV = VALACT ## Devuelve el valor actual de una inversión. -RATE = TASA ## Devuelve la tasa de interés por período de una anualidad. -RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido. -SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado. -SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado. -TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.) -TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.) -TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.) -VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución. -XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico. -XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico. -YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos. -YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.) -YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento. - +CELL = CELDA +ERROR.TYPE = TIPO.DE.ERROR +INFO = INFO +ISBLANK = ESBLANCO +ISERR = ESERR +ISERROR = ESERROR +ISEVEN = ES.PAR +ISFORMULA = ESFORMULA +ISLOGICAL = ESLOGICO +ISNA = ESNOD +ISNONTEXT = ESNOTEXTO +ISNUMBER = ESNUMERO +ISODD = ES.IMPAR +ISREF = ESREF +ISTEXT = ESTEXTO +N = N +NA = NOD +SHEET = HOJA +SHEETS = HOJAS +TYPE = TIPO ## -## Information functions Funciones de información +## Funciones lógicas (Logical Functions) ## -CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda. -ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error. -INFO = INFO ## Devuelve información acerca del entorno operativo en uso. -ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco. -ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A. -ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error. -ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par. -ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico. -ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A. -ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto. -ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número. -ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar. -ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia. -ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto. -N = N ## Devuelve un valor convertido en un número. -NA = ND ## Devuelve el valor de error #N/A. -TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor. - +AND = Y +FALSE = FALSO +IF = SI +IFERROR = SI.ERROR +IFNA = SI.ND +IFS = SI.CONJUNTO +NOT = NO +OR = O +SWITCH = CAMBIAR +TRUE = VERDADERO +XOR = XO ## -## Logical functions Funciones lógicas +## Funciones de búsqueda y referencia (Lookup & Reference Functions) ## -AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO. -FALSE = FALSO ## Devuelve el valor lógico FALSO. -IF = SI ## Especifica una prueba lógica que realizar. -IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula. -NOT = NO ## Invierte el valor lógico del argumento. -OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO. -TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO. - +ADDRESS = DIRECCION +AREAS = AREAS +CHOOSE = ELEGIR +COLUMN = COLUMNA +COLUMNS = COLUMNAS +FORMULATEXT = FORMULATEXTO +GETPIVOTDATA = IMPORTARDATOSDINAMICOS +HLOOKUP = BUSCARH +HYPERLINK = HIPERVINCULO +INDEX = INDICE +INDIRECT = INDIRECTO +LOOKUP = BUSCAR +MATCH = COINCIDIR +OFFSET = DESREF +ROW = FILA +ROWS = FILAS +RTD = RDTR +TRANSPOSE = TRANSPONER +VLOOKUP = BUSCARV ## -## Lookup and reference functions Funciones de búsqueda y referencia +## Funciones matemáticas y trigonométricas (Math & Trig Functions) ## -ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo. -AREAS = AREAS ## Devuelve el número de áreas de una referencia. -CHOOSE = ELEGIR ## Elige un valor de una lista de valores. -COLUMN = COLUMNA ## Devuelve el número de columna de una referencia. -COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia. -HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada. -HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet. -INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz. -INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto. -LOOKUP = BUSCAR ## Busca valores de un vector o una matriz. -MATCH = COINCIDIR ## Busca valores de una referencia o matriz. -OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada. -ROW = FILA ## Devuelve el número de fila de una referencia. -ROWS = FILAS ## Devuelve el número de filas de una referencia. -RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).). -TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz. -VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = NUMERO.ARABE +ASIN = ASENO +ASINH = ASENOH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = MULTIPLO.SUPERIOR.MAT +CEILING.PRECISE = MULTIPLO.SUPERIOR.EXACTO +COMBIN = COMBINAT +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = CONV.DECIMAL +DEGREES = GRADOS +ECMA.CEILING = MULTIPLO.SUPERIOR.ECMA +EVEN = REDONDEA.PAR +EXP = EXP +FACT = FACT +FACTDOUBLE = FACT.DOBLE +FLOOR.MATH = MULTIPLO.INFERIOR.MAT +FLOOR.PRECISE = MULTIPLO.INFERIOR.EXACTO +GCD = M.C.D +INT = ENTERO +ISO.CEILING = MULTIPLO.SUPERIOR.ISO +LCM = M.C.M +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERSA +MMULT = MMULT +MOD = RESIDUO +MROUND = REDOND.MULT +MULTINOMIAL = MULTINOMIAL +MUNIT = M.UNIDAD +ODD = REDONDEA.IMPAR +PI = PI +POWER = POTENCIA +PRODUCT = PRODUCTO +QUOTIENT = COCIENTE +RADIANS = RADIANES +RAND = ALEATORIO +RANDBETWEEN = ALEATORIO.ENTRE +ROMAN = NUMERO.ROMANO +ROUND = REDONDEAR +ROUNDBAHTDOWN = REDONDEAR.BAHT.MAS +ROUNDBAHTUP = REDONDEAR.BAHT.MENOS +ROUNDDOWN = REDONDEAR.MENOS +ROUNDUP = REDONDEAR.MAS +SEC = SEC +SECH = SECH +SERIESSUM = SUMA.SERIES +SIGN = SIGNO +SIN = SENO +SINH = SENOH +SQRT = RAIZ +SQRTPI = RAIZ2PI +SUBTOTAL = SUBTOTALES +SUM = SUMA +SUMIF = SUMAR.SI +SUMIFS = SUMAR.SI.CONJUNTO +SUMPRODUCT = SUMAPRODUCTO +SUMSQ = SUMA.CUADRADOS +SUMX2MY2 = SUMAX2MENOSY2 +SUMX2PY2 = SUMAX2MASY2 +SUMXMY2 = SUMAXMENOSY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR ## -## Math and trigonometry functions Funciones matemáticas y trigonométricas +## Funciones estadísticas (Statistical Functions) ## -ABS = ABS ## Devuelve el valor absoluto de un número. -ACOS = ACOS ## Devuelve el arcocoseno de un número. -ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número. -ASIN = ASENO ## Devuelve el arcoseno de un número. -ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número. -ATAN = ATAN ## Devuelve la arcotangente de un número. -ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y". -ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número. -CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano. -COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos. -COS = COS ## Devuelve el coseno de un número. -COSH = COSH ## Devuelve el coseno hiperbólico de un número. -DEGREES = GRADOS ## Convierte radianes en grados. -EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo. -EXP = EXP ## Devuelve e elevado a la potencia de un número dado. -FACT = FACT ## Devuelve el factorial de un número. -FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número. -FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero. -GCD = M.C.D ## Devuelve el máximo común divisor. -INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo. -LCM = M.C.M ## Devuelve el mínimo común múltiplo. -LN = LN ## Devuelve el logaritmo natural (neperiano) de un número. -LOG = LOG ## Devuelve el logaritmo de un número en una base especificada. -LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número. -MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz. -MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz. -MMULT = MMULT ## Devuelve el producto de matriz de dos matrices. -MOD = RESIDUO ## Devuelve el resto de la división. -MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado. -MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números. -ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo. -PI = PI ## Devuelve el valor de pi. -POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia. -PRODUCT = PRODUCTO ## Multiplica sus argumentos. -QUOTIENT = COCIENTE ## Devuelve la parte entera de una división. -RADIANS = RADIANES ## Convierte grados en radianes. -RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1. -RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique. -ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto. -ROUND = REDONDEAR ## Redondea un número al número de decimales especificado. -ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero. -ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero. -SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula. -SIGN = SIGNO ## Devuelve el signo de un número. -SIN = SENO ## Devuelve el seno de un ángulo determinado. -SINH = SENOH ## Devuelve el seno hiperbólico de un número. -SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número. -SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi). -SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos. -SUM = SUMA ## Suma sus argumentos. -SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados. -SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios. -SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz. -SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos. -SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices. -SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices. -SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices. -TAN = TAN ## Devuelve la tangente de un número. -TANH = TANH ## Devuelve la tangente hiperbólica de un número. -TRUNC = TRUNCAR ## Trunca un número a un entero. - +AVEDEV = DESVPROM +AVERAGE = PROMEDIO +AVERAGEA = PROMEDIOA +AVERAGEIF = PROMEDIO.SI +AVERAGEIFS = PROMEDIO.SI.CONJUNTO +BETA.DIST = DISTR.BETA.N +BETA.INV = INV.BETA.N +BINOM.DIST = DISTR.BINOM.N +BINOM.DIST.RANGE = DISTR.BINOM.SERIE +BINOM.INV = INV.BINOM +CHISQ.DIST = DISTR.CHICUAD +CHISQ.DIST.RT = DISTR.CHICUAD.CD +CHISQ.INV = INV.CHICUAD +CHISQ.INV.RT = INV.CHICUAD.CD +CHISQ.TEST = PRUEBA.CHICUAD +CONFIDENCE.NORM = INTERVALO.CONFIANZA.NORM +CONFIDENCE.T = INTERVALO.CONFIANZA.T +CORREL = COEF.DE.CORREL +COUNT = CONTAR +COUNTA = CONTARA +COUNTBLANK = CONTAR.BLANCO +COUNTIF = CONTAR.SI +COUNTIFS = CONTAR.SI.CONJUNTO +COVARIANCE.P = COVARIANCE.P +COVARIANCE.S = COVARIANZA.M +DEVSQ = DESVIA2 +EXPON.DIST = DISTR.EXP.N +F.DIST = DISTR.F.N +F.DIST.RT = DISTR.F.CD +F.INV = INV.F +F.INV.RT = INV.F.CD +F.TEST = PRUEBA.F.N +FISHER = FISHER +FISHERINV = PRUEBA.FISHER.INV +FORECAST.ETS = PRONOSTICO.ETS +FORECAST.ETS.CONFINT = PRONOSTICO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PRONOSTICO.ETS.ESTACIONALIDAD +FORECAST.ETS.STAT = PRONOSTICO.ETS.STAT +FORECAST.LINEAR = PRONOSTICO.LINEAL +FREQUENCY = FRECUENCIA +GAMMA = GAMMA +GAMMA.DIST = DISTR.GAMMA.N +GAMMA.INV = INV.GAMMA +GAMMALN = GAMMA.LN +GAMMALN.PRECISE = GAMMA.LN.EXACTO +GAUSS = GAUSS +GEOMEAN = MEDIA.GEOM +GROWTH = CRECIMIENTO +HARMEAN = MEDIA.ARMO +HYPGEOM.DIST = DISTR.HIPERGEOM.N +INTERCEPT = INTERSECCION.EJE +KURT = CURTOSIS +LARGE = K.ESIMO.MAYOR +LINEST = ESTIMACION.LINEAL +LOGEST = ESTIMACION.LOGARITMICA +LOGNORM.DIST = DISTR.LOGNORM +LOGNORM.INV = INV.LOGNORM +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.SI.CONJUNTO +MEDIAN = MEDIANA +MIN = MIN +MINA = MINA +MINIFS = MIN.SI.CONJUNTO +MODE.MULT = MODA.VARIOS +MODE.SNGL = MODA.UNO +NEGBINOM.DIST = NEGBINOM.DIST +NORM.DIST = DISTR.NORM.N +NORM.INV = INV.NORM +NORM.S.DIST = DISTR.NORM.ESTAND.N +NORM.S.INV = INV.NORM.ESTAND +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = RANGO.PERCENTIL.EXC +PERCENTRANK.INC = RANGO.PERCENTIL.INC +PERMUT = PERMUTACIONES +PERMUTATIONA = PERMUTACIONES.A +PHI = FI +POISSON.DIST = POISSON.DIST +PROB = PROBABILIDAD +QUARTILE.EXC = CUARTIL.EXC +QUARTILE.INC = CUARTIL.INC +RANK.AVG = JERARQUIA.MEDIA +RANK.EQ = JERARQUIA.EQV +RSQ = COEFICIENTE.R2 +SKEW = COEFICIENTE.ASIMETRIA +SKEW.P = COEFICIENTE.ASIMETRIA.P +SLOPE = PENDIENTE +SMALL = K.ESIMO.MENOR +STANDARDIZE = NORMALIZACION +STDEV.P = DESVEST.P +STDEV.S = DESVEST.M +STDEVA = DESVESTA +STDEVPA = DESVESTPA +STEYX = ERROR.TIPICO.XY +T.DIST = DISTR.T.N +T.DIST.2T = DISTR.T.2C +T.DIST.RT = DISTR.T.CD +T.INV = INV.T +T.INV.2T = INV.T.2C +T.TEST = PRUEBA.T.N +TREND = TENDENCIA +TRIMMEAN = MEDIA.ACOTADA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DISTR.WEIBULL +Z.TEST = PRUEBA.Z.N ## -## Statistical functions Funciones estadísticas +## Funciones de texto (Text Functions) ## -AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos. -AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos. -AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos. -AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados. -AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios. -BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa. -BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada. -BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial. -CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. -CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. -CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia. -CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población. -CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos. -COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos. -COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos. -COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango. -COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado. -COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios. -COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos. -CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio. -DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones. -EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial. -FDIST = DISTR.F ## Devuelve la distribución de probabilidad F. -FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F. -FISHER = FISHER ## Devuelve la transformación Fisher. -FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher. -FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal. -FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical. -FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F. -GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma. -GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa. -GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x). -GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica. -GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial. -HARMEAN = MEDIA.ARMO ## Devuelve la media armónica. -HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica. -INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal. -KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos. -LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos. -LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal. -LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial. -LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal. -LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa. -MAX = MAX ## Devuelve el valor máximo de una lista de argumentos. -MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos. -MEDIAN = MEDIANA ## Devuelve la mediana de los números dados. -MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos. -MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos. -MODE = MODA ## Devuelve el valor más común de un conjunto de datos. -NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa. -NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa. -NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa. -NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa. -NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa. -PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson. -PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango. -PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos. -PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos. -POISSON = POISSON ## Devuelve la distribución de Poisson. -PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites. -QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos. -RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números. -RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson. -SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución. -SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal. -SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos. -STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado. -STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra. -STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos. -STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población. -STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos. -STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión. -TDIST = DISTR.T ## Devuelve la distribución de t de Student. -TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student. -TREND = TENDENCIA ## Devuelve valores en una tendencia lineal. -TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos. -TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student. -VAR = VAR ## Calcula la varianza en función de una muestra. -VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos. -VARP = VARP ## Calcula la varianza en función de toda la población. -VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos. -WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull. -ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z. +BAHTTEXT = TEXTOBAHT +CHAR = CARACTER +CLEAN = LIMPIAR +CODE = CODIGO +CONCAT = CONCAT +DOLLAR = MONEDA +EXACT = IGUAL +FIND = ENCONTRAR +FIXED = DECIMAL +ISTHAIDIGIT = ESDIGITOTAI +LEFT = IZQUIERDA +LEN = LARGO +LOWER = MINUSC +MID = EXTRAE +NUMBERSTRING = CADENA.NUMERO +NUMBERVALUE = VALOR.NUMERO +PHONETIC = FONETICO +PROPER = NOMPROPIO +REPLACE = REEMPLAZAR +REPT = REPETIR +RIGHT = DERECHA +SEARCH = HALLAR +SUBSTITUTE = SUSTITUIR +T = T +TEXT = TEXTO +TEXTJOIN = UNIRCADENAS +THAIDIGIT = DIGITOTAI +THAINUMSOUND = SONNUMTAI +THAINUMSTRING = CADENANUMTAI +THAISTRINGLENGTH = LONGCADENATAI +TRIM = ESPACIOS +UNICHAR = UNICAR +UNICODE = UNICODE +UPPER = MAYUSC +VALUE = VALOR +## +## Funciones web (Web Functions) +## +ENCODEURL = URLCODIF +FILTERXML = XMLFILTRO +WEBSERVICE = SERVICIOWEB ## -## Text functions Funciones de texto +## Funciones de compatibilidad (Compatibility Functions) ## -ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte). -BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht). -CHAR = CARACTER ## Devuelve el carácter especificado por el número de código. -CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles. -CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto. -CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo. -DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar). -EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos. -FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). -FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). -FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales. -JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes). -LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto. -LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto. -LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto. -LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto. -LOWER = MINUSC ## Pone el texto en minúsculas. -MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. -MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. -PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto. -PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto. -REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto. -REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto. -REPT = REPETIR ## Repite el texto un número determinado de veces. -RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto. -RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto. -SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). -SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). -SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto. -T = T ## Convierte sus argumentos a texto. -TEXT = TEXTO ## Da formato a un número y lo convierte en texto. -TRIM = ESPACIOS ## Quita los espacios del texto. -UPPER = MAYUSC ## Pone el texto en mayúsculas. -VALUE = VALOR ## Convierte un argumento de texto en un número. +BETADIST = DISTR.BETA +BETAINV = DISTR.BETA.INV +BINOMDIST = DISTR.BINOM +CEILING = MULTIPLO.SUPERIOR +CHIDIST = DISTR.CHI +CHIINV = PRUEBA.CHI.INV +CHITEST = PRUEBA.CHI +CONCATENATE = CONCATENAR +CONFIDENCE = INTERVALO.CONFIANZA +COVAR = COVAR +CRITBINOM = BINOM.CRIT +EXPONDIST = DISTR.EXP +FDIST = DISTR.F +FINV = DISTR.F.INV +FLOOR = MULTIPLO.INFERIOR +FORECAST = PRONOSTICO +FTEST = PRUEBA.F +GAMMADIST = DISTR.GAMMA +GAMMAINV = DISTR.GAMMA.INV +HYPGEOMDIST = DISTR.HIPERGEOM +LOGINV = DISTR.LOG.INV +LOGNORMDIST = DISTR.LOG.NORM +MODE = MODA +NEGBINOMDIST = NEGBINOMDIST +NORMDIST = DISTR.NORM +NORMINV = DISTR.NORM.INV +NORMSDIST = DISTR.NORM.ESTAND +NORMSINV = DISTR.NORM.ESTAND.INV +PERCENTILE = PERCENTIL +PERCENTRANK = RANGO.PERCENTIL +POISSON = POISSON +QUARTILE = CUARTIL +RANK = JERARQUIA +STDEV = DESVEST +STDEVP = DESVESTP +TDIST = DISTR.T +TINV = DISTR.T.INV +TTEST = PRUEBA.T +VAR = VAR +VARP = VARP +WEIBULL = DIST.WEIBULL +ZTEST = PRUEBA.Z diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config index 22aaf58b..5388f939 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Suomi (Finnish) ## -## (For future use) -## -currencySymbol = $ # Symbol not known, should it be a € (Euro)? +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #TYHJÄ! -DIV0 = #JAKO/0! -VALUE = #ARVO! -REF = #VIITTAUS! -NAME = #NIMI? -NUM = #LUKU! -NA = #PUUTTUU +NULL = #TYHJÄ! +DIV0 = #JAKO/0! +VALUE = #ARVO! +REF = #VIITTAUS! +NAME = #NIMI? +NUM = #LUKU! +NA = #PUUTTUU! diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions index 289e0eac..33068d93 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fi/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Suomi (Finnish) ## +############################################################ ## -## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot +## Kuutiofunktiot (Cube Functions) ## -GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja. - +CUBEKPIMEMBER = KUUTIOKPIJÄSEN +CUBEMEMBER = KUUTIONJÄSEN +CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS +CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN +CUBESET = KUUTIOJOUKKO +CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ +CUBEVALUE = KUUTIONARVO ## -## Cube functions Kuutiofunktiot +## Tietokantafunktiot (Database Functions) ## -CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä. -CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa. -CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden. -CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa. -CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille. -CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän. -CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta. - +DAVERAGE = TKESKIARVO +DCOUNT = TLASKE +DCOUNTA = TLASKEA +DGET = TNOUDA +DMAX = TMAKS +DMIN = TMIN +DPRODUCT = TTULO +DSTDEV = TKESKIHAJONTA +DSTDEVP = TKESKIHAJONTAP +DSUM = TSUMMA +DVAR = TVARIANSSI +DVARP = TVARIANSSIP ## -## Database functions Tietokantafunktiot +## Päivämäärä- ja aikafunktiot (Date & Time Functions) ## -DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon. -DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän. -DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän. -DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta. -DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta. -DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta. -DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot. -DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella. -DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella. -DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen. -DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella. -DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella. - +DATE = PÄIVÄYS +DATEDIF = PVMERO +DATESTRING = PVMMERKKIJONO +DATEVALUE = PÄIVÄYSARVO +DAY = PÄIVÄ +DAYS = PÄIVÄT +DAYS360 = PÄIVÄT360 +EDATE = PÄIVÄ.KUUKAUSI +EOMONTH = KUUKAUSI.LOPPU +HOUR = TUNNIT +ISOWEEKNUM = VIIKKO.ISO.NRO +MINUTE = MINUUTIT +MONTH = KUUKAUSI +NETWORKDAYS = TYÖPÄIVÄT +NETWORKDAYS.INTL = TYÖPÄIVÄT.KANSVÄL +NOW = NYT +SECOND = SEKUNNIT +THAIDAYOFWEEK = THAI.VIIKONPÄIVÄ +THAIMONTHOFYEAR = THAI.KUUKAUSI +THAIYEAR = THAI.VUOSI +TIME = AIKA +TIMEVALUE = AIKA_ARVO +TODAY = TÄMÄ.PÄIVÄ +WEEKDAY = VIIKONPÄIVÄ +WEEKNUM = VIIKKO.NRO +WORKDAY = TYÖPÄIVÄ +WORKDAY.INTL = TYÖPÄIVÄ.KANSVÄL +YEAR = VUOSI +YEARFRAC = VUOSI.OSA ## -## Date and time functions Päivämäärä- ja aikafunktiot +## Tekniset funktiot (Engineering Functions) ## -DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun. -DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi. -DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi. -DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta. -EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin. -EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin. -HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi. -MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi. -MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi. -NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän. -NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron. -SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi. -TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun. -TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi. -TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun. -WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi. -WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna. -WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin. -YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi. -YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINDES +BIN2HEX = BINHEKSA +BIN2OCT = BINOKT +BITAND = BITTI.JA +BITLSHIFT = BITTI.SIIRTO.V +BITOR = BITTI.TAI +BITRSHIFT = BITTI.SIIRTO.O +BITXOR = BITTI.EHDOTON.TAI +COMPLEX = KOMPLEKSI +CONVERT = MUUNNA +DEC2BIN = DESBIN +DEC2HEX = DESHEKSA +DEC2OCT = DESOKT +DELTA = SAMA.ARVO +ERF = VIRHEFUNKTIO +ERF.PRECISE = VIRHEFUNKTIO.TARKKA +ERFC = VIRHEFUNKTIO.KOMPLEMENTTI +ERFC.PRECISE = VIRHEFUNKTIO.KOMPLEMENTTI.TARKKA +GESTEP = RAJA +HEX2BIN = HEKSABIN +HEX2DEC = HEKSADES +HEX2OCT = HEKSAOKT +IMABS = KOMPLEKSI.ABS +IMAGINARY = KOMPLEKSI.IMAG +IMARGUMENT = KOMPLEKSI.ARG +IMCONJUGATE = KOMPLEKSI.KONJ +IMCOS = KOMPLEKSI.COS +IMCOSH = IMCOSH +IMCOT = KOMPLEKSI.COT +IMCSC = KOMPLEKSI.KOSEK +IMCSCH = KOMPLEKSI.KOSEKH +IMDIV = KOMPLEKSI.OSAM +IMEXP = KOMPLEKSI.EKSP +IMLN = KOMPLEKSI.LN +IMLOG10 = KOMPLEKSI.LOG10 +IMLOG2 = KOMPLEKSI.LOG2 +IMPOWER = KOMPLEKSI.POT +IMPRODUCT = KOMPLEKSI.TULO +IMREAL = KOMPLEKSI.REAALI +IMSEC = KOMPLEKSI.SEK +IMSECH = KOMPLEKSI.SEKH +IMSIN = KOMPLEKSI.SIN +IMSINH = KOMPLEKSI.SINH +IMSQRT = KOMPLEKSI.NELIÖJ +IMSUB = KOMPLEKSI.EROTUS +IMSUM = KOMPLEKSI.SUM +IMTAN = KOMPLEKSI.TAN +OCT2BIN = OKTBIN +OCT2DEC = OKTDES +OCT2HEX = OKTHEKSA ## -## Engineering functions Tekniset funktiot +## Rahoitusfunktiot (Financial Functions) ## -BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x). -BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x). -BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x). -BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x). -BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi. -BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi. -BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi. -COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi. -CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi. -DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi. -DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi. -DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi. -DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria. -ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion. -ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion. -GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo. -HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi. -HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi. -HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi. -IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen). -IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen. -IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma. -IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun. -IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin. -IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän. -IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin. -IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin. -IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin. -IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin. -IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun. -IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon. -IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen. -IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin. -IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren. -IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen. -IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan. -OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi. -OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi. -OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi. - +ACCRINT = KERTYNYT.KORKO +ACCRINTM = KERTYNYT.KORKO.LOPUSSA +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KORKOPÄIVÄT.ALUSTA +COUPDAYS = KORKOPÄIVÄT +COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA +COUPNCD = KORKOPÄIVÄ.SEURAAVA +COUPNUM = KORKOPÄIVÄ.JAKSOT +COUPPCD = KORKOPÄIVÄ.EDELLINEN +CUMIPMT = MAKSETTU.KORKO +CUMPRINC = MAKSETTU.LYHENNYS +DB = DB +DDB = DDB +DISC = DISKONTTOKORKO +DOLLARDE = VALUUTTA.DES +DOLLARFR = VALUUTTA.MURTO +DURATION = KESTO +EFFECT = KORKO.EFEKT +FV = TULEVA.ARVO +FVSCHEDULE = TULEVA.ARVO.ERIKORKO +INTRATE = KORKO.ARVOPAPERI +IPMT = IPMT +IRR = SISÄINEN.KORKO +ISPMT = ISPMT +MDURATION = KESTO.MUUNN +MIRR = MSISÄINEN +NOMINAL = KORKO.VUOSI +NPER = NJAKSO +NPV = NNA +ODDFPRICE = PARITON.ENS.NIMELLISARVO +ODDFYIELD = PARITON.ENS.TUOTTO +ODDLPRICE = PARITON.VIIM.NIMELLISARVO +ODDLYIELD = PARITON.VIIM.TUOTTO +PDURATION = KESTO.JAKSO +PMT = MAKSU +PPMT = PPMT +PRICE = HINTA +PRICEDISC = HINTA.DISK +PRICEMAT = HINTA.LUNASTUS +PV = NA +RATE = KORKO +RECEIVED = SAATU.HINTA +RRI = TOT.ROI +SLN = STP +SYD = VUOSIPOISTO +TBILLEQ = OBLIG.TUOTTOPROS +TBILLPRICE = OBLIG.HINTA +TBILLYIELD = OBLIG.TUOTTO +VDB = VDB +XIRR = SISÄINEN.KORKO.JAKSOTON +XNPV = NNA.JAKSOTON +YIELD = TUOTTO +YIELDDISC = TUOTTO.DISK +YIELDMAT = TUOTTO.ERÄP ## -## Financial functions Rahoitusfunktiot +## Tietofunktiot (Information Functions) ## -ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin. -ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä. -AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä. -AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston. -COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän. -COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu. -COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän. -COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän. -COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän. -COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän. -CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron. -CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen. -DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. -DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan. -DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron. -DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi. -DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi. -DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti. -EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron. -FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon. -FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti. -INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille. -IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron. -IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle. -ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla. -MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa. -MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen. -NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron. -NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän. -NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella. -ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton. -ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton. -ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton. -ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton. -PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän. -PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen. -PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin. -PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden. -PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä. -PV = NA ## Palauttaa sijoituksen nykyarvon. -RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan. -RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle. -SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta. -SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla. -TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona. -TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden. -TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton. -VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. -XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä. -XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen. -YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin. -YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton. -YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton. - +CELL = SOLU +ERROR.TYPE = VIRHEEN.LAJI +INFO = KUVAUS +ISBLANK = ONTYHJÄ +ISERR = ONVIRH +ISERROR = ONVIRHE +ISEVEN = ONPARILLINEN +ISFORMULA = ONKAAVA +ISLOGICAL = ONTOTUUS +ISNA = ONPUUTTUU +ISNONTEXT = ONEI_TEKSTI +ISNUMBER = ONLUKU +ISODD = ONPARITON +ISREF = ONVIITT +ISTEXT = ONTEKSTI +N = N +NA = PUUTTUU +SHEET = TAULUKKO +SHEETS = TAULUKOT +TYPE = TYYPPI ## -## Information functions Erikoisfunktiot +## Loogiset funktiot (Logical Functions) ## -CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä. -ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun. -INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä. -ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä. -ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!. -ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo. -ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen. -ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo. -ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!. -ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti. -ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku. -ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton. -ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus. -ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti. -N = N ## Palauttaa arvon luvuksi muunnettuna. -NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!. -TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin. - +AND = JA +FALSE = EPÄTOSI +IF = JOS +IFERROR = JOSVIRHE +IFNA = JOSPUUTTUU +IFS = JOSS +NOT = EI +OR = TAI +SWITCH = MUUTA +TRUE = TOSI +XOR = EHDOTON.TAI ## -## Logical functions Loogiset funktiot +## Haku- ja viitefunktiot (Lookup & Reference Functions) ## -AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI. -FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI. -IF = JOS ## Määrittää suoritettavan loogisen testin. -IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen. -NOT = EI ## Kääntää argumentin loogisen arvon. -OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI. -TRUE = TOSI ## Palauttaa totuusarvon TOSI. - +ADDRESS = OSOITE +AREAS = ALUEET +CHOOSE = VALITSE.INDEKSI +COLUMN = SARAKE +COLUMNS = SARAKKEET +FORMULATEXT = KAAVA.TEKSTI +GETPIVOTDATA = NOUDA.PIVOT.TIEDOT +HLOOKUP = VHAKU +HYPERLINK = HYPERLINKKI +INDEX = INDEKSI +INDIRECT = EPÄSUORA +LOOKUP = HAKU +MATCH = VASTINE +OFFSET = SIIRTYMÄ +ROW = RIVI +ROWS = RIVIT +RTD = RTD +TRANSPOSE = TRANSPONOI +VLOOKUP = PHAKU ## -## Lookup and reference functions Haku- ja viitefunktiot +## Matemaattiset ja trigonometriset funktiot (Math & Trig Functions) ## -ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä. -AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän. -CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta. -COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron. -COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän. -HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon. -HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston. -INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan. -INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen. -LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista. -MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista. -OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän. -ROW = RIVI ## Palauttaa viittauksen rivinumeron. -ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän. -RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja. -TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin. -VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon. - +ABS = ITSEISARVO +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = KOOSTE +ARABIC = ARABIA +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = PERUS +CEILING.MATH = PYÖRISTÄ.KERR.YLÖS.MATEMAATTINEN +CEILING.PRECISE = PYÖRISTÄ.KERR.YLÖS.TARKKA +COMBIN = KOMBINAATIO +COMBINA = KOMBINAATIOA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = KOSEK +CSCH = KOSEKH +DECIMAL = DESIMAALI +DEGREES = ASTEET +ECMA.CEILING = ECMA.PYÖRISTÄ.KERR.YLÖS +EVEN = PARILLINEN +EXP = EKSPONENTTI +FACT = KERTOMA +FACTDOUBLE = KERTOMA.OSA +FLOOR.MATH = PYÖRISTÄ.KERR.ALAS.MATEMAATTINEN +FLOOR.PRECISE = PYÖRISTÄ.KERR.ALAS.TARKKA +GCD = SUURIN.YHT.TEKIJÄ +INT = KOKONAISLUKU +ISO.CEILING = ISO.PYÖRISTÄ.KERR.YLÖS +LCM = PIENIN.YHT.JAETTAVA +LN = LUONNLOG +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MKÄÄNTEINEN +MMULT = MKERRO +MOD = JAKOJ +MROUND = PYÖRISTÄ.KERR +MULTINOMIAL = MULTINOMI +MUNIT = YKSIKKÖM +ODD = PARITON +PI = PII +POWER = POTENSSI +PRODUCT = TULO +QUOTIENT = OSAMÄÄRÄ +RADIANS = RADIAANIT +RAND = SATUNNAISLUKU +RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ +ROMAN = ROMAN +ROUND = PYÖRISTÄ +ROUNDBAHTDOWN = PYÖRISTÄ.BAHT.ALAS +ROUNDBAHTUP = PYÖRISTÄ.BAHT.YLÖS +ROUNDDOWN = PYÖRISTÄ.DES.ALAS +ROUNDUP = PYÖRISTÄ.DES.YLÖS +SEC = SEK +SECH = SEKH +SERIESSUM = SARJA.SUMMA +SIGN = ETUMERKKI +SIN = SIN +SINH = SINH +SQRT = NELIÖJUURI +SQRTPI = NELIÖJUURI.PII +SUBTOTAL = VÄLISUMMA +SUM = SUMMA +SUMIF = SUMMA.JOS +SUMIFS = SUMMA.JOS.JOUKKO +SUMPRODUCT = TULOJEN.SUMMA +SUMSQ = NELIÖSUMMA +SUMX2MY2 = NELIÖSUMMIEN.EROTUS +SUMX2PY2 = NELIÖSUMMIEN.SUMMA +SUMXMY2 = EROTUSTEN.NELIÖSUMMA +TAN = TAN +TANH = TANH +TRUNC = KATKAISE ## -## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot +## Tilastolliset funktiot (Statistical Functions) ## -ABS = ITSEISARVO ## Palauttaa luvun itseisarvon. -ACOS = ACOS ## Palauttaa luvun arkuskosinin. -ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin. -ASIN = ASIN ## Palauttaa luvun arkussinin. -ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin. -ATAN = ATAN ## Palauttaa luvun arkustangentin. -ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella. -ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin. -CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen. -COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle. -COS = COS ## Palauttaa luvun kosinin. -COSH = COSH ## Palauttaa luvun hyperbolisen kosinin. -DEGREES = ASTEET ## Muuntaa radiaanit asteiksi. -EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun. -EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin. -FACT = KERTOMA ## Palauttaa luvun kertoman. -FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman. -FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). -GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän. -INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun. -LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän. -LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin. -LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua. -LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin. -MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin. -MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin. -MMULT = MKERRO ## Palauttaa kahden matriisin tulon. -MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen. -MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen. -MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin. -ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun. -PI = PII ## Palauttaa piin arvon. -POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin. -PRODUCT = TULO ## Kertoo annetut argumentit. -QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan. -RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi. -RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1. -RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä. -ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi. -ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja. -ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). -ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta). -SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon. -SIGN = ETUMERKKI ## Palauttaa luvun etumerkin. -SIN = SIN ## Palauttaa annetun kulman sinin. -SINH = SINH ## Palauttaa luvun hyperbolisen sinin. -SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren. -SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren. -SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman. -SUM = SUMMA ## Laskee yhteen annetut argumentit. -SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan. -SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut. -SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan. -SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan. -SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen. -SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan. -SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman. -TAN = TAN ## Palauttaa luvun tangentin. -TANH = TANH ## Palauttaa luvun hyperbolisen tangentin. -TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi. - +AVEDEV = KESKIPOIKKEAMA +AVERAGE = KESKIARVO +AVERAGEA = KESKIARVOA +AVERAGEIF = KESKIARVO.JOS +AVERAGEIFS = KESKIARVO.JOS.JOUKKO +BETA.DIST = BEETA.JAKAUMA +BETA.INV = BEETA.KÄÄNT +BINOM.DIST = BINOMI.JAKAUMA +BINOM.DIST.RANGE = BINOMI.JAKAUMA.ALUE +BINOM.INV = BINOMIJAKAUMA.KÄÄNT +CHISQ.DIST = CHINELIÖ.JAKAUMA +CHISQ.DIST.RT = CHINELIÖ.JAKAUMA.OH +CHISQ.INV = CHINELIÖ.KÄÄNT +CHISQ.INV.RT = CHINELIÖ.KÄÄNT.OH +CHISQ.TEST = CHINELIÖ.TESTI +CONFIDENCE.NORM = LUOTTAMUSVÄLI.NORM +CONFIDENCE.T = LUOTTAMUSVÄLI.T +CORREL = KORRELAATIO +COUNT = LASKE +COUNTA = LASKE.A +COUNTBLANK = LASKE.TYHJÄT +COUNTIF = LASKE.JOS +COUNTIFS = LASKE.JOS.JOUKKO +COVARIANCE.P = KOVARIANSSI.P +COVARIANCE.S = KOVARIANSSI.S +DEVSQ = OIKAISTU.NELIÖSUMMA +EXPON.DIST = EKSPONENTIAALI.JAKAUMA +F.DIST = F.JAKAUMA +F.DIST.RT = F.JAKAUMA.OH +F.INV = F.KÄÄNT +F.INV.RT = F.KÄÄNT.OH +F.TEST = F.TESTI +FISHER = FISHER +FISHERINV = FISHER.KÄÄNT +FORECAST.ETS = ENNUSTE.ETS +FORECAST.ETS.CONFINT = ENNUSTE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = ENNUSTE.ETS.KAUSIVAIHTELU +FORECAST.ETS.STAT = ENNUSTE.ETS.STAT +FORECAST.LINEAR = ENNUSTE.LINEAARINEN +FREQUENCY = TAAJUUS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.JAKAUMA +GAMMA.INV = GAMMA.JAKAUMA.KÄÄNT +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.TARKKA +GAUSS = GAUSS +GEOMEAN = KESKIARVO.GEOM +GROWTH = KASVU +HARMEAN = KESKIARVO.HARM +HYPGEOM.DIST = HYPERGEOM_JAKAUMA +INTERCEPT = LEIKKAUSPISTE +KURT = KURT +LARGE = SUURI +LINEST = LINREGR +LOGEST = LOGREGR +LOGNORM.DIST = LOGNORM_JAKAUMA +LOGNORM.INV = LOGNORM.KÄÄNT +MAX = MAKS +MAXA = MAKSA +MAXIFS = MAKS.JOS +MEDIAN = MEDIAANI +MIN = MIN +MINA = MINA +MINIFS = MIN.JOS +MODE.MULT = MOODI.USEA +MODE.SNGL = MOODI.YKSI +NEGBINOM.DIST = BINOMI.JAKAUMA.NEG +NORM.DIST = NORMAALI.JAKAUMA +NORM.INV = NORMAALI.JAKAUMA.KÄÄNT +NORM.S.DIST = NORM_JAKAUMA.NORMIT +NORM.S.INV = NORM_JAKAUMA.KÄÄNT +PEARSON = PEARSON +PERCENTILE.EXC = PROSENTTIPISTE.ULK +PERCENTILE.INC = PROSENTTIPISTE.SIS +PERCENTRANK.EXC = PROSENTTIJÄRJESTYS.ULK +PERCENTRANK.INC = PROSENTTIJÄRJESTYS.SIS +PERMUT = PERMUTAATIO +PERMUTATIONA = PERMUTAATIOA +PHI = FII +POISSON.DIST = POISSON.JAKAUMA +PROB = TODENNÄKÖISYYS +QUARTILE.EXC = NELJÄNNES.ULK +QUARTILE.INC = NELJÄNNES.SIS +RANK.AVG = ARVON.MUKAAN.KESKIARVO +RANK.EQ = ARVON.MUKAAN.TASAN +RSQ = PEARSON.NELIÖ +SKEW = JAKAUMAN.VINOUS +SKEW.P = JAKAUMAN.VINOUS.POP +SLOPE = KULMAKERROIN +SMALL = PIENI +STANDARDIZE = NORMITA +STDEV.P = KESKIHAJONTA.P +STDEV.S = KESKIHAJONTA.S +STDEVA = KESKIHAJONTAA +STDEVPA = KESKIHAJONTAPA +STEYX = KESKIVIRHE +T.DIST = T.JAKAUMA +T.DIST.2T = T.JAKAUMA.2S +T.DIST.RT = T.JAKAUMA.OH +T.INV = T.KÄÄNT +T.INV.2T = T.KÄÄNT.2S +T.TEST = T.TESTI +TREND = SUUNTAUS +TRIMMEAN = KESKIARVO.TASATTU +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.JAKAUMA +Z.TEST = Z.TESTI ## -## Statistical functions Tilastolliset funktiot +## Tekstifunktiot (Text Functions) ## -AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon. -AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon. -AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon. -AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot. -AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja. -BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon. -BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon. -BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden. -CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden. -CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon. -CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen. -CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle. -CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen. -COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän. -COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän. -COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän. -COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja. -COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja. -COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista. -CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo. -DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman. -EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman. -FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman. -FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion. -FISHER = FISHER ## Palauttaa Fisher-muunnoksen. -FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen. -FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon. -FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina. -FTEST = FTESTI ## Palauttaa F-testin tuloksen. -GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman. -GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion. -GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x). -GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon. -GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon. -HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon. -HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman. -INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen. -KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden. -LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon. -LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit. -LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit. -LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion. -LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion. -MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta. -MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon. -MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin. -MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta. -MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon. -MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon. -NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman. -NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion. -NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion. -NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion. -NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon. -PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen. -PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen. -PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun. -PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle. -POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman. -PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä. -QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen. -RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa. -RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön. -SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden. -SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen. -SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon. -STANDARDIZE = NORMITA ## Palauttaa normitetun arvon. -STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella. -STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. -STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella. -STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. -STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen. -TDIST = TJAKAUMA ## Palauttaa t-jakautuman. -TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman. -TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja. -TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon. -TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden. -VAR = VAR ## Arvioi populaation varianssia otoksen perusteella. -VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. -VARP = VARP ## Laskee varianssin koko populaation perusteella. -VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. -WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman. -ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon. +BAHTTEXT = BAHTTEKSTI +CHAR = MERKKI +CLEAN = SIIVOA +CODE = KOODI +CONCAT = YHDISTÄ +DOLLAR = VALUUTTA +EXACT = VERTAA +FIND = ETSI +FIXED = KIINTEÄ +ISTHAIDIGIT = ON.THAI.NUMERO +LEFT = VASEN +LEN = PITUUS +LOWER = PIENET +MID = POIMI.TEKSTI +NUMBERSTRING = NROMERKKIJONO +NUMBERVALUE = NROARVO +PHONETIC = FONEETTINEN +PROPER = ERISNIMI +REPLACE = KORVAA +REPT = TOISTA +RIGHT = OIKEA +SEARCH = KÄY.LÄPI +SUBSTITUTE = VAIHDA +T = T +TEXT = TEKSTI +TEXTJOIN = TEKSTI.YHDISTÄ +THAIDIGIT = THAI.NUMERO +THAINUMSOUND = THAI.LUKU.ÄÄNI +THAINUMSTRING = THAI.LUKU.MERKKIJONO +THAISTRINGLENGTH = THAI.MERKKIJONON.PITUUS +TRIM = POISTA.VÄLIT +UNICHAR = UNICODEMERKKI +UNICODE = UNICODE +UPPER = ISOT +VALUE = ARVO +## +## Verkkofunktiot (Web Functions) +## +ENCODEURL = URLKOODAUS +FILTERXML = SUODATA.XML +WEBSERVICE = VERKKOPALVELU ## -## Text functions Tekstifunktiot +## Yhteensopivuusfunktiot (Compatibility Functions) ## -ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi. -BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä. -CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin. -CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit. -CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin. -CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi. -DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä. -EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset. -FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). -FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). -FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja. -JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi. -LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit. -LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit. -LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän. -LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän. -LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi. -MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. -MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. -PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta. -PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi. -REPLACE = KORVAA ## Korvaa tekstissä olevat merkit. -REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit. -REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja. -RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit. -RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit. -SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). -SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). -SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella. -T = T ## Muuntaa argumentit tekstiksi. -TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi. -TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä. -UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi. -VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi. +BETADIST = BEETAJAKAUMA +BETAINV = BEETAJAKAUMA.KÄÄNT +BINOMDIST = BINOMIJAKAUMA +CEILING = PYÖRISTÄ.KERR.YLÖS +CHIDIST = CHIJAKAUMA +CHIINV = CHIJAKAUMA.KÄÄNT +CHITEST = CHITESTI +CONCATENATE = KETJUTA +CONFIDENCE = LUOTTAMUSVÄLI +COVAR = KOVARIANSSI +CRITBINOM = BINOMIJAKAUMA.KRIT +EXPONDIST = EKSPONENTIAALIJAKAUMA +FDIST = FJAKAUMA +FINV = FJAKAUMA.KÄÄNT +FLOOR = PYÖRISTÄ.KERR.ALAS +FORECAST = ENNUSTE +FTEST = FTESTI +GAMMADIST = GAMMAJAKAUMA +GAMMAINV = GAMMAJAKAUMA.KÄÄNT +HYPGEOMDIST = HYPERGEOM.JAKAUMA +LOGINV = LOGNORM.JAKAUMA.KÄÄNT +LOGNORMDIST = LOGNORM.JAKAUMA +MODE = MOODI +NEGBINOMDIST = BINOMIJAKAUMA.NEG +NORMDIST = NORM.JAKAUMA +NORMINV = NORM.JAKAUMA.KÄÄNT +NORMSDIST = NORM.JAKAUMA.NORMIT +NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT +PERCENTILE = PROSENTTIPISTE +PERCENTRANK = PROSENTTIJÄRJESTYS +POISSON = POISSON +QUARTILE = NELJÄNNES +RANK = ARVON.MUKAAN +STDEV = KESKIHAJONTA +STDEVP = KESKIHAJONTAP +TDIST = TJAKAUMA +TINV = TJAKAUMA.KÄÄNT +TTEST = TTESTI +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = ZTESTI diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config index 81895986..bdac4121 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Français (French) ## -## (For future use) -## -currencySymbol = € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NUL! -DIV0 = #DIV/0! -VALUE = #VALEUR! -REF = #REF! -NAME = #NOM? -NUM = #NOMBRE! -NA = #N/A +NULL = #NUL! +DIV0 +VALUE = #VALEUR! +REF +NAME = #NOM? +NUM = #NOMBRE! +NA diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions index 7f40d5fd..78b603e9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/fr/functions @@ -1,416 +1,524 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Français (French) ## +############################################################ ## -## Add-in and Automation functions Fonctions de complément et d’automatisation +## Fonctions Cube (Cube Functions) ## -GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique. - +CUBEKPIMEMBER = MEMBREKPICUBE +CUBEMEMBER = MEMBRECUBE +CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE +CUBERANKEDMEMBER = RANGMEMBRECUBE +CUBESET = JEUCUBE +CUBESETCOUNT = NBJEUCUBE +CUBEVALUE = VALEURCUBE ## -## Cube functions Fonctions Cube +## Fonctions de base de données (Database Functions) ## -CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise. -CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube. -CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre. -CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants. -CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel. -CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu. -CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube. - +DAVERAGE = BDMOYENNE +DCOUNT = BDNB +DCOUNTA = BDNBVAL +DGET = BDLIRE +DMAX = BDMAX +DMIN = BDMIN +DPRODUCT = BDPRODUIT +DSTDEV = BDECARTYPE +DSTDEVP = BDECARTYPEP +DSUM = BDSOMME +DVAR = BDVAR +DVARP = BDVARP ## -## Database functions Fonctions de base de données +## Fonctions de date et d’heure (Date & Time Functions) ## -DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées. -DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres. -DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données. -DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés. -DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées. -DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées. -DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés. -DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées. -DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées. -DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères. -DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées. -DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées. - +DATE = DATE +DATEVALUE = DATEVAL +DAY = JOUR +DAYS = JOURS +DAYS360 = JOURS360 +EDATE = MOIS.DECALER +EOMONTH = FIN.MOIS +HOUR = HEURE +ISOWEEKNUM = NO.SEMAINE.ISO +MINUTE = MINUTE +MONTH = MOIS +NETWORKDAYS = NB.JOURS.OUVRES +NETWORKDAYS.INTL = NB.JOURS.OUVRES.INTL +NOW = MAINTENANT +SECOND = SECONDE +TIME = TEMPS +TIMEVALUE = TEMPSVAL +TODAY = AUJOURDHUI +WEEKDAY = JOURSEM +WEEKNUM = NO.SEMAINE +WORKDAY = SERIE.JOUR.OUVRE +WORKDAY.INTL = SERIE.JOUR.OUVRE.INTL +YEAR = ANNEE +YEARFRAC = FRACTION.ANNEE ## -## Date and time functions Fonctions de date et d’heure +## Fonctions d’ingénierie (Engineering Functions) ## -DATE = DATE ## Renvoie le numéro de série d’une date précise. -DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série. -DAY = JOUR ## Convertit un numéro de série en jour du mois. -DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours. -EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué. -EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué. -HOUR = HEURE ## Convertit un numéro de série en heure. -MINUTE = MINUTE ## Convertit un numéro de série en minute. -MONTH = MOIS ## Convertit un numéro de série en mois. -NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates. -NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour. -SECOND = SECONDE ## Convertit un numéro de série en seconde. -TIME = TEMPS ## Renvoie le numéro de série d’une heure précise. -TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série. -TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour. -WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine. -WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année. -WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés. -YEAR = ANNEE ## Convertit un numéro de série en année. -YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINDEC +BIN2HEX = BINHEX +BIN2OCT = BINOCT +BITAND = BITET +BITLSHIFT = BITDECALG +BITOR = BITOU +BITRSHIFT = BITDECALD +BITXOR = BITOUEXCLUSIF +COMPLEX = COMPLEXE +CONVERT = CONVERT +DEC2BIN = DECBIN +DEC2HEX = DECHEX +DEC2OCT = DECOCT +DELTA = DELTA +ERF = ERF +ERF.PRECISE = ERF.PRECIS +ERFC = ERFC +ERFC.PRECISE = ERFC.PRECIS +GESTEP = SUP.SEUIL +HEX2BIN = HEXBIN +HEX2DEC = HEXDEC +HEX2OCT = HEXOCT +IMABS = COMPLEXE.MODULE +IMAGINARY = COMPLEXE.IMAGINAIRE +IMARGUMENT = COMPLEXE.ARGUMENT +IMCONJUGATE = COMPLEXE.CONJUGUE +IMCOS = COMPLEXE.COS +IMCOSH = COMPLEXE.COSH +IMCOT = COMPLEXE.COT +IMCSC = COMPLEXE.CSC +IMCSCH = COMPLEXE.CSCH +IMDIV = COMPLEXE.DIV +IMEXP = COMPLEXE.EXP +IMLN = COMPLEXE.LN +IMLOG10 = COMPLEXE.LOG10 +IMLOG2 = COMPLEXE.LOG2 +IMPOWER = COMPLEXE.PUISSANCE +IMPRODUCT = COMPLEXE.PRODUIT +IMREAL = COMPLEXE.REEL +IMSEC = COMPLEXE.SEC +IMSECH = COMPLEXE.SECH +IMSIN = COMPLEXE.SIN +IMSINH = COMPLEXE.SINH +IMSQRT = COMPLEXE.RACINE +IMSUB = COMPLEXE.DIFFERENCE +IMSUM = COMPLEXE.SOMME +IMTAN = COMPLEXE.TAN +OCT2BIN = OCTBIN +OCT2DEC = OCTDEC +OCT2HEX = OCTHEX ## -## Engineering functions Fonctions d’ingénierie +## Fonctions financières (Financial Functions) ## -BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x). -BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x). -BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x). -BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x). -BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal. -BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal. -BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal. -COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe. -CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre. -DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire. -DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal. -DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal. -DELTA = DELTA ## Teste l’égalité de deux nombres. -ERF = ERF ## Renvoie la valeur de la fonction d’erreur. -ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire. -GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil. -HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire. -HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal. -HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal. -IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe. -IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe. -IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians. -IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe. -IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe. -IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes. -IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe. -IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe. -IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe. -IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe. -IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière. -IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes. -IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe. -IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe. -IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe. -IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes. -IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes. -OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire. -OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal. -OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal. - +ACCRINT = INTERET.ACC +ACCRINTM = INTERET.ACC.MAT +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = NB.JOURS.COUPON.PREC +COUPDAYS = NB.JOURS.COUPONS +COUPDAYSNC = NB.JOURS.COUPON.SUIV +COUPNCD = DATE.COUPON.SUIV +COUPNUM = NB.COUPONS +COUPPCD = DATE.COUPON.PREC +CUMIPMT = CUMUL.INTER +CUMPRINC = CUMUL.PRINCPER +DB = DB +DDB = DDB +DISC = TAUX.ESCOMPTE +DOLLARDE = PRIX.DEC +DOLLARFR = PRIX.FRAC +DURATION = DUREE +EFFECT = TAUX.EFFECTIF +FV = VC +FVSCHEDULE = VC.PAIEMENTS +INTRATE = TAUX.INTERET +IPMT = INTPER +IRR = TRI +ISPMT = ISPMT +MDURATION = DUREE.MODIFIEE +MIRR = TRIM +NOMINAL = TAUX.NOMINAL +NPER = NPM +NPV = VAN +ODDFPRICE = PRIX.PCOUPON.IRREG +ODDFYIELD = REND.PCOUPON.IRREG +ODDLPRICE = PRIX.DCOUPON.IRREG +ODDLYIELD = REND.DCOUPON.IRREG +PDURATION = PDUREE +PMT = VPM +PPMT = PRINCPER +PRICE = PRIX.TITRE +PRICEDISC = VALEUR.ENCAISSEMENT +PRICEMAT = PRIX.TITRE.ECHEANCE +PV = VA +RATE = TAUX +RECEIVED = VALEUR.NOMINALE +RRI = TAUX.INT.EQUIV +SLN = AMORLIN +SYD = SYD +TBILLEQ = TAUX.ESCOMPTE.R +TBILLPRICE = PRIX.BON.TRESOR +TBILLYIELD = RENDEMENT.BON.TRESOR +VDB = VDB +XIRR = TRI.PAIEMENTS +XNPV = VAN.PAIEMENTS +YIELD = RENDEMENT.TITRE +YIELDDISC = RENDEMENT.SIMPLE +YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## -## Financial functions Fonctions financières +## Fonctions d’information (Information Functions) ## -ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement. -ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance. -AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement. -AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée. -COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation. -COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation. -COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation. -COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement. -COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance. -COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement. -CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes. -CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes. -DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe. -DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier. -DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction. -DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal. -DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction. -DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement. -EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif. -FV = VC ## Renvoie la valeur future d’un investissement. -FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites. -INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi. -IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée. -IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries. -ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée. -MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros. -MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents. -NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel. -NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt. -NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte. -ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. -ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière. -ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. -ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière. -PMT = VPM ## Calcule le paiement périodique d’un investissement donné. -PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement. -PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros. -PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros. -PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance. -PV = PV ## Calcule la valeur actuelle d’un investissement. -RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité. -RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce. -SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée. -SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante). -TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor. -TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros. -TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor. -VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe. -XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques. -XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques. -YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement. -YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor). -YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance. - +CELL = CELLULE +ERROR.TYPE = TYPE.ERREUR +INFO = INFORMATIONS +ISBLANK = ESTVIDE +ISERR = ESTERR +ISERROR = ESTERREUR +ISEVEN = EST.PAIR +ISFORMULA = ESTFORMULE +ISLOGICAL = ESTLOGIQUE +ISNA = ESTNA +ISNONTEXT = ESTNONTEXTE +ISNUMBER = ESTNUM +ISODD = EST.IMPAIR +ISREF = ESTREF +ISTEXT = ESTTEXTE +N = N +NA = NA +SHEET = FEUILLE +SHEETS = FEUILLES +TYPE = TYPE ## -## Information functions Fonctions d’information +## Fonctions logiques (Logical Functions) ## -CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule. -ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur. -INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel. -ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide. -ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A. -ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur. -ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair. -ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique. -ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A. -ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte. -ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre. -ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair. -ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence. -ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte. -N = N ## Renvoie une valeur convertie en nombre. -NA = NA ## Renvoie la valeur d’erreur #N/A. -TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur. - +AND = ET +FALSE = FAUX +IF = SI +IFERROR = SIERREUR +IFNA = SI.NON.DISP +IFS = SI.CONDITIONS +NOT = NON +OR = OU +SWITCH = SI.MULTIPLE +TRUE = VRAI +XOR = OUX ## -## Logical functions Fonctions logiques +## Fonctions de recherche et de référence (Lookup & Reference Functions) ## -AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI. -FALSE = FAUX ## Renvoie la valeur logique FAUX. -IF = SI ## Spécifie un test logique à effectuer. -IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule. -NOT = NON ## Inverse la logique de cet argument. -OR = OU ## Renvoie VRAI si un des arguments est VRAI. -TRUE = VRAI ## Renvoie la valeur logique VRAI. - +ADDRESS = ADRESSE +AREAS = ZONES +CHOOSE = CHOISIR +COLUMN = COLONNE +COLUMNS = COLONNES +FORMULATEXT = FORMULETEXTE +GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE +HLOOKUP = RECHERCHEH +HYPERLINK = LIEN_HYPERTEXTE +INDEX = INDEX +INDIRECT = INDIRECT +LOOKUP = RECHERCHE +MATCH = EQUIV +OFFSET = DECALER +ROW = LIGNE +ROWS = LIGNES +RTD = RTD +TRANSPOSE = TRANSPOSE +VLOOKUP = RECHERCHEV ## -## Lookup and reference functions Fonctions de recherche et de référence +## Fonctions mathématiques et trigonométriques (Math & Trig Functions) ## -ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul. -AREAS = ZONES ## Renvoie le nombre de zones dans une référence. -CHOOSE = CHOISIR ## Choisit une valeur dans une liste. -COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence. -COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence. -HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée. -HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet. -INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice. -INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte. -LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice. -MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice. -OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée. -ROW = LIGNE ## Renvoie le numéro de ligne d’une référence. -ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence. -RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).). -TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice. -VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAT +ARABIC = CHIFFRE.ARABE +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = PLAFOND.MATH +CEILING.PRECISE = PLAFOND.PRECIS +COMBIN = COMBIN +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = DEGRES +ECMA.CEILING = ECMA.PLAFOND +EVEN = PAIR +EXP = EXP +FACT = FACT +FACTDOUBLE = FACTDOUBLE +FLOOR.MATH = PLANCHER.MATH +FLOOR.PRECISE = PLANCHER.PRECIS +GCD = PGCD +INT = ENT +ISO.CEILING = ISO.PLAFOND +LCM = PPCM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMAT +MINVERSE = INVERSEMAT +MMULT = PRODUITMAT +MOD = MOD +MROUND = ARRONDI.AU.MULTIPLE +MULTINOMIAL = MULTINOMIALE +MUNIT = MATRICE.UNITAIRE +ODD = IMPAIR +PI = PI +POWER = PUISSANCE +PRODUCT = PRODUIT +QUOTIENT = QUOTIENT +RADIANS = RADIANS +RAND = ALEA +RANDBETWEEN = ALEA.ENTRE.BORNES +ROMAN = ROMAIN +ROUND = ARRONDI +ROUNDDOWN = ARRONDI.INF +ROUNDUP = ARRONDI.SUP +SEC = SEC +SECH = SECH +SERIESSUM = SOMME.SERIES +SIGN = SIGNE +SIN = SIN +SINH = SINH +SQRT = RACINE +SQRTPI = RACINE.PI +SUBTOTAL = SOUS.TOTAL +SUM = SOMME +SUMIF = SOMME.SI +SUMIFS = SOMME.SI.ENS +SUMPRODUCT = SOMMEPROD +SUMSQ = SOMME.CARRES +SUMX2MY2 = SOMME.X2MY2 +SUMX2PY2 = SOMME.X2PY2 +SUMXMY2 = SOMME.XMY2 +TAN = TAN +TANH = TANH +TRUNC = TRONQUE ## -## Math and trigonometry functions Fonctions mathématiques et trigonométriques +## Fonctions statistiques (Statistical Functions) ## -ABS = ABS ## Renvoie la valeur absolue d’un nombre. -ACOS = ACOS ## Renvoie l’arccosinus d’un nombre. -ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre. -ASIN = ASIN ## Renvoie l’arcsinus d’un nombre. -ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre. -ATAN = ATAN ## Renvoie l’arctangente d’un nombre. -ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y. -ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre. -CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro. -COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets. -COS = COS ## Renvoie le cosinus d’un nombre. -COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre. -DEGREES = DEGRES ## Convertit des radians en degrés. -EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro. -EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné. -FACT = FACT ## Renvoie la factorielle d’un nombre. -FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre. -FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro). -GCD = PGCD ## Renvoie le plus grand commun diviseur. -INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur. -LCM = PPCM ## Renvoie le plus petit commun multiple. -LN = LN ## Renvoie le logarithme népérien d’un nombre. -LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée. -LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre. -MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice. -MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice. -MMULT = PRODUITMAT ## Renvoie le produit de deux matrices. -MOD = MOD ## Renvoie le reste d’une division. -MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié. -MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres. -ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro. -PI = PI ## Renvoie la valeur de pi. -POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance. -PRODUCT = PRODUIT ## Multiplie ses arguments. -QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division. -RADIANS = RADIANS ## Convertit des degrés en radians. -RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1. -RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez. -ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte. -ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué. -ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro). -ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro. -SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante : -SIGN = SIGNE ## Renvoie le signe d’un nombre. -SIN = SIN ## Renvoie le sinus d’un angle donné. -SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre. -SQRT = RACINE ## Renvoie la racine carrée d’un nombre. -SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi). -SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données. -SUM = SOMME ## Calcule la somme de ses arguments. -SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné. -SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères. -SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits. -SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments. -SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices. -SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices. -SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices. -TAN = TAN ## Renvoie la tangente d’un nombre. -TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre. -TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre. - +AVEDEV = ECART.MOYEN +AVERAGE = MOYENNE +AVERAGEA = AVERAGEA +AVERAGEIF = MOYENNE.SI +AVERAGEIFS = MOYENNE.SI.ENS +BETA.DIST = LOI.BETA.N +BETA.INV = BETA.INVERSE.N +BINOM.DIST = LOI.BINOMIALE.N +BINOM.DIST.RANGE = LOI.BINOMIALE.SERIE +BINOM.INV = LOI.BINOMIALE.INVERSE +CHISQ.DIST = LOI.KHIDEUX.N +CHISQ.DIST.RT = LOI.KHIDEUX.DROITE +CHISQ.INV = LOI.KHIDEUX.INVERSE +CHISQ.INV.RT = LOI.KHIDEUX.INVERSE.DROITE +CHISQ.TEST = CHISQ.TEST +CONFIDENCE.NORM = INTERVALLE.CONFIANCE.NORMAL +CONFIDENCE.T = INTERVALLE.CONFIANCE.STUDENT +CORREL = COEFFICIENT.CORRELATION +COUNT = NB +COUNTA = NBVAL +COUNTBLANK = NB.VIDE +COUNTIF = NB.SI +COUNTIFS = NB.SI.ENS +COVARIANCE.P = COVARIANCE.PEARSON +COVARIANCE.S = COVARIANCE.STANDARD +DEVSQ = SOMME.CARRES.ECARTS +EXPON.DIST = LOI.EXPONENTIELLE.N +F.DIST = LOI.F.N +F.DIST.RT = LOI.F.DROITE +F.INV = INVERSE.LOI.F.N +F.INV.RT = INVERSE.LOI.F.DROITE +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHER.INVERSE +FORECAST.ETS = PREVISION.ETS +FORECAST.ETS.CONFINT = PREVISION.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISION.ETS.CARACTERESAISONNIER +FORECAST.ETS.STAT = PREVISION.ETS.STAT +FORECAST.LINEAR = PREVISION.LINEAIRE +FREQUENCY = FREQUENCE +GAMMA = GAMMA +GAMMA.DIST = LOI.GAMMA.N +GAMMA.INV = LOI.GAMMA.INVERSE.N +GAMMALN = LNGAMMA +GAMMALN.PRECISE = LNGAMMA.PRECIS +GAUSS = GAUSS +GEOMEAN = MOYENNE.GEOMETRIQUE +GROWTH = CROISSANCE +HARMEAN = MOYENNE.HARMONIQUE +HYPGEOM.DIST = LOI.HYPERGEOMETRIQUE.N +INTERCEPT = ORDONNEE.ORIGINE +KURT = KURTOSIS +LARGE = GRANDE.VALEUR +LINEST = DROITEREG +LOGEST = LOGREG +LOGNORM.DIST = LOI.LOGNORMALE.N +LOGNORM.INV = LOI.LOGNORMALE.INVERSE.N +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.SI +MEDIAN = MEDIANE +MIN = MIN +MINA = MINA +MINIFS = MIN.SI +MODE.MULT = MODE.MULTIPLE +MODE.SNGL = MODE.SIMPLE +NEGBINOM.DIST = LOI.BINOMIALE.NEG.N +NORM.DIST = LOI.NORMALE.N +NORM.INV = LOI.NORMALE.INVERSE.N +NORM.S.DIST = LOI.NORMALE.STANDARD.N +NORM.S.INV = LOI.NORMALE.STANDARD.INVERSE.N +PEARSON = PEARSON +PERCENTILE.EXC = CENTILE.EXCLURE +PERCENTILE.INC = CENTILE.INCLURE +PERCENTRANK.EXC = RANG.POURCENTAGE.EXCLURE +PERCENTRANK.INC = RANG.POURCENTAGE.INCLURE +PERMUT = PERMUTATION +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = LOI.POISSON.N +PROB = PROBABILITE +QUARTILE.EXC = QUARTILE.EXCLURE +QUARTILE.INC = QUARTILE.INCLURE +RANK.AVG = MOYENNE.RANG +RANK.EQ = EQUATION.RANG +RSQ = COEFFICIENT.DETERMINATION +SKEW = COEFFICIENT.ASYMETRIE +SKEW.P = COEFFICIENT.ASYMETRIE.P +SLOPE = PENTE +SMALL = PETITE.VALEUR +STANDARDIZE = CENTREE.REDUITE +STDEV.P = ECARTYPE.PEARSON +STDEV.S = ECARTYPE.STANDARD +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = ERREUR.TYPE.XY +T.DIST = LOI.STUDENT.N +T.DIST.2T = LOI.STUDENT.BILATERALE +T.DIST.RT = LOI.STUDENT.DROITE +T.INV = LOI.STUDENT.INVERSE.N +T.INV.2T = LOI.STUDENT.INVERSE.BILATERALE +T.TEST = T.TEST +TREND = TENDANCE +TRIMMEAN = MOYENNE.REDUITE +VAR.P = VAR.P.N +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = LOI.WEIBULL.N +Z.TEST = Z.TEST ## -## Statistical functions Fonctions statistiques +## Fonctions de texte (Text Functions) ## -AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données. -AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments. -AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus. -AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés. -AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères. -BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée. -BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée. -BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale. -CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux. -CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux. -CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance. -CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population. -CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données. -COUNT = NB ## Détermine les nombres compris dans la liste des arguments. -COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments. -COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage. -COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage. -COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères. -COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations. -CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère. -DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts. -EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle. -FDIST = LOI.F ## Renvoie la distribution de probabilité F. -FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F. -FISHER = FISHER ## Renvoie la transformation de Fisher. -FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher. -FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire. -FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale. -FTEST = TEST.F ## Renvoie le résultat d’un test F. -GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma. -GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma. -GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x) -GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique. -GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle. -HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique. -HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique. -INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire. -KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données. -LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données. -LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire. -LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle. -LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale. -LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale. -MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments. -MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus. -MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés. -MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments. -MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus. -MODE = MODE ## Renvoie la valeur la plus courante d’une série de données. -NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative. -NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale. -NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard. -NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard. -NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard. -PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson. -PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage. -PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données. -PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets. -POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson. -PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites. -QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données. -RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste. -RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire. -SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution. -SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire. -SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données. -STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite. -STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population. -STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus. -STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière. -STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus. -STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression. -TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student. -TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student. -TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire. -TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données. -TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student. -VAR = VAR ## Calcule la variance sur la base d’un échantillon. -VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses. -VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population. -VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus. -WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull. -ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z. +BAHTTEXT = BAHTTEXT +CHAR = CAR +CLEAN = EPURAGE +CODE = CODE +CONCAT = CONCAT +DOLLAR = DEVISE +EXACT = EXACT +FIND = TROUVE +FIXED = CTXT +LEFT = GAUCHE +LEN = NBCAR +LOWER = MINUSCULE +MID = STXT +NUMBERVALUE = VALEURNOMBRE +PHONETIC = PHONETIQUE +PROPER = NOMPROPRE +REPLACE = REMPLACER +REPT = REPT +RIGHT = DROITE +SEARCH = CHERCHE +SUBSTITUTE = SUBSTITUE +T = T +TEXT = TEXTE +TEXTJOIN = JOINDRE.TEXTE +TRIM = SUPPRESPACE +UNICHAR = UNICAR +UNICODE = UNICODE +UPPER = MAJUSCULE +VALUE = CNUM +## +## Fonctions web (Web Functions) +## +ENCODEURL = URLENCODAGE +FILTERXML = FILTRE.XML +WEBSERVICE = SERVICEWEB ## -## Text functions Fonctions de texte +## Fonctions de compatibilité (Compatibility Functions) ## -ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet). -BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht). -CHAR = CAR ## Renvoie le caractère spécifié par le code numérique. -CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte. -CODE = CODE ## Renvoie le numéro de code du premier caractère du texte. -CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul. -DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro). -EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques. -FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse. -FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse. -FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié. -JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets). -LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. -LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. -LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte. -LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte. -LOWER = MINUSCULE ## Convertit le texte en minuscules. -MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. -MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. -PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte. -PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle. -REPLACE = REMPLACER ## Remplace des caractères dans un texte. -REPLACEB = REMPLACERB ## Remplace des caractères dans un texte. -REPT = REPT ## Répète un texte un certain nombre de fois. -RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. -RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. -SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse). -SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse). -SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau. -T = T ## Convertit ses arguments en texte. -TEXT = TEXTE ## Convertit un nombre au format texte. -TRIM = SUPPRESPACE ## Supprime les espaces du texte. -UPPER = MAJUSCULE ## Convertit le texte en majuscules. -VALUE = CNUM ## Convertit un argument textuel en nombre +BETADIST = LOI.BETA +BETAINV = BETA.INVERSE +BINOMDIST = LOI.BINOMIALE +CEILING = PLAFOND +CHIDIST = LOI.KHIDEUX +CHIINV = KHIDEUX.INVERSE +CHITEST = TEST.KHIDEUX +CONCATENATE = CONCATENER +CONFIDENCE = INTERVALLE.CONFIANCE +COVAR = COVARIANCE +CRITBINOM = CRITERE.LOI.BINOMIALE +EXPONDIST = LOI.EXPONENTIELLE +FDIST = LOI.F +FINV = INVERSE.LOI.F +FLOOR = PLANCHER +FORECAST = PREVISION +FTEST = TEST.F +GAMMADIST = LOI.GAMMA +GAMMAINV = LOI.GAMMA.INVERSE +HYPGEOMDIST = LOI.HYPERGEOMETRIQUE +LOGINV = LOI.LOGNORMALE.INVERSE +LOGNORMDIST = LOI.LOGNORMALE +MODE = MODE +NEGBINOMDIST = LOI.BINOMIALE.NEG +NORMDIST = LOI.NORMALE +NORMINV = LOI.NORMALE.INVERSE +NORMSDIST = LOI.NORMALE.STANDARD +NORMSINV = LOI.NORMALE.STANDARD.INVERSE +PERCENTILE = CENTILE +PERCENTRANK = RANG.POURCENTAGE +POISSON = LOI.POISSON +QUARTILE = QUARTILE +RANK = RANG +STDEV = ECARTYPE +STDEVP = ECARTYPEP +TDIST = LOI.STUDENT +TINV = LOI.STUDENT.INVERSE +TTEST = TEST.STUDENT +VAR = VAR +VARP = VAR.P +WEIBULL = LOI.WEIBULL +ZTEST = TEST.Z diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config index db61436c..dc585d71 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/config @@ -1,23 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - -## -## (For future use) +## Magyar (Hungarian) ## -currencySymbol = Ft +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) +## Error Codes ## -NULL = #NULLA! -DIV0 = #ZÉRÓOSZTÓ! -VALUE = #ÉRTÉK! -REF = #HIV! -NAME = #NÉV? -NUM = #SZÁM! -NA = #HIÁNYZIK +NULL = #NULLA! +DIV0 = #ZÉRÓOSZTÓ! +VALUE = #ÉRTÉK! +REF = #HIV! +NAME = #NÉV? +NUM = #SZÁM! +NA = #HIÁNYZIK diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions index 3adffeb1..46b30127 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/hu/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Magyar (Hungarian) ## +############################################################ ## -## Add-in and Automation functions Bővítmények és automatizálási függvények +## Kockafüggvények (Cube Functions) ## -GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható. - +CUBEKPIMEMBER = KOCKA.FŐTELJMUT +CUBEMEMBER = KOCKA.TAG +CUBEMEMBERPROPERTY = KOCKA.TAG.TUL +CUBERANKEDMEMBER = KOCKA.HALM.ELEM +CUBESET = KOCKA.HALM +CUBESETCOUNT = KOCKA.HALM.DB +CUBEVALUE = KOCKA.ÉRTÉK ## -## Cube functions Kockafüggvények +## Adatbázis-kezelő függvények (Database Functions) ## -CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók. -CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord. -CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság. -CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót. -CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak. -CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül. -CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül. - +DAVERAGE = AB.ÁTLAG +DCOUNT = AB.DARAB +DCOUNTA = AB.DARAB2 +DGET = AB.MEZŐ +DMAX = AB.MAX +DMIN = AB.MIN +DPRODUCT = AB.SZORZAT +DSTDEV = AB.SZÓRÁS +DSTDEVP = AB.SZÓRÁS2 +DSUM = AB.SZUM +DVAR = AB.VAR +DVARP = AB.VAR2 ## -## Database functions Adatbázis-kezelő függvények +## Dátumfüggvények (Date & Time Functions) ## -DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki. -DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat. -DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat. -DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek. -DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül. -DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül. -DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja. -DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást. -DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást. -DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat. -DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre. -DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet. - +DATE = DÁTUM +DATEDIF = DÁTUMTÓLIG +DATESTRING = DÁTUMSZÖVEG +DATEVALUE = DÁTUMÉRTÉK +DAY = NAP +DAYS = NAPOK +DAYS360 = NAP360 +EDATE = KALK.DÁTUM +EOMONTH = HÓNAP.UTOLSÓ.NAP +HOUR = ÓRA +ISOWEEKNUM = ISO.HÉT.SZÁMA +MINUTE = PERCEK +MONTH = HÓNAP +NETWORKDAYS = ÖSSZ.MUNKANAP +NETWORKDAYS.INTL = ÖSSZ.MUNKANAP.INTL +NOW = MOST +SECOND = MPERC +THAIDAYOFWEEK = THAIHÉTNAPJA +THAIMONTHOFYEAR = THAIHÓNAP +THAIYEAR = THAIÉV +TIME = IDŐ +TIMEVALUE = IDŐÉRTÉK +TODAY = MA +WEEKDAY = HÉT.NAPJA +WEEKNUM = HÉT.SZÁMA +WORKDAY = KALK.MUNKANAP +WORKDAY.INTL = KALK.MUNKANAP.INTL +YEAR = ÉV +YEARFRAC = TÖRTÉV ## -## Date and time functions Dátumfüggvények +## Mérnöki függvények (Engineering Functions) ## -DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül. -DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át. -DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít. -DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján. -EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül. -EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül. -HOUR = ÓRA ## Időértéket órákká alakít. -MINUTE = PERC ## Időértéket percekké alakít. -MONTH = HÓNAP ## Időértéket hónapokká alakít. -NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg. -NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül. -SECOND = MPERC ## Időértéket másodpercekké alakít át. -TIME = IDŐ ## Adott időpont időértékét adja meg. -TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át. -TODAY = MA ## A napi dátum dátumértékét adja eredményül. -WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át. -WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik. -WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül. -YEAR = ÉV ## Sorszámot évvé alakít át. -YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.DEC +BIN2HEX = BIN.HEX +BIN2OCT = BIN.OKT +BITAND = BIT.ÉS +BITLSHIFT = BIT.BAL.ELTOL +BITOR = BIT.VAGY +BITRSHIFT = BIT.JOBB.ELTOL +BITXOR = BIT.XVAGY +COMPLEX = KOMPLEX +CONVERT = KONVERTÁLÁS +DEC2BIN = DEC.BIN +DEC2HEX = DEC.HEX +DEC2OCT = DEC.OKT +DELTA = DELTA +ERF = HIBAF +ERF.PRECISE = HIBAF.PONTOS +ERFC = HIBAF.KOMPLEMENTER +ERFC.PRECISE = HIBAFKOMPLEMENTER.PONTOS +GESTEP = KÜSZÖBNÉL.NAGYOBB +HEX2BIN = HEX.BIN +HEX2DEC = HEX.DEC +HEX2OCT = HEX.OKT +IMABS = KÉPZ.ABSZ +IMAGINARY = KÉPZETES +IMARGUMENT = KÉPZ.ARGUMENT +IMCONJUGATE = KÉPZ.KONJUGÁLT +IMCOS = KÉPZ.COS +IMCOSH = KÉPZ.COSH +IMCOT = KÉPZ.COT +IMCSC = KÉPZ.CSC +IMCSCH = KÉPZ.CSCH +IMDIV = KÉPZ.HÁNYAD +IMEXP = KÉPZ.EXP +IMLN = KÉPZ.LN +IMLOG10 = KÉPZ.LOG10 +IMLOG2 = KÉPZ.LOG2 +IMPOWER = KÉPZ.HATV +IMPRODUCT = KÉPZ.SZORZAT +IMREAL = KÉPZ.VALÓS +IMSEC = KÉPZ.SEC +IMSECH = KÉPZ.SECH +IMSIN = KÉPZ.SIN +IMSINH = KÉPZ.SINH +IMSQRT = KÉPZ.GYÖK +IMSUB = KÉPZ.KÜL +IMSUM = KÉPZ.ÖSSZEG +IMTAN = KÉPZ.TAN +OCT2BIN = OKT.BIN +OCT2DEC = OKT.DEC +OCT2HEX = OKT.HEX ## -## Engineering functions Mérnöki függvények +## Pénzügyi függvények (Financial Functions) ## -BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül. -BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül. -BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül. -BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül. -BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át. -BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át. -BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át. -COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez. -CONVERT = CONVERT ## Mértékegységeket vált át. -DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át. -DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át. -DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át. -DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e. -ERF = ERF ## A hibafüggvény értékét adja eredményül. -ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül. -GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél. -HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át. -HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át. -HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át. -IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül. -IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül. -IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül. -IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül. -IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül. -IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül. -IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül. -IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül. -IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül. -IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül. -IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül. -IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül. -IMREAL = IMREAL ## Komplex szám valós részét adja eredményül. -IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül. -IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül. -IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül. -IMSUM = IMSUM ## Komplex számok összegét adja eredményül. -OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át. -OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át. -OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át. - +ACCRINT = IDŐSZAKI.KAMAT +ACCRINTM = LEJÁRATI.KAMAT +AMORDEGRC = ÉRTÉKCSÖKK.TÉNYEZŐVEL +AMORLINC = ÉRTÉKCSÖKK +COUPDAYBS = SZELVÉNYIDŐ.KEZDETTŐL +COUPDAYS = SZELVÉNYIDŐ +COUPDAYSNC = SZELVÉNYIDŐ.KIFIZETÉSTŐL +COUPNCD = ELSŐ.SZELVÉNYDÁTUM +COUPNUM = SZELVÉNYSZÁM +COUPPCD = UTOLSÓ.SZELVÉNYDÁTUM +CUMIPMT = ÖSSZES.KAMAT +CUMPRINC = ÖSSZES.TŐKERÉSZ +DB = KCS2 +DDB = KCSA +DISC = LESZÁM +DOLLARDE = FORINT.DEC +DOLLARFR = FORINT.TÖRT +DURATION = KAMATÉRZ +EFFECT = TÉNYLEGES +FV = JBÉ +FVSCHEDULE = KJÉ +INTRATE = KAMATRÁTA +IPMT = RRÉSZLET +IRR = BMR +ISPMT = LRÉSZLETKAMAT +MDURATION = MKAMATÉRZ +MIRR = MEGTÉRÜLÉS +NOMINAL = NÉVLEGES +NPER = PER.SZÁM +NPV = NMÉ +ODDFPRICE = ELTÉRŐ.EÁR +ODDFYIELD = ELTÉRŐ.EHOZAM +ODDLPRICE = ELTÉRŐ.UÁR +ODDLYIELD = ELTÉRŐ.UHOZAM +PDURATION = KAMATÉRZ.PER +PMT = RÉSZLET +PPMT = PRÉSZLET +PRICE = ÁR +PRICEDISC = ÁR.LESZÁM +PRICEMAT = ÁR.LEJÁRAT +PV = MÉ +RATE = RÁTA +RECEIVED = KAPOTT +RRI = MR +SLN = LCSA +SYD = ÉSZÖ +TBILLEQ = KJEGY.EGYENÉRT +TBILLPRICE = KJEGY.ÁR +TBILLYIELD = KJEGY.HOZAM +VDB = ÉCSRI +XIRR = XBMR +XNPV = XNJÉ +YIELD = HOZAM +YIELDDISC = HOZAM.LESZÁM +YIELDMAT = HOZAM.LEJÁRAT ## -## Financial functions Pénzügyi függvények +## Információs függvények (Information Functions) ## -ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül. -ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül. -AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan. -AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg. -COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza. -COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban. -COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg. -COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül. -COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül. -COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül. -CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül. -CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül. -DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával. -DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával. -DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül. -DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át. -DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át. -DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül. -EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül. -FV = JBÉ ## Befektetés jövőbeli értékét számítja ki. -FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül. -INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül. -IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. -IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz. -ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki. -MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül. -MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett. -NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül. -NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg. -NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett. -ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül. -ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül. -ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül. -ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül. -PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki. -PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. -PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül. -PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül. -PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül. -PV = MÉ ## Befektetés jelenlegi értékét számítja ki. -RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki. -RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül. -SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva. -SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján. -TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül. -TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül. -TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül. -VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával. -XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül. -XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül. -YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül. -YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül. -YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül. - +CELL = CELLA +ERROR.TYPE = HIBA.TÍPUS +INFO = INFÓ +ISBLANK = ÜRES +ISERR = HIBA.E +ISERROR = HIBÁS +ISEVEN = PÁROSE +ISFORMULA = KÉPLET +ISLOGICAL = LOGIKAI +ISNA = NINCS +ISNONTEXT = NEM.SZÖVEG +ISNUMBER = SZÁM +ISODD = PÁRATLANE +ISREF = HIVATKOZÁS +ISTEXT = SZÖVEG.E +N = S +NA = HIÁNYZIK +SHEET = LAP +SHEETS = LAPOK +TYPE = TÍPUS ## -## Information functions Információs függvények +## Logikai függvények (Logical Functions) ## -CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül. -ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül. -INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást. -ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres. -ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével. -ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték. -ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám. -ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték. -ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték. -ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg. -ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám. -ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám. -ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás. -ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg. -N = N ## Argumentumának értékét számmá alakítja. -NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték. -TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül. - +AND = ÉS +FALSE = HAMIS +IF = HA +IFERROR = HAHIBA +IFNA = HAHIÁNYZIK +IFS = HAELSŐIGAZ +NOT = NEM +OR = VAGY +SWITCH = ÁTVÁLT +TRUE = IGAZ +XOR = XVAGY ## -## Logical functions Logikai függvények +## Keresési és hivatkozási függvények (Lookup & Reference Functions) ## -AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ. -FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül. -IF = HA ## Logikai vizsgálatot hajt végre. -IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül. -NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül. -OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ. -TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül. - +ADDRESS = CÍM +AREAS = TERÜLET +CHOOSE = VÁLASZT +COLUMN = OSZLOP +COLUMNS = OSZLOPOK +FORMULATEXT = KÉPLETSZÖVEG +GETPIVOTDATA = KIMUTATÁSADATOT.VESZ +HLOOKUP = VKERES +HYPERLINK = HIPERHIVATKOZÁS +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = KERES +MATCH = HOL.VAN +OFFSET = ELTOLÁS +ROW = SOR +ROWS = SOROK +RTD = VIA +TRANSPOSE = TRANSZPONÁLÁS +VLOOKUP = FKERES ## -## Lookup and reference functions Keresési és hivatkozási függvények +## Matematikai és trigonometrikus függvények (Math & Trig Functions) ## -ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül. -AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül. -CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet. -COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül. -COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül. -HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza. -HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre. -INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza. -INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül. -LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket. -MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres. -OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg. -ROW = SOR ## Egy hivatkozás sorának számát adja meg. -ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg. -RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból. -TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül. -VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül. - +ABS = ABS +ACOS = ARCCOS +ACOSH = ACOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = ÖSSZESÍT +ARABIC = ARAB +ASIN = ARCSIN +ASINH = ASINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ATANH +BASE = ALAP +CEILING.MATH = PLAFON.MAT +CEILING.PRECISE = PLAFON.PONTOS +COMBIN = KOMBINÁCIÓK +COMBINA = KOMBINÁCIÓK.ISM +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = TIZEDES +DEGREES = FOK +ECMA.CEILING = ECMA.PLAFON +EVEN = PÁROS +EXP = KITEVŐ +FACT = FAKT +FACTDOUBLE = FAKTDUPLA +FLOOR.MATH = PADLÓ.MAT +FLOOR.PRECISE = PADLÓ.PONTOS +GCD = LKO +INT = INT +ISO.CEILING = ISO.PLAFON +LCM = LKT +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = INVERZ.MÁTRIX +MMULT = MSZORZAT +MOD = MARADÉK +MROUND = TÖBBSZ.KEREKÍT +MULTINOMIAL = SZORHÁNYFAKT +MUNIT = MMÁTRIX +ODD = PÁRATLAN +PI = PI +POWER = HATVÁNY +PRODUCT = SZORZAT +QUOTIENT = KVÓCIENS +RADIANS = RADIÁN +RAND = VÉL +RANDBETWEEN = VÉLETLEN.KÖZÖTT +ROMAN = RÓMAI +ROUND = KEREKÍTÉS +ROUNDBAHTDOWN = BAHTKEREK.LE +ROUNDBAHTUP = BAHTKEREK.FEL +ROUNDDOWN = KEREK.LE +ROUNDUP = KEREK.FEL +SEC = SEC +SECH = SECH +SERIESSUM = SORÖSSZEG +SIGN = ELŐJEL +SIN = SIN +SINH = SINH +SQRT = GYÖK +SQRTPI = GYÖKPI +SUBTOTAL = RÉSZÖSSZEG +SUM = SZUM +SUMIF = SZUMHA +SUMIFS = SZUMHATÖBB +SUMPRODUCT = SZORZATÖSSZEG +SUMSQ = NÉGYZETÖSSZEG +SUMX2MY2 = SZUMX2BŐLY2 +SUMX2PY2 = SZUMX2MEGY2 +SUMXMY2 = SZUMXBŐLY2 +TAN = TAN +TANH = TANH +TRUNC = CSONK ## -## Math and trigonometry functions Matematikai és trigonometrikus függvények +## Statisztikai függvények (Statistical Functions) ## -ABS = ABS ## Egy szám abszolút értékét adja eredményül. -ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki. -ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki. -ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki. -ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki. -ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki. -ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket. -ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki. -CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít. -COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki. -COS = COS ## Egy szám koszinuszát számítja ki. -COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki. -DEGREES = FOK ## Radiánt fokká alakít át. -EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít. -EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül. -FACT = FAKT ## Egy szám faktoriálisát számítja ki. -FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül. -FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít. -GCD = GCD ## A legnagyobb közös osztót adja eredményül. -INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre. -LCM = LCM ## A legkisebb közös többszöröst adja eredményül. -LN = LN ## Egy szám természetes logaritmusát számítja ki. -LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki. -LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki. -MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki. -MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül. -MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg. -MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül. -MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül. -MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül. -ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít. -PI = PI ## A pi matematikai állandót adja vissza. -POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki. -PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki. -QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül. -RADIANS = RADIÁN ## Fokot radiánná alakít át. -RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül. -RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő. -ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül. -ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít. -ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít. -ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít. -SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül. -SIGN = ELŐJEL ## Egy szám előjelét adja meg. -SIN = SIN ## Egy szög szinuszát számítja ki. -SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki. -SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki. -SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül. -SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül. -SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat. -SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze. -SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül. -SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki. -SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki. -SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi. -SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi. -SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki. -TAN = TAN ## Egy szám tangensét számítja ki. -TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki. -TRUNC = CSONK ## Egy számot egésszé csonkít. - +AVEDEV = ÁTL.ELTÉRÉS +AVERAGE = ÁTLAG +AVERAGEA = ÁTLAGA +AVERAGEIF = ÁTLAGHA +AVERAGEIFS = ÁTLAGHATÖBB +BETA.DIST = BÉTA.ELOSZL +BETA.INV = BÉTA.INVERZ +BINOM.DIST = BINOM.ELOSZL +BINOM.DIST.RANGE = BINOM.ELOSZL.TART +BINOM.INV = BINOM.INVERZ +CHISQ.DIST = KHINÉGYZET.ELOSZLÁS +CHISQ.DIST.RT = KHINÉGYZET.ELOSZLÁS.JOBB +CHISQ.INV = KHINÉGYZET.INVERZ +CHISQ.INV.RT = KHINÉGYZET.INVERZ.JOBB +CHISQ.TEST = KHINÉGYZET.PRÓBA +CONFIDENCE.NORM = MEGBÍZHATÓSÁG.NORM +CONFIDENCE.T = MEGBÍZHATÓSÁG.T +CORREL = KORREL +COUNT = DARAB +COUNTA = DARAB2 +COUNTBLANK = DARABÜRES +COUNTIF = DARABTELI +COUNTIFS = DARABHATÖBB +COVARIANCE.P = KOVARIANCIA.S +COVARIANCE.S = KOVARIANCIA.M +DEVSQ = SQ +EXPON.DIST = EXP.ELOSZL +F.DIST = F.ELOSZL +F.DIST.RT = F.ELOSZLÁS.JOBB +F.INV = F.INVERZ +F.INV.RT = F.INVERZ.JOBB +F.TEST = F.PRÓB +FISHER = FISHER +FISHERINV = INVERZ.FISHER +FORECAST.ETS = ELŐREJELZÉS.ESIM +FORECAST.ETS.CONFINT = ELŐREJELZÉS.ESIM.KONFINT +FORECAST.ETS.SEASONALITY = ELŐREJELZÉS.ESIM.SZEZONALITÁS +FORECAST.ETS.STAT = ELŐREJELZÉS.ESIM.STAT +FORECAST.LINEAR = ELŐREJELZÉS.LINEÁRIS +FREQUENCY = GYAKORISÁG +GAMMA = GAMMA +GAMMA.DIST = GAMMA.ELOSZL +GAMMA.INV = GAMMA.INVERZ +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PONTOS +GAUSS = GAUSS +GEOMEAN = MÉRTANI.KÖZÉP +GROWTH = NÖV +HARMEAN = HARM.KÖZÉP +HYPGEOM.DIST = HIPGEOM.ELOSZLÁS +INTERCEPT = METSZ +KURT = CSÚCSOSSÁG +LARGE = NAGY +LINEST = LIN.ILL +LOGEST = LOG.ILL +LOGNORM.DIST = LOGNORM.ELOSZLÁS +LOGNORM.INV = LOGNORM.INVERZ +MAX = MAX +MAXA = MAXA +MAXIFS = MAXHA +MEDIAN = MEDIÁN +MIN = MIN +MINA = MIN2 +MINIFS = MINHA +MODE.MULT = MÓDUSZ.TÖBB +MODE.SNGL = MÓDUSZ.EGY +NEGBINOM.DIST = NEGBINOM.ELOSZLÁS +NORM.DIST = NORM.ELOSZLÁS +NORM.INV = NORM.INVERZ +NORM.S.DIST = NORM.S.ELOSZLÁS +NORM.S.INV = NORM.S.INVERZ +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTILIS.KIZÁR +PERCENTILE.INC = PERCENTILIS.TARTALMAZ +PERCENTRANK.EXC = SZÁZALÉKRANG.KIZÁR +PERCENTRANK.INC = SZÁZALÉKRANG.TARTALMAZ +PERMUT = VARIÁCIÓK +PERMUTATIONA = VARIÁCIÓK.ISM +PHI = FI +POISSON.DIST = POISSON.ELOSZLÁS +PROB = VALÓSZÍNŰSÉG +QUARTILE.EXC = KVARTILIS.KIZÁR +QUARTILE.INC = KVARTILIS.TARTALMAZ +RANK.AVG = RANG.ÁTL +RANK.EQ = RANG.EGY +RSQ = RNÉGYZET +SKEW = FERDESÉG +SKEW.P = FERDESÉG.P +SLOPE = MEREDEKSÉG +SMALL = KICSI +STANDARDIZE = NORMALIZÁLÁS +STDEV.P = SZÓR.S +STDEV.S = SZÓR.M +STDEVA = SZÓRÁSA +STDEVPA = SZÓRÁSPA +STEYX = STHIBAYX +T.DIST = T.ELOSZL +T.DIST.2T = T.ELOSZLÁS.2SZ +T.DIST.RT = T.ELOSZLÁS.JOBB +T.INV = T.INVERZ +T.INV.2T = T.INVERZ.2SZ +T.TEST = T.PRÓB +TREND = TREND +TRIMMEAN = RÉSZÁTLAG +VAR.P = VAR.S +VAR.S = VAR.M +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.ELOSZLÁS +Z.TEST = Z.PRÓB ## -## Statistical functions Statisztikai függvények +## Szövegműveletekhez használható függvények (Text Functions) ## -AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki. -AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki. -AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket). -AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül. -AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül. -BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki. -BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét. -BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki. -CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki. -CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki. -CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre. -CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül. -CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki. -COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található. -COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található. -COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat. -COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek. -COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek. -COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki. -CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél. -DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki. -EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki. -FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki. -FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki. -FISHER = FISHER ## Fisher-transzformációt hajt végre. -FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre. -FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül. -FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül. -FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül. -GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki. -GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki. -GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki. -GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést. -HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki. -HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki. -INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg. -KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki. -LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül. -LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg. -LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg. -LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki. -LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki. -MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg. -MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket). -MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki. -MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg. -MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket. -MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot. -NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki. -NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki. -NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki. -NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. -PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki. -PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül. -PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki. -PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki. -POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki. -PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek. -QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki. -RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban. -RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét. -SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg. -SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki. -SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg. -STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül. -STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását. -STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket). -STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását. -STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket). -STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki. -TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki. -TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki. -TREND = TREND ## Lineáris trend értékeit számítja ki. -TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki. -TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki. -VAR = VAR ## Minta alapján becslést ad a varianciára. -VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket). -VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki. -VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket). -WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki. -ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki. +BAHTTEXT = BAHTSZÖVEG +CHAR = KARAKTER +CLEAN = TISZTÍT +CODE = KÓD +CONCAT = FŰZ +DOLLAR = FORINT +EXACT = AZONOS +FIND = SZÖVEG.TALÁL +FIXED = FIX +ISTHAIDIGIT = ON.THAI.NUMERO +LEFT = BAL +LEN = HOSSZ +LOWER = KISBETŰ +MID = KÖZÉP +NUMBERSTRING = SZÁM.BETŰVEL +NUMBERVALUE = SZÁMÉRTÉK +PHONETIC = FONETIKUS +PROPER = TNÉV +REPLACE = CSERE +REPT = SOKSZOR +RIGHT = JOBB +SEARCH = SZÖVEG.KERES +SUBSTITUTE = HELYETTE +T = T +TEXT = SZÖVEG +TEXTJOIN = SZÖVEGÖSSZEFŰZÉS +THAIDIGIT = THAISZÁM +THAINUMSOUND = THAISZÁMHANG +THAINUMSTRING = THAISZÁMKAR +THAISTRINGLENGTH = THAIKARHOSSZ +TRIM = KIMETSZ +UNICHAR = UNIKARAKTER +UNICODE = UNICODE +UPPER = NAGYBETŰS +VALUE = ÉRTÉK +## +## Webes függvények (Web Functions) +## +ENCODEURL = URL.KÓDOL +FILTERXML = XMLSZŰRÉS +WEBSERVICE = WEBSZOLGÁLTATÁS ## -## Text functions Szövegműveletekhez használható függvények +## Kompatibilitási függvények (Compatibility Functions) ## -ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja. -BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával. -CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül. -CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert. -CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül. -CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze. -DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át. -EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e. -FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). -FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). -FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve. -JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja. -LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül. -LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül. -LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül. -LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül. -LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át. -MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. -MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. -PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza. -PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli. -REPLACE = CSERE ## A szövegen belül karaktereket cserél. -REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél. -REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt. -RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül. -RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül. -SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). -SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). -SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél. -T = T ## Argumentumát szöveggé alakítja át. -TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé. -TRIM = TRIM ## A szövegből eltávolítja a szóközöket. -UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át. -VALUE = ÉRTÉK ## Szöveget számmá alakít át. +BETADIST = BÉTA.ELOSZLÁS +BETAINV = INVERZ.BÉTA +BINOMDIST = BINOM.ELOSZLÁS +CEILING = PLAFON +CHIDIST = KHI.ELOSZLÁS +CHIINV = INVERZ.KHI +CHITEST = KHI.PRÓBA +CONCATENATE = ÖSSZEFŰZ +CONFIDENCE = MEGBÍZHATÓSÁG +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXP.ELOSZLÁS +FDIST = F.ELOSZLÁS +FINV = INVERZ.F +FLOOR = PADLÓ +FORECAST = ELŐREJELZÉS +FTEST = F.PRÓBA +GAMMADIST = GAMMA.ELOSZLÁS +GAMMAINV = INVERZ.GAMMA +HYPGEOMDIST = HIPERGEOM.ELOSZLÁS +LOGINV = INVERZ.LOG.ELOSZLÁS +LOGNORMDIST = LOG.ELOSZLÁS +MODE = MÓDUSZ +NEGBINOMDIST = NEGBINOM.ELOSZL +NORMDIST = NORM.ELOSZL +NORMINV = INVERZ.NORM +NORMSDIST = STNORMELOSZL +NORMSINV = INVERZ.STNORM +PERCENTILE = PERCENTILIS +PERCENTRANK = SZÁZALÉKRANG +POISSON = POISSON +QUARTILE = KVARTILIS +RANK = SORSZÁM +STDEV = SZÓRÁS +STDEVP = SZÓRÁSP +TDIST = T.ELOSZLÁS +TINV = INVERZ.T +TTEST = T.PRÓBA +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = Z.PRÓBA diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config index 6cc013ae..5c1e4955 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Italiano (Italian) ## -## (For future use) -## -currencySymbol = € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NULLO! -DIV0 = #DIV/0! -VALUE = #VALORE! -REF = #RIF! -NAME = #NOME? -NUM = #NUM! -NA = #N/D +NULL +DIV0 +VALUE = #VALORE! +REF = #RIF! +NAME = #NOME? +NUM +NA = #N/D diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions index 1901bafa..c14ed85f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/it/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Italiano (Italian) ## +############################################################ ## -## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi +## Funzioni cubo (Cube Functions) ## -GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot - +CUBEKPIMEMBER = MEMBRO.KPI.CUBO +CUBEMEMBER = MEMBRO.CUBO +CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO +CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO +CUBESET = SET.CUBO +CUBESETCOUNT = CONTA.SET.CUBO +CUBEVALUE = VALORE.CUBO ## -## Cube functions Funzioni cubo +## Funzioni di database (Database Functions) ## -CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione. -CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo. -CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro. -CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti. -CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel. -CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme. -CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo. - +DAVERAGE = DB.MEDIA +DCOUNT = DB.CONTA.NUMERI +DCOUNTA = DB.CONTA.VALORI +DGET = DB.VALORI +DMAX = DB.MAX +DMIN = DB.MIN +DPRODUCT = DB.PRODOTTO +DSTDEV = DB.DEV.ST +DSTDEVP = DB.DEV.ST.POP +DSUM = DB.SOMMA +DVAR = DB.VAR +DVARP = DB.VAR.POP ## -## Database functions Funzioni di database +## Funzioni data e ora (Date & Time Functions) ## -DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate -DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri -DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database -DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati -DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database -DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate -DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database -DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate -DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate -DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri -DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate -DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate - +DATE = DATA +DATEDIF = DATA.DIFF +DATESTRING = DATA.STRINGA +DATEVALUE = DATA.VALORE +DAY = GIORNO +DAYS = GIORNI +DAYS360 = GIORNO360 +EDATE = DATA.MESE +EOMONTH = FINE.MESE +HOUR = ORA +ISOWEEKNUM = NUM.SETTIMANA.ISO +MINUTE = MINUTO +MONTH = MESE +NETWORKDAYS = GIORNI.LAVORATIVI.TOT +NETWORKDAYS.INTL = GIORNI.LAVORATIVI.TOT.INTL +NOW = ADESSO +SECOND = SECONDO +THAIDAYOFWEEK = THAIGIORNODELLASETTIMANA +THAIMONTHOFYEAR = THAIMESEDELLANNO +THAIYEAR = THAIANNO +TIME = ORARIO +TIMEVALUE = ORARIO.VALORE +TODAY = OGGI +WEEKDAY = GIORNO.SETTIMANA +WEEKNUM = NUM.SETTIMANA +WORKDAY = GIORNO.LAVORATIVO +WORKDAY.INTL = GIORNO.LAVORATIVO.INTL +YEAR = ANNO +YEARFRAC = FRAZIONE.ANNO ## -## Date and time functions Funzioni data e ora +## Funzioni ingegneristiche (Engineering Functions) ## -DATE = DATA ## Restituisce il numero seriale di una determinata data -DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale -DAY = GIORNO ## Converte un numero seriale in un giorno del mese -DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni -EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio -EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi -HOUR = ORA ## Converte un numero seriale in un'ora -MINUTE = MINUTO ## Converte un numero seriale in un minuto -MONTH = MESE ## Converte un numero seriale in un mese -NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date -NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente -SECOND = SECONDO ## Converte un numero seriale in un secondo -TIME = ORARIO ## Restituisce il numero seriale di una determinata ora -TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale -TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna -WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana -WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno -WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi -YEAR = ANNO ## Converte un numero seriale in un anno -YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = BINARIO.DECIMALE +BIN2HEX = BINARIO.HEX +BIN2OCT = BINARIO.OCT +BITAND = BITAND +BITLSHIFT = BIT.SPOSTA.SX +BITOR = BITOR +BITRSHIFT = BIT.SPOSTA.DX +BITXOR = BITXOR +COMPLEX = COMPLESSO +CONVERT = CONVERTI +DEC2BIN = DECIMALE.BINARIO +DEC2HEX = DECIMALE.HEX +DEC2OCT = DECIMALE.OCT +DELTA = DELTA +ERF = FUNZ.ERRORE +ERF.PRECISE = FUNZ.ERRORE.PRECISA +ERFC = FUNZ.ERRORE.COMP +ERFC.PRECISE = FUNZ.ERRORE.COMP.PRECISA +GESTEP = SOGLIA +HEX2BIN = HEX.BINARIO +HEX2DEC = HEX.DECIMALE +HEX2OCT = HEX.OCT +IMABS = COMP.MODULO +IMAGINARY = COMP.IMMAGINARIO +IMARGUMENT = COMP.ARGOMENTO +IMCONJUGATE = COMP.CONIUGATO +IMCOS = COMP.COS +IMCOSH = COMP.COSH +IMCOT = COMP.COT +IMCSC = COMP.CSC +IMCSCH = COMP.CSCH +IMDIV = COMP.DIV +IMEXP = COMP.EXP +IMLN = COMP.LN +IMLOG10 = COMP.LOG10 +IMLOG2 = COMP.LOG2 +IMPOWER = COMP.POTENZA +IMPRODUCT = COMP.PRODOTTO +IMREAL = COMP.PARTE.REALE +IMSEC = COMP.SEC +IMSECH = COMP.SECH +IMSIN = COMP.SEN +IMSINH = COMP.SENH +IMSQRT = COMP.RADQ +IMSUB = COMP.DIFF +IMSUM = COMP.SOMMA +IMTAN = COMP.TAN +OCT2BIN = OCT.BINARIO +OCT2DEC = OCT.DECIMALE +OCT2HEX = OCT.HEX ## -## Engineering functions Funzioni ingegneristiche +## Funzioni finanziarie (Financial Functions) ## -BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x) -BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x) -BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x) -BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x) -BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale -BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale -BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale -COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi -CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro -DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario -DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale -DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale -DELTA = DELTA ## Verifica se due valori sono uguali -ERF = FUNZ.ERRORE ## Restituisce la funzione di errore -ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare -GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia -HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario -HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale -HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale -IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso -IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso -IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti -IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso -IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso -IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi -IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso -IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso -IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso -IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso -IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera -IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29 -IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso -IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso -IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso -IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi -IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi -OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario -OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale -OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale - +ACCRINT = INT.MATURATO.PER +ACCRINTM = INT.MATURATO.SCAD +AMORDEGRC = AMMORT.DEGR +AMORLINC = AMMORT.PER +COUPDAYBS = GIORNI.CED.INIZ.LIQ +COUPDAYS = GIORNI.CED +COUPDAYSNC = GIORNI.CED.NUOVA +COUPNCD = DATA.CED.SUCC +COUPNUM = NUM.CED +COUPPCD = DATA.CED.PREC +CUMIPMT = INT.CUMUL +CUMPRINC = CAP.CUM +DB = AMMORT.FISSO +DDB = AMMORT +DISC = TASSO.SCONTO +DOLLARDE = VALUTA.DEC +DOLLARFR = VALUTA.FRAZ +DURATION = DURATA +EFFECT = EFFETTIVO +FV = VAL.FUT +FVSCHEDULE = VAL.FUT.CAPITALE +INTRATE = TASSO.INT +IPMT = INTERESSI +IRR = TIR.COST +ISPMT = INTERESSE.RATA +MDURATION = DURATA.M +MIRR = TIR.VAR +NOMINAL = NOMINALE +NPER = NUM.RATE +NPV = VAN +ODDFPRICE = PREZZO.PRIMO.IRR +ODDFYIELD = REND.PRIMO.IRR +ODDLPRICE = PREZZO.ULTIMO.IRR +ODDLYIELD = REND.ULTIMO.IRR +PDURATION = DURATA.P +PMT = RATA +PPMT = P.RATA +PRICE = PREZZO +PRICEDISC = PREZZO.SCONT +PRICEMAT = PREZZO.SCAD +PV = VA +RATE = TASSO +RECEIVED = RICEV.SCAD +RRI = RIT.INVEST.EFFETT +SLN = AMMORT.COST +SYD = AMMORT.ANNUO +TBILLEQ = BOT.EQUIV +TBILLPRICE = BOT.PREZZO +TBILLYIELD = BOT.REND +VDB = AMMORT.VAR +XIRR = TIR.X +XNPV = VAN.X +YIELD = REND +YIELDDISC = REND.TITOLI.SCONT +YIELDMAT = REND.SCAD ## -## Financial functions Funzioni finanziarie +## Funzioni relative alle informazioni (Information Functions) ## -ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici -ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza -AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento -AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile -COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione -COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione -COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva -COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione -COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza -COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione -CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi -CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi -DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti -DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati -DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo -DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale -DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione -DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico -EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo -FV = VAL.FUT ## Restituisce il valore futuro di un investimento -FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti -INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito -IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico -IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa -ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico -MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100 -MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti -NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale -NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento -NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto -ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare -ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare -ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare -ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare -PMT = RATA ## Restituisce il pagamento periodico di una rendita annua -PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo -PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici -PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100 -PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza -PV = VA ## Restituisce il valore attuale di un investimento -RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità -RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito -SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo -SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato -TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro -TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100 -TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro -VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui -XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa -XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici -YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici -YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro -YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza - +CELL = CELLA +ERROR.TYPE = ERRORE.TIPO +INFO = AMBIENTE.INFO +ISBLANK = VAL.VUOTO +ISERR = VAL.ERR +ISERROR = VAL.ERRORE +ISEVEN = VAL.PARI +ISFORMULA = VAL.FORMULA +ISLOGICAL = VAL.LOGICO +ISNA = VAL.NON.DISP +ISNONTEXT = VAL.NON.TESTO +ISNUMBER = VAL.NUMERO +ISODD = VAL.DISPARI +ISREF = VAL.RIF +ISTEXT = VAL.TESTO +N = NUM +NA = NON.DISP +SHEET = FOGLIO +SHEETS = FOGLI +TYPE = TIPO ## -## Information functions Funzioni relative alle informazioni +## Funzioni logiche (Logical Functions) ## -CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella -ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore -INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente -ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto -ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D -ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi -ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari -ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico -ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D -ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo -ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero -ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari -ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento -ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo -N = NUM ## Restituisce un valore convertito in numero -NA = NON.DISP ## Restituisce il valore di errore #N/D -TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SE.ERRORE +IFNA = SE.NON.DISP. +IFS = PIÙ.SE +NOT = NON +OR = O +SWITCH = SWITCH +TRUE = VERO +XOR = XOR ## -## Logical functions Funzioni logiche +## Funzioni di ricerca e di riferimento (Lookup & Reference Functions) ## -AND = E ## Restituisce VERO se tutti gli argomenti sono VERO -FALSE = FALSO ## Restituisce il valore logico FALSO -IF = SE ## Specifica un test logico da eseguire -IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula -NOT = NON ## Inverte la logica degli argomenti -OR = O ## Restituisce VERO se un argomento qualsiasi è VERO -TRUE = VERO ## Restituisce il valore logico VERO - +ADDRESS = INDIRIZZO +AREAS = AREE +CHOOSE = SCEGLI +COLUMN = RIF.COLONNA +COLUMNS = COLONNE +FORMULATEXT = TESTO.FORMULA +GETPIVOTDATA = INFO.DATI.TAB.PIVOT +HLOOKUP = CERCA.ORIZZ +HYPERLINK = COLLEG.IPERTESTUALE +INDEX = INDICE +INDIRECT = INDIRETTO +LOOKUP = CERCA +MATCH = CONFRONTA +OFFSET = SCARTO +ROW = RIF.RIGA +ROWS = RIGHE +RTD = DATITEMPOREALE +TRANSPOSE = MATR.TRASPOSTA +VLOOKUP = CERCA.VERT ## -## Lookup and reference functions Funzioni di ricerca e di riferimento +## Funzioni matematiche e trigonometriche (Math & Trig Functions) ## -ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro -AREAS = AREE ## Restituisce il numero di aree in un riferimento -CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori -COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento -COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento -HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata -HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet -INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice -INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo -LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice -MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice -OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato -ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento -ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento -RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).) -TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice -VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella - +ABS = ASS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = AGGREGA +ARABIC = ARABO +ASIN = ARCSEN +ASINH = ARCSENH +ATAN = ARCTAN +ATAN2 = ARCTAN.2 +ATANH = ARCTANH +BASE = BASE +CEILING.MATH = ARROTONDA.ECCESSO.MAT +CEILING.PRECISE = ARROTONDA.ECCESSO.PRECISA +COMBIN = COMBINAZIONE +COMBINA = COMBINAZIONE.VALORI +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMALE +DEGREES = GRADI +ECMA.CEILING = ECMA.ARROTONDA.ECCESSO +EVEN = PARI +EXP = EXP +FACT = FATTORIALE +FACTDOUBLE = FATT.DOPPIO +FLOOR.MATH = ARROTONDA.DIFETTO.MAT +FLOOR.PRECISE = ARROTONDA.DIFETTO.PRECISA +GCD = MCD +INT = INT +ISO.CEILING = ISO.ARROTONDA.ECCESSO +LCM = MCM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATR.DETERM +MINVERSE = MATR.INVERSA +MMULT = MATR.PRODOTTO +MOD = RESTO +MROUND = ARROTONDA.MULTIPLO +MULTINOMIAL = MULTINOMIALE +MUNIT = MATR.UNIT +ODD = DISPARI +PI = PI.GRECO +POWER = POTENZA +PRODUCT = PRODOTTO +QUOTIENT = QUOZIENTE +RADIANS = RADIANTI +RAND = CASUALE +RANDBETWEEN = CASUALE.TRA +ROMAN = ROMANO +ROUND = ARROTONDA +ROUNDBAHTDOWN = ARROTBAHTGIU +ROUNDBAHTUP = ARROTBAHTSU +ROUNDDOWN = ARROTONDA.PER.DIF +ROUNDUP = ARROTONDA.PER.ECC +SEC = SEC +SECH = SECH +SERIESSUM = SOMMA.SERIE +SIGN = SEGNO +SIN = SEN +SINH = SENH +SQRT = RADQ +SQRTPI = RADQ.PI.GRECO +SUBTOTAL = SUBTOTALE +SUM = SOMMA +SUMIF = SOMMA.SE +SUMIFS = SOMMA.PIÙ.SE +SUMPRODUCT = MATR.SOMMA.PRODOTTO +SUMSQ = SOMMA.Q +SUMX2MY2 = SOMMA.DIFF.Q +SUMX2PY2 = SOMMA.SOMMA.Q +SUMXMY2 = SOMMA.Q.DIFF +TAN = TAN +TANH = TANH +TRUNC = TRONCA ## -## Math and trigonometry functions Funzioni matematiche e trigonometriche +## Funzioni statistiche (Statistical Functions) ## -ABS = ASS ## Restituisce il valore assoluto di un numero. -ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero -ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero -ASIN = ARCSEN ## Restituisce l'arcoseno di un numero -ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero -ATAN = ARCTAN ## Restituisce l'arcotangente di un numero -ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate -ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero -CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso -COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi -COS = COS ## Restituisce il coseno dell'angolo specificato -COSH = COSH ## Restituisce il coseno iperbolico di un numero -DEGREES = GRADI ## Converte i radianti in gradi -EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari -EXP = ESP ## Restituisce il numero e elevato alla potenza di num -FACT = FATTORIALE ## Restituisce il fattoriale di un numero -FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero -FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero -GCD = MCD ## Restituisce il massimo comune divisore -INT = INT ## Arrotonda un numero per difetto al numero intero più vicino -LCM = MCM ## Restituisce il minimo comune multiplo -LN = LN ## Restituisce il logaritmo naturale di un numero -LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base -LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero -MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice -MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice -MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici -MOD = RESTO ## Restituisce il resto della divisione -MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato -MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri -ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari -PI = PI.GRECO ## Restituisce il valore di pi greco -POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza -PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti -QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione -RADIANS = RADIANTI ## Converte i gradi in radianti -RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1 -RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati -ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo -ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato -ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto -ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso -SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula -SIGN = SEGNO ## Restituisce il segno di un numero -SIN = SEN ## Restituisce il seno di un dato angolo -SINH = SENH ## Restituisce il seno iperbolico di un numero -SQRT = RADQ ## Restituisce una radice quadrata -SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco) -SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database -SUM = SOMMA ## Somma i suoi argomenti -SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio -SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri -SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice -SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti -SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici -SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici -SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici -TAN = TAN ## Restituisce la tangente di un numero -TANH = TANH ## Restituisce la tangente iperbolica di un numero -TRUNC = TRONCA ## Tronca la parte decimale di un numero - +AVEDEV = MEDIA.DEV +AVERAGE = MEDIA +AVERAGEA = MEDIA.VALORI +AVERAGEIF = MEDIA.SE +AVERAGEIFS = MEDIA.PIÙ.SE +BETA.DIST = DISTRIB.BETA.N +BETA.INV = INV.BETA.N +BINOM.DIST = DISTRIB.BINOM.N +BINOM.DIST.RANGE = INTERVALLO.DISTRIB.BINOM.N. +BINOM.INV = INV.BINOM +CHISQ.DIST = DISTRIB.CHI.QUAD +CHISQ.DIST.RT = DISTRIB.CHI.QUAD.DS +CHISQ.INV = INV.CHI.QUAD +CHISQ.INV.RT = INV.CHI.QUAD.DS +CHISQ.TEST = TEST.CHI.QUAD +CONFIDENCE.NORM = CONFIDENZA.NORM +CONFIDENCE.T = CONFIDENZA.T +CORREL = CORRELAZIONE +COUNT = CONTA.NUMERI +COUNTA = CONTA.VALORI +COUNTBLANK = CONTA.VUOTE +COUNTIF = CONTA.SE +COUNTIFS = CONTA.PIÙ.SE +COVARIANCE.P = COVARIANZA.P +COVARIANCE.S = COVARIANZA.C +DEVSQ = DEV.Q +EXPON.DIST = DISTRIB.EXP.N +F.DIST = DISTRIBF +F.DIST.RT = DISTRIB.F.DS +F.INV = INVF +F.INV.RT = INV.F.DS +F.TEST = TESTF +FISHER = FISHER +FISHERINV = INV.FISHER +FORECAST.ETS = PREVISIONE.ETS +FORECAST.ETS.CONFINT = PREVISIONE.ETS.INTCONF +FORECAST.ETS.SEASONALITY = PREVISIONE.ETS.STAGIONALITÀ +FORECAST.ETS.STAT = PREVISIONE.ETS.STAT +FORECAST.LINEAR = PREVISIONE.LINEARE +FREQUENCY = FREQUENZA +GAMMA = GAMMA +GAMMA.DIST = DISTRIB.GAMMA.N +GAMMA.INV = INV.GAMMA.N +GAMMALN = LN.GAMMA +GAMMALN.PRECISE = LN.GAMMA.PRECISA +GAUSS = GAUSS +GEOMEAN = MEDIA.GEOMETRICA +GROWTH = CRESCITA +HARMEAN = MEDIA.ARMONICA +HYPGEOM.DIST = DISTRIB.IPERGEOM.N +INTERCEPT = INTERCETTA +KURT = CURTOSI +LARGE = GRANDE +LINEST = REGR.LIN +LOGEST = REGR.LOG +LOGNORM.DIST = DISTRIB.LOGNORM.N +LOGNORM.INV = INV.LOGNORM.N +MAX = MAX +MAXA = MAX.VALORI +MAXIFS = MAX.PIÙ.SE +MEDIAN = MEDIANA +MIN = MIN +MINA = MIN.VALORI +MINIFS = MIN.PIÙ.SE +MODE.MULT = MODA.MULT +MODE.SNGL = MODA.SNGL +NEGBINOM.DIST = DISTRIB.BINOM.NEG.N +NORM.DIST = DISTRIB.NORM.N +NORM.INV = INV.NORM.N +NORM.S.DIST = DISTRIB.NORM.ST.N +NORM.S.INV = INV.NORM.S +PEARSON = PEARSON +PERCENTILE.EXC = ESC.PERCENTILE +PERCENTILE.INC = INC.PERCENTILE +PERCENTRANK.EXC = ESC.PERCENT.RANGO +PERCENTRANK.INC = INC.PERCENT.RANGO +PERMUT = PERMUTAZIONE +PERMUTATIONA = PERMUTAZIONE.VALORI +PHI = PHI +POISSON.DIST = DISTRIB.POISSON +PROB = PROBABILITÀ +QUARTILE.EXC = ESC.QUARTILE +QUARTILE.INC = INC.QUARTILE +RANK.AVG = RANGO.MEDIA +RANK.EQ = RANGO.UG +RSQ = RQ +SKEW = ASIMMETRIA +SKEW.P = ASIMMETRIA.P +SLOPE = PENDENZA +SMALL = PICCOLO +STANDARDIZE = NORMALIZZA +STDEV.P = DEV.ST.P +STDEV.S = DEV.ST.C +STDEVA = DEV.ST.VALORI +STDEVPA = DEV.ST.POP.VALORI +STEYX = ERR.STD.YX +T.DIST = DISTRIB.T.N +T.DIST.2T = DISTRIB.T.2T +T.DIST.RT = DISTRIB.T.DS +T.INV = INVT +T.INV.2T = INV.T.2T +T.TEST = TESTT +TREND = TENDENZA +TRIMMEAN = MEDIA.TRONCATA +VAR.P = VAR.P +VAR.S = VAR.C +VARA = VAR.VALORI +VARPA = VAR.POP.VALORI +WEIBULL.DIST = DISTRIB.WEIBULL +Z.TEST = TESTZ ## -## Statistical functions Funzioni statistiche +## Funzioni di testo (Text Functions) ## -AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media -AVERAGE = MEDIA ## Restituisce la media degli argomenti -AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici -AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio -AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri -BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta -BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata -BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale -CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato -CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato -CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza -CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione -CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati -COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti -COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti -COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo -COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati -COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri. -COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate -CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio -DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni -EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale -FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F -FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F -FISHER = FISHER ## Restituisce la trasformazione di Fisher -FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher -FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare -FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale -FTEST = TEST.F ## Restituisce il risultato di un test F -GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma -GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma -GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x) -GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica -GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale -HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica -HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica -INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare -KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati -LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati -LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare -LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale -LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale -LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa -MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti -MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici -MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati -MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti -MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici -MODE = MODA ## Restituisce il valore più comune in un insieme di dati -NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa -NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale -NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard -NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard -NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale -PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson -PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo -PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale -PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti -POISSON = POISSON ## Restituisce la distribuzione di Poisson -PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti -QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati -RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri -RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson -SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione -SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare -SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati -STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato -STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione -STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici -STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione -STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici -STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione -TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student -TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student -TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare -TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati -TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student -VAR = VAR ## Stima la varianza sulla base di un campione -VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici -VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione -VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici -WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull -ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z +BAHTTEXT = BAHTTESTO +CHAR = CODICE.CARATT +CLEAN = LIBERA +CODE = CODICE +CONCAT = CONCAT +DOLLAR = VALUTA +EXACT = IDENTICO +FIND = TROVA +FIXED = FISSO +ISTHAIDIGIT = ÈTHAICIFRA +LEFT = SINISTRA +LEN = LUNGHEZZA +LOWER = MINUSC +MID = STRINGA.ESTRAI +NUMBERSTRING = NUMERO.STRINGA +NUMBERVALUE = NUMERO.VALORE +PHONETIC = FURIGANA +PROPER = MAIUSC.INIZ +REPLACE = RIMPIAZZA +REPT = RIPETI +RIGHT = DESTRA +SEARCH = RICERCA +SUBSTITUTE = SOSTITUISCI +T = T +TEXT = TESTO +TEXTJOIN = TESTO.UNISCI +THAIDIGIT = THAICIFRA +THAINUMSOUND = THAINUMSUONO +THAINUMSTRING = THAISZÁMKAR +THAISTRINGLENGTH = THAILUNGSTRINGA +TRIM = ANNULLA.SPAZI +UNICHAR = CARATT.UNI +UNICODE = UNICODE +UPPER = MAIUSC +VALUE = VALORE +## +## Funzioni Web (Web Functions) +## +ENCODEURL = CODIFICA.URL +FILTERXML = FILTRO.XML +WEBSERVICE = SERVIZIO.WEB ## -## Text functions Funzioni di testo +## Funzioni di compatibilità (Compatibility Functions) ## -ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte -BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht) -CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice -CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare -CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo -CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo -DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro) -EXACT = IDENTICO ## Verifica se due valori di testo sono uguali -FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) -FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) -FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali -JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio. -LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo -LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo -LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo -LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo -LOWER = MINUSC ## Converte il testo in lettere minuscole -MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata -MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata -PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo. -PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo -REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo -REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo -REPT = RIPETI ## Ripete un testo per un dato numero di volte -RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo -RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo -SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) -SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) -SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa -T = T ## Converte gli argomenti in testo -TEXT = TESTO ## Formatta un numero e lo converte in testo -TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo -UPPER = MAIUSC ## Converte il testo in lettere maiuscole -VALUE = VALORE ## Converte un argomento di testo in numero +BETADIST = DISTRIB.BETA +BETAINV = INV.BETA +BINOMDIST = DISTRIB.BINOM +CEILING = ARROTONDA.ECCESSO +CHIDIST = DISTRIB.CHI +CHIINV = INV.CHI +CHITEST = TEST.CHI +CONCATENATE = CONCATENA +CONFIDENCE = CONFIDENZA +COVAR = COVARIANZA +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTRIB.EXP +FDIST = DISTRIB.F +FINV = INV.F +FLOOR = ARROTONDA.DIFETTO +FORECAST = PREVISIONE +FTEST = TEST.F +GAMMADIST = DISTRIB.GAMMA +GAMMAINV = INV.GAMMA +HYPGEOMDIST = DISTRIB.IPERGEOM +LOGINV = INV.LOGNORM +LOGNORMDIST = DISTRIB.LOGNORM +MODE = MODA +NEGBINOMDIST = DISTRIB.BINOM.NEG +NORMDIST = DISTRIB.NORM +NORMINV = INV.NORM +NORMSDIST = DISTRIB.NORM.ST +NORMSINV = INV.NORM.ST +PERCENTILE = PERCENTILE +PERCENTRANK = PERCENT.RANGO +POISSON = POISSON +QUARTILE = QUARTILE +RANK = RANGO +STDEV = DEV.ST +STDEVP = DEV.ST.POP +TDIST = DISTRIB.T +TINV = INV.T +TTEST = TEST.T +VAR = VAR +VARP = VAR.POP +WEIBULL = WEIBULL +ZTEST = TEST.Z diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config new file mode 100644 index 00000000..a7f3be17 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/config @@ -0,0 +1,20 @@ +############################################################ +## +## PhpSpreadsheet - locale settings +## +## Norsk Bokmål (Norwegian Bokmål) +## +############################################################ + +ArgumentSeparator = ; + +## +## Error Codes +## +NULL +DIV0 +VALUE = #VERDI! +REF +NAME = #NAVN? +NUM +NA = #N/D diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions new file mode 100644 index 00000000..b0a0f949 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nb/functions @@ -0,0 +1,538 @@ +############################################################ +## +## PhpSpreadsheet - function name translations +## +## Norsk Bokmål (Norwegian Bokmål) +## +############################################################ + + +## +## Kubefunksjoner (Cube Functions) +## +CUBEKPIMEMBER = KUBEKPIMEDLEM +CUBEMEMBER = KUBEMEDLEM +CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP +CUBERANKEDMEMBER = KUBERANGERTMEDLEM +CUBESET = KUBESETT +CUBESETCOUNT = KUBESETTANTALL +CUBEVALUE = KUBEVERDI + +## +## Databasefunksjoner (Database Functions) +## +DAVERAGE = DGJENNOMSNITT +DCOUNT = DANTALL +DCOUNTA = DANTALLA +DGET = DHENT +DMAX = DMAKS +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAV +DSTDEVP = DSTDAVP +DSUM = DSUMMER +DVAR = DVARIANS +DVARP = DVARIANSP + +## +## Dato- og tidsfunksjoner (Date & Time Functions) +## +DATE = DATO +DATEDIF = DATODIFF +DATESTRING = DATOSTRENG +DATEVALUE = DATOVERDI +DAY = DAG +DAYS = DAGER +DAYS360 = DAGER360 +EDATE = DAG.ETTER +EOMONTH = MÅNEDSSLUTT +HOUR = TIME +ISOWEEKNUM = ISOUKENR +MINUTE = MINUTT +MONTH = MÅNED +NETWORKDAYS = NETT.ARBEIDSDAGER +NETWORKDAYS.INTL = NETT.ARBEIDSDAGER.INTL +NOW = NÅ +SECOND = SEKUND +THAIDAYOFWEEK = THAIUKEDAG +THAIMONTHOFYEAR = THAIMÅNED +THAIYEAR = THAIÅR +TIME = TID +TIMEVALUE = TIDSVERDI +TODAY = IDAG +WEEKDAY = UKEDAG +WEEKNUM = UKENR +WORKDAY = ARBEIDSDAG +WORKDAY.INTL = ARBEIDSDAG.INTL +YEAR = ÅR +YEARFRAC = ÅRDEL + +## +## Tekniske funksjoner (Engineering Functions) +## +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINTILDES +BIN2HEX = BINTILHEKS +BIN2OCT = BINTILOKT +BITAND = BITOG +BITLSHIFT = BITVFORSKYV +BITOR = BITELLER +BITRSHIFT = BITHFORSKYV +BITXOR = BITEKSKLUSIVELLER +COMPLEX = KOMPLEKS +CONVERT = KONVERTER +DEC2BIN = DESTILBIN +DEC2HEX = DESTILHEKS +DEC2OCT = DESTILOKT +DELTA = DELTA +ERF = FEILF +ERF.PRECISE = FEILF.PRESIS +ERFC = FEILFK +ERFC.PRECISE = FEILFK.PRESIS +GESTEP = GRENSEVERDI +HEX2BIN = HEKSTILBIN +HEX2DEC = HEKSTILDES +HEX2OCT = HEKSTILOKT +IMABS = IMABS +IMAGINARY = IMAGINÆR +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGERT +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEKSP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMOPPHØY +IMPRODUCT = IMPRODUKT +IMREAL = IMREELL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMROT +IMSUB = IMSUB +IMSUM = IMSUMMER +IMTAN = IMTAN +OCT2BIN = OKTTILBIN +OCT2DEC = OKTTILDES +OCT2HEX = OKTTILHEKS + +## +## Økonomiske funksjoner (Financial Functions) +## +ACCRINT = PÅLØPT.PERIODISK.RENTE +ACCRINTM = PÅLØPT.FORFALLSRENTE +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = OBLIG.DAGER.FF +COUPDAYS = OBLIG.DAGER +COUPDAYSNC = OBLIG.DAGER.NF +COUPNCD = OBLIG.DAGER.EF +COUPNUM = OBLIG.ANTALL +COUPPCD = OBLIG.DAG.FORRIGE +CUMIPMT = SAMLET.RENTE +CUMPRINC = SAMLET.HOVEDSTOL +DB = DAVSKR +DDB = DEGRAVS +DISC = DISKONTERT +DOLLARDE = DOLLARDE +DOLLARFR = DOLLARBR +DURATION = VARIGHET +EFFECT = EFFEKTIV.RENTE +FV = SLUTTVERDI +FVSCHEDULE = SVPLAN +INTRATE = RENTESATS +IPMT = RAVDRAG +IRR = IR +ISPMT = ER.AVDRAG +MDURATION = MVARIGHET +MIRR = MODIR +NOMINAL = NOMINELL +NPER = PERIODER +NPV = NNV +ODDFPRICE = AVVIKFP.PRIS +ODDFYIELD = AVVIKFP.AVKASTNING +ODDLPRICE = AVVIKSP.PRIS +ODDLYIELD = AVVIKSP.AVKASTNING +PDURATION = PVARIGHET +PMT = AVDRAG +PPMT = AMORT +PRICE = PRIS +PRICEDISC = PRIS.DISKONTERT +PRICEMAT = PRIS.FORFALL +PV = NÅVERDI +RATE = RENTE +RECEIVED = MOTTATT.AVKAST +RRI = REALISERT.AVKASTNING +SLN = LINAVS +SYD = ÅRSAVS +TBILLEQ = TBILLEKV +TBILLPRICE = TBILLPRIS +TBILLYIELD = TBILLAVKASTNING +VDB = VERDIAVS +XIRR = XIR +XNPV = XNNV +YIELD = AVKAST +YIELDDISC = AVKAST.DISKONTERT +YIELDMAT = AVKAST.FORFALL + +## +## Informasjonsfunksjoner (Information Functions) +## +CELL = CELLE +ERROR.TYPE = FEIL.TYPE +INFO = INFO +ISBLANK = ERTOM +ISERR = ERF +ISERROR = ERFEIL +ISEVEN = ERPARTALL +ISFORMULA = ERFORMEL +ISLOGICAL = ERLOGISK +ISNA = ERIT +ISNONTEXT = ERIKKETEKST +ISNUMBER = ERTALL +ISODD = ERODDE +ISREF = ERREF +ISTEXT = ERTEKST +N = N +NA = IT +SHEET = ARK +SHEETS = ANTALL.ARK +TYPE = VERDITYPE + +## +## Logiske funksjoner (Logical Functions) +## +AND = OG +FALSE = USANN +IF = HVIS +IFERROR = HVISFEIL +IFNA = HVIS.IT +IFS = HVIS.SETT +NOT = IKKE +OR = ELLER +SWITCH = BRYTER +TRUE = SANN +XOR = EKSKLUSIVELLER + +## +## Oppslag- og referansefunksjoner (Lookup & Reference Functions) +## +ADDRESS = ADRESSE +AREAS = OMRÅDER +CHOOSE = VELG +COLUMN = KOLONNE +COLUMNS = KOLONNER +FORMULATEXT = FORMELTEKST +GETPIVOTDATA = HENTPIVOTDATA +HLOOKUP = FINN.KOLONNE +HYPERLINK = HYPERKOBLING +INDEX = INDEKS +INDIRECT = INDIREKTE +LOOKUP = SLÅ.OPP +MATCH = SAMMENLIGNE +OFFSET = FORSKYVNING +ROW = RAD +ROWS = RADER +RTD = RTD +TRANSPOSE = TRANSPONER +VLOOKUP = FINN.RAD + +## +## Matematikk- og trigonometrifunksjoner (Math & Trig Functions) +## +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = MENGDE +ARABIC = ARABISK +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = GRUNNTALL +CEILING.MATH = AVRUND.GJELDENDE.MULTIPLUM.OPP.MATEMATISK +CEILING.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.PRESIS +COMBIN = KOMBINASJON +COMBINA = KOMBINASJONA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DESIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.AVRUND.GJELDENDE.MULTIPLUM +EVEN = AVRUND.TIL.PARTALL +EXP = EKSP +FACT = FAKULTET +FACTDOUBLE = DOBBELFAKT +FLOOR.MATH = AVRUND.GJELDENDE.MULTIPLUM.NED.MATEMATISK +FLOOR.PRECISE = AVRUND.GJELDENDE.MULTIPLUM.NED.PRESIS +GCD = SFF +INT = HELTALL +ISO.CEILING = ISO.AVRUND.GJELDENDE.MULTIPLUM +LCM = MFM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERS +MMULT = MMULT +MOD = REST +MROUND = MRUND +MULTINOMIAL = MULTINOMINELL +MUNIT = MENHET +ODD = AVRUND.TIL.ODDETALL +PI = PI +POWER = OPPHØYD.I +PRODUCT = PRODUKT +QUOTIENT = KVOTIENT +RADIANS = RADIANER +RAND = TILFELDIG +RANDBETWEEN = TILFELDIGMELLOM +ROMAN = ROMERTALL +ROUND = AVRUND +ROUNDBAHTDOWN = RUNDAVBAHTNEDOVER +ROUNDBAHTUP = RUNDAVBAHTOPPOVER +ROUNDDOWN = AVRUND.NED +ROUNDUP = AVRUND.OPP +SEC = SEC +SECH = SECH +SERIESSUM = SUMMER.REKKE +SIGN = FORTEGN +SIN = SIN +SINH = SINH +SQRT = ROT +SQRTPI = ROTPI +SUBTOTAL = DELSUM +SUM = SUMMER +SUMIF = SUMMERHVIS +SUMIFS = SUMMER.HVIS.SETT +SUMPRODUCT = SUMMERPRODUKT +SUMSQ = SUMMERKVADRAT +SUMX2MY2 = SUMMERX2MY2 +SUMX2PY2 = SUMMERX2PY2 +SUMXMY2 = SUMMERXMY2 +TAN = TAN +TANH = TANH +TRUNC = AVKORT + +## +## Statistiske funksjoner (Statistical Functions) +## +AVEDEV = GJENNOMSNITTSAVVIK +AVERAGE = GJENNOMSNITT +AVERAGEA = GJENNOMSNITTA +AVERAGEIF = GJENNOMSNITTHVIS +AVERAGEIFS = GJENNOMSNITT.HVIS.SETT +BETA.DIST = BETA.FORDELING.N +BETA.INV = BETA.INV +BINOM.DIST = BINOM.FORDELING.N +BINOM.DIST.RANGE = BINOM.FORDELING.OMRÅDE +BINOM.INV = BINOM.INV +CHISQ.DIST = KJIKVADRAT.FORDELING +CHISQ.DIST.RT = KJIKVADRAT.FORDELING.H +CHISQ.INV = KJIKVADRAT.INV +CHISQ.INV.RT = KJIKVADRAT.INV.H +CHISQ.TEST = KJIKVADRAT.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENS.T +CORREL = KORRELASJON +COUNT = ANTALL +COUNTA = ANTALLA +COUNTBLANK = TELLBLANKE +COUNTIF = ANTALL.HVIS +COUNTIFS = ANTALL.HVIS.SETT +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = AVVIK.KVADRERT +EXPON.DIST = EKSP.FORDELING.N +F.DIST = F.FORDELING +F.DIST.RT = F.FORDELING.H +F.INV = F.INV +F.INV.RT = F.INV.H +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOSE.ETS +FORECAST.ETS.CONFINT = PROGNOSE.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PROGNOSE.ETS.SESONGAVHENGIGHET +FORECAST.ETS.STAT = PROGNOSE.ETS.STAT +FORECAST.LINEAR = PROGNOSE.LINEÆR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FORDELING +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.PRESIS +GAUSS = GAUSS +GEOMEAN = GJENNOMSNITT.GEOMETRISK +GROWTH = VEKST +HARMEAN = GJENNOMSNITT.HARMONISK +HYPGEOM.DIST = HYPGEOM.FORDELING.N +INTERCEPT = SKJÆRINGSPUNKT +KURT = KURT +LARGE = N.STØRST +LINEST = RETTLINJE +LOGEST = KURVE +LOGNORM.DIST = LOGNORM.FORDELING +LOGNORM.INV = LOGNORM.INV +MAX = STØRST +MAXA = MAKSA +MAXIFS = MAKS.HVIS.SETT +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MIN.HVIS.SETT +MODE.MULT = MODUS.MULT +MODE.SNGL = MODUS.SNGL +NEGBINOM.DIST = NEGBINOM.FORDELING.N +NORM.DIST = NORM.FORDELING +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.FORDELING +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERSENTIL.EKS +PERCENTILE.INC = PERSENTIL.INK +PERCENTRANK.EXC = PROSENTDEL.EKS +PERCENTRANK.INC = PROSENTDEL.INK +PERMUT = PERMUTER +PERMUTATIONA = PERMUTASJONA +PHI = PHI +POISSON.DIST = POISSON.FORDELING +PROB = SANNSYNLIG +QUARTILE.EXC = KVARTIL.EKS +QUARTILE.INC = KVARTIL.INK +RANK.AVG = RANG.GJSN +RANK.EQ = RANG.EKV +RSQ = RKVADRAT +SKEW = SKJEVFORDELING +SKEW.P = SKJEVFORDELING.P +SLOPE = STIGNINGSTALL +SMALL = N.MINST +STANDARDIZE = NORMALISER +STDEV.P = STDAV.P +STDEV.S = STDAV.S +STDEVA = STDAVVIKA +STDEVPA = STDAVVIKPA +STEYX = STANDARDFEIL +T.DIST = T.FORDELING +T.DIST.2T = T.FORDELING.2T +T.DIST.RT = T.FORDELING.H +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = TRIMMET.GJENNOMSNITT +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARIANSA +VARPA = VARIANSPA +WEIBULL.DIST = WEIBULL.DIST.N +Z.TEST = Z.TEST + +## +## Tekstfunksjoner (Text Functions) +## +ASC = STIGENDE +BAHTTEXT = BAHTTEKST +CHAR = TEGNKODE +CLEAN = RENSK +CODE = KODE +CONCAT = KJED.SAMMEN +DOLLAR = VALUTA +EXACT = EKSAKT +FIND = FINN +FIXED = FASTSATT +ISTHAIDIGIT = ERTHAISIFFER +LEFT = VENSTRE +LEN = LENGDE +LOWER = SMÅ +MID = DELTEKST +NUMBERSTRING = TALLSTRENG +NUMBERVALUE = TALLVERDI +PHONETIC = FURIGANA +PROPER = STOR.FORBOKSTAV +REPLACE = ERSTATT +REPT = GJENTA +RIGHT = HØYRE +SEARCH = SØK +SUBSTITUTE = BYTT.UT +T = T +TEXT = TEKST +TEXTJOIN = TEKST.KOMBINER +THAIDIGIT = THAISIFFER +THAINUMSOUND = THAINUMLYD +THAINUMSTRING = THAINUMSTRENG +THAISTRINGLENGTH = THAISTRENGLENGDE +TRIM = TRIMME +UNICHAR = UNICODETEGN +UNICODE = UNICODE +UPPER = STORE +VALUE = VERDI + +## +## Nettfunksjoner (Web Functions) +## +ENCODEURL = URL.KODE +FILTERXML = FILTRERXML +WEBSERVICE = NETTJENESTE + +## +## Kompatibilitetsfunksjoner (Compatibility Functions) +## +BETADIST = BETA.FORDELING +BETAINV = INVERS.BETA.FORDELING +BINOMDIST = BINOM.FORDELING +CEILING = AVRUND.GJELDENDE.MULTIPLUM +CHIDIST = KJI.FORDELING +CHIINV = INVERS.KJI.FORDELING +CHITEST = KJI.TEST +CONCATENATE = KJEDE.SAMMEN +CONFIDENCE = KONFIDENS +COVAR = KOVARIANS +CRITBINOM = GRENSE.BINOM +EXPONDIST = EKSP.FORDELING +FDIST = FFORDELING +FINV = FFORDELING.INVERS +FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED +FORECAST = PROGNOSE +FTEST = FTEST +GAMMADIST = GAMMAFORDELING +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOM.FORDELING +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFORD +MODE = MODUS +NEGBINOMDIST = NEGBINOM.FORDELING +NORMDIST = NORMALFORDELING +NORMINV = NORMINV +NORMSDIST = NORMSFORDELING +NORMSINV = NORMSINV +PERCENTILE = PERSENTIL +PERCENTRANK = PROSENTDEL +POISSON = POISSON +QUARTILE = KVARTIL +RANK = RANG +STDEV = STDAV +STDEVP = STDAVP +TDIST = TFORDELING +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL.FORDELING +ZTEST = ZTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config index 8376022d..370567a7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Nederlands (Dutch) ## -## (For future use) -## -currencySymbol = € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #LEEG! -DIV0 = #DEEL/0! -VALUE = #WAARDE! -REF = #VERW! -NAME = #NAAM? -NUM = #GETAL! -NA = #N/B +NULL = #LEEG! +DIV0 = #DEEL/0! +VALUE = #WAARDE! +REF = #VERW! +NAME = #NAAM? +NUM = #GETAL! +NA = #N/B diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions index 2518f421..0e4f1597 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/nl/functions @@ -1,416 +1,536 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Nederlands (Dutch) ## +############################################################ ## -## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen +## Kubusfuncties (Cube Functions) ## -GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat - +CUBEKPIMEMBER = KUBUSKPILID +CUBEMEMBER = KUBUSLID +CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP +CUBERANKEDMEMBER = KUBUSGERANGSCHIKTLID +CUBESET = KUBUSSET +CUBESETCOUNT = KUBUSSETAANTAL +CUBEVALUE = KUBUSWAARDE ## -## Cube functions Kubusfuncties +## Databasefuncties (Database Functions) ## -CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken -CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is -CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid -CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten -CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel -CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set -CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus - +DAVERAGE = DBGEMIDDELDE +DCOUNT = DBAANTAL +DCOUNTA = DBAANTALC +DGET = DBLEZEN +DMAX = DBMAX +DMIN = DBMIN +DPRODUCT = DBPRODUCT +DSTDEV = DBSTDEV +DSTDEVP = DBSTDEVP +DSUM = DBSOM +DVAR = DBVAR +DVARP = DBVARP ## -## Database functions Databasefuncties +## Datum- en tijdfuncties (Date & Time Functions) ## -DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens -DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database -DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database -DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database -DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens -DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens -DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database -DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens -DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens -DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria -DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens -DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens - +DATE = DATUM +DATESTRING = DATUMNOTATIE +DATEVALUE = DATUMWAARDE +DAY = DAG +DAYS = DAGEN +DAYS360 = DAGEN360 +EDATE = ZELFDE.DAG +EOMONTH = LAATSTE.DAG +HOUR = UUR +ISOWEEKNUM = ISO.WEEKNUMMER +MINUTE = MINUUT +MONTH = MAAND +NETWORKDAYS = NETTO.WERKDAGEN +NETWORKDAYS.INTL = NETWERKDAGEN.INTL +NOW = NU +SECOND = SECONDE +THAIDAYOFWEEK = THAIS.WEEKDAG +THAIMONTHOFYEAR = THAIS.MAAND.VAN.JAAR +THAIYEAR = THAIS.JAAR +TIME = TIJD +TIMEVALUE = TIJDWAARDE +TODAY = VANDAAG +WEEKDAY = WEEKDAG +WEEKNUM = WEEKNUMMER +WORKDAY = WERKDAG +WORKDAY.INTL = WERKDAG.INTL +YEAR = JAAR +YEARFRAC = JAAR.DEEL ## -## Date and time functions Datum- en tijdfuncties +## Technische functies (Engineering Functions) ## -DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum -DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal -DAY = DAG ## Converteert een serieel getal naar een dag van de maand -DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen -EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt -EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden -HOUR = UUR ## Converteert een serieel getal naar uren -MINUTE = MINUUT ## Converteert een serieel naar getal minuten -MONTH = MAAND ## Converteert een serieel getal naar een maand -NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums -NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd -SECOND = SECONDE ## Converteert een serieel getal naar seconden -TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip -TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal -TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum -WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag -WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer -WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen -YEAR = JAAR ## Converteert een serieel getal naar een jaar -YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = BIN.N.DEC +BIN2HEX = BIN.N.HEX +BIN2OCT = BIN.N.OCT +BITAND = BIT.EN +BITLSHIFT = BIT.VERSCHUIF.LINKS +BITOR = BIT.OF +BITRSHIFT = BIT.VERSCHUIF.RECHTS +BITXOR = BIT.EX.OF +COMPLEX = COMPLEX +CONVERT = CONVERTEREN +DEC2BIN = DEC.N.BIN +DEC2HEX = DEC.N.HEX +DEC2OCT = DEC.N.OCT +DELTA = DELTA +ERF = FOUTFUNCTIE +ERF.PRECISE = FOUTFUNCTIE.NAUWKEURIG +ERFC = FOUT.COMPLEMENT +ERFC.PRECISE = FOUT.COMPLEMENT.NAUWKEURIG +GESTEP = GROTER.DAN +HEX2BIN = HEX.N.BIN +HEX2DEC = HEX.N.DEC +HEX2OCT = HEX.N.OCT +IMABS = C.ABS +IMAGINARY = C.IM.DEEL +IMARGUMENT = C.ARGUMENT +IMCONJUGATE = C.TOEGEVOEGD +IMCOS = C.COS +IMCOSH = C.COSH +IMCOT = C.COT +IMCSC = C.COSEC +IMCSCH = C.COSECH +IMDIV = C.QUOTIENT +IMEXP = C.EXP +IMLN = C.LN +IMLOG10 = C.LOG10 +IMLOG2 = C.LOG2 +IMPOWER = C.MACHT +IMPRODUCT = C.PRODUCT +IMREAL = C.REEEL.DEEL +IMSEC = C.SEC +IMSECH = C.SECH +IMSIN = C.SIN +IMSINH = C.SINH +IMSQRT = C.WORTEL +IMSUB = C.VERSCHIL +IMSUM = C.SOM +IMTAN = C.TAN +OCT2BIN = OCT.N.BIN +OCT2DEC = OCT.N.DEC +OCT2HEX = OCT.N.HEX ## -## Engineering functions Technische functies +## Financiële functies (Financial Functions) ## -BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x) -BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x) -BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x) -BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x) -BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal -BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal -BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal -COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal -CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid -DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal -DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal -DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal -DELTA = DELTA ## Test of twee waarden gelijk zijn -ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie -ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie -GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde -HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal -HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal -HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal -IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal -IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal -IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen -IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal -IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal -IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen -IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal -IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal -IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal -IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal -IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal -IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen -IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal -IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal -IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal -IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen -IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen -OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal -OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal -OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal - +ACCRINT = SAMENG.RENTE +ACCRINTM = SAMENG.RENTE.V +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = COUP.DAGEN.BB +COUPDAYS = COUP.DAGEN +COUPDAYSNC = COUP.DAGEN.VV +COUPNCD = COUP.DATUM.NB +COUPNUM = COUP.AANTAL +COUPPCD = COUP.DATUM.VB +CUMIPMT = CUM.RENTE +CUMPRINC = CUM.HOOFDSOM +DB = DB +DDB = DDB +DISC = DISCONTO +DOLLARDE = EURO.DE +DOLLARFR = EURO.BR +DURATION = DUUR +EFFECT = EFFECT.RENTE +FV = TW +FVSCHEDULE = TOEK.WAARDE2 +INTRATE = RENTEPERCENTAGE +IPMT = IBET +IRR = IR +ISPMT = ISBET +MDURATION = AANG.DUUR +MIRR = GIR +NOMINAL = NOMINALE.RENTE +NPER = NPER +NPV = NHW +ODDFPRICE = AFW.ET.PRIJS +ODDFYIELD = AFW.ET.REND +ODDLPRICE = AFW.LT.PRIJS +ODDLYIELD = AFW.LT.REND +PDURATION = PDUUR +PMT = BET +PPMT = PBET +PRICE = PRIJS.NOM +PRICEDISC = PRIJS.DISCONTO +PRICEMAT = PRIJS.VERVALDAG +PV = HW +RATE = RENTE +RECEIVED = OPBRENGST +RRI = RRI +SLN = LIN.AFSCHR +SYD = SYD +TBILLEQ = SCHATK.OBL +TBILLPRICE = SCHATK.PRIJS +TBILLYIELD = SCHATK.REND +VDB = VDB +XIRR = IR.SCHEMA +XNPV = NHW2 +YIELD = RENDEMENT +YIELDDISC = REND.DISCONTO +YIELDMAT = REND.VERVAL ## -## Financial functions Financiële functies +## Informatiefuncties (Information Functions) ## -ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd -AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen -AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode -COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum -COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt -COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum -COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum -COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum -COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum -CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd -CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald -DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode -DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft -DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier -DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal -DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk -DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen -EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage -FV = TW ## Geeft als resultaat de toekomstige waarde van een investering -FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages -INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier -IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn -IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows -ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering -MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt -MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten -NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage -NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering -NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage -ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn -ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn -ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn -ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn -PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit -PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn -PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier -PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum -PV = HW ## Geeft als resultaat de huidige waarde van een investering -RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit -RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier -SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn -SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode -TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties -TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier -TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier -VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode -XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows -XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows -YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd -YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier -YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum - +CELL = CEL +ERROR.TYPE = TYPE.FOUT +INFO = INFO +ISBLANK = ISLEEG +ISERR = ISFOUT2 +ISERROR = ISFOUT +ISEVEN = IS.EVEN +ISFORMULA = ISFORMULE +ISLOGICAL = ISLOGISCH +ISNA = ISNB +ISNONTEXT = ISGEENTEKST +ISNUMBER = ISGETAL +ISODD = IS.ONEVEN +ISREF = ISVERWIJZING +ISTEXT = ISTEKST +N = N +NA = NB +SHEET = BLAD +SHEETS = BLADEN +TYPE = TYPE ## -## Information functions Informatiefuncties +## Logische functies (Logical Functions) ## -CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel -ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel -INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving -ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is -ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B -ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is -ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is -ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is -ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is -ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is -ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is -ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is -ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is -ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is -N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal -NA = NB ## Geeft als resultaat de foutwaarde #N/B -TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft - +AND = EN +FALSE = ONWAAR +IF = ALS +IFERROR = ALS.FOUT +IFNA = ALS.NB +IFS = ALS.VOORWAARDEN +NOT = NIET +OR = OF +SWITCH = SCHAKELEN +TRUE = WAAR +XOR = EX.OF ## -## Logical functions Logische functies +## Zoek- en verwijzingsfuncties (Lookup & Reference Functions) ## -AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn -FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR -IF = ALS ## Geeft een logische test aan -IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd -NOT = NIET ## Keert de logische waarde van het argument om -OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is -TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR - +ADDRESS = ADRES +AREAS = BEREIKEN +CHOOSE = KIEZEN +COLUMN = KOLOM +COLUMNS = KOLOMMEN +FORMULATEXT = FORMULETEKST +GETPIVOTDATA = DRAAITABEL.OPHALEN +HLOOKUP = HORIZ.ZOEKEN +HYPERLINK = HYPERLINK +INDEX = INDEX +INDIRECT = INDIRECT +LOOKUP = ZOEKEN +MATCH = VERGELIJKEN +OFFSET = VERSCHUIVING +ROW = RIJ +ROWS = RIJEN +RTD = RTG +TRANSPOSE = TRANSPONEREN +VLOOKUP = VERT.ZOEKEN ## -## Lookup and reference functions Zoek- en verwijzingsfuncties +## Wiskundige en trigonometrische functies (Math & Trig Functions) ## -ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad -AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing -CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden -COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing -COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing -HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel -HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet -INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix -INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde -LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix -MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix -OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing -ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing -ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing -RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt -TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix -VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel - +ABS = ABS +ACOS = BOOGCOS +ACOSH = BOOGCOSH +ACOT = BOOGCOT +ACOTH = BOOGCOTH +AGGREGATE = AGGREGAAT +ARABIC = ARABISCH +ASIN = BOOGSIN +ASINH = BOOGSINH +ATAN = BOOGTAN +ATAN2 = BOOGTAN2 +ATANH = BOOGTANH +BASE = BASIS +CEILING.MATH = AFRONDEN.BOVEN.WISK +CEILING.PRECISE = AFRONDEN.BOVEN.NAUWKEURIG +COMBIN = COMBINATIES +COMBINA = COMBIN.A +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = COSEC +CSCH = COSECH +DECIMAL = DECIMAAL +DEGREES = GRADEN +ECMA.CEILING = ECMA.AFRONDEN.BOVEN +EVEN = EVEN +EXP = EXP +FACT = FACULTEIT +FACTDOUBLE = DUBBELE.FACULTEIT +FLOOR.MATH = AFRONDEN.BENEDEN.WISK +FLOOR.PRECISE = AFRONDEN.BENEDEN.NAUWKEURIG +GCD = GGD +INT = INTEGER +ISO.CEILING = ISO.AFRONDEN.BOVEN +LCM = KGV +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMINANTMAT +MINVERSE = INVERSEMAT +MMULT = PRODUCTMAT +MOD = REST +MROUND = AFRONDEN.N.VEELVOUD +MULTINOMIAL = MULTINOMIAAL +MUNIT = EENHEIDMAT +ODD = ONEVEN +PI = PI +POWER = MACHT +PRODUCT = PRODUCT +QUOTIENT = QUOTIENT +RADIANS = RADIALEN +RAND = ASELECT +RANDBETWEEN = ASELECTTUSSEN +ROMAN = ROMEINS +ROUND = AFRONDEN +ROUNDBAHTDOWN = BAHT.AFR.NAAR.BENEDEN +ROUNDBAHTUP = BAHT.AFR.NAAR.BOVEN +ROUNDDOWN = AFRONDEN.NAAR.BENEDEN +ROUNDUP = AFRONDEN.NAAR.BOVEN +SEC = SEC +SECH = SECH +SERIESSUM = SOM.MACHTREEKS +SIGN = POS.NEG +SIN = SIN +SINH = SINH +SQRT = WORTEL +SQRTPI = WORTEL.PI +SUBTOTAL = SUBTOTAAL +SUM = SOM +SUMIF = SOM.ALS +SUMIFS = SOMMEN.ALS +SUMPRODUCT = SOMPRODUCT +SUMSQ = KWADRATENSOM +SUMX2MY2 = SOM.X2MINY2 +SUMX2PY2 = SOM.X2PLUSY2 +SUMXMY2 = SOM.XMINY.2 +TAN = TAN +TANH = TANH +TRUNC = GEHEEL ## -## Math and trigonometry functions Wiskundige en trigonometrische functies +## Statistische functies (Statistical Functions) ## -ABS = ABS ## Geeft als resultaat de absolute waarde van een getal -ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal -ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal -ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal -ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal -ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal -ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten -ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal -CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud -COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten -COS = COS ## Geeft als resultaat de cosinus van een getal -COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal -DEGREES = GRADEN ## Converteert radialen naar graden -EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal -EXP = EXP ## Verheft e tot de macht van een bepaald getal -FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal -FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal -FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af -GCD = GGD ## Geeft als resultaat de grootste gemene deler -INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal -LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud -LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal -LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal -LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal -MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix -MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix -MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices -MOD = REST ## Geeft als resultaat het restgetal van een deling -MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud -MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen -ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal -PI = PI ## Geeft als resultaat de waarde van pi -POWER = MACHT ## Verheft een getal tot een macht -PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar -QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal -RADIANS = RADIALEN ## Converteert graden naar radialen -RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1 -RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven -ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst -ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen -ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af -ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af -SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule -SIGN = POS.NEG ## Geeft als resultaat het teken van een getal -SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek -SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal -SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal -SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi) -SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik -SUM = SOM ## Telt de argumenten op -SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium -SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen -SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen -SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten -SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices -SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices -SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices -TAN = TAN ## Geeft als resultaat de tangens van een getal -TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal -TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal - +AVEDEV = GEM.DEVIATIE +AVERAGE = GEMIDDELDE +AVERAGEA = GEMIDDELDEA +AVERAGEIF = GEMIDDELDE.ALS +AVERAGEIFS = GEMIDDELDEN.ALS +BETA.DIST = BETA.VERD +BETA.INV = BETA.INV +BINOM.DIST = BINOM.VERD +BINOM.DIST.RANGE = BINOM.VERD.BEREIK +BINOM.INV = BINOMIALE.INV +CHISQ.DIST = CHIKW.VERD +CHISQ.DIST.RT = CHIKW.VERD.RECHTS +CHISQ.INV = CHIKW.INV +CHISQ.INV.RT = CHIKW.INV.RECHTS +CHISQ.TEST = CHIKW.TEST +CONFIDENCE.NORM = VERTROUWELIJKHEID.NORM +CONFIDENCE.T = VERTROUWELIJKHEID.T +CORREL = CORRELATIE +COUNT = AANTAL +COUNTA = AANTALARG +COUNTBLANK = AANTAL.LEGE.CELLEN +COUNTIF = AANTAL.ALS +COUNTIFS = AANTALLEN.ALS +COVARIANCE.P = COVARIANTIE.P +COVARIANCE.S = COVARIANTIE.S +DEVSQ = DEV.KWAD +EXPON.DIST = EXPON.VERD.N +F.DIST = F.VERD +F.DIST.RT = F.VERD.RECHTS +F.INV = F.INV +F.INV.RT = F.INV.RECHTS +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHER.INV +FORECAST.ETS = VOORSPELLEN.ETS +FORECAST.ETS.CONFINT = VOORSPELLEN.ETS.CONFINT +FORECAST.ETS.SEASONALITY = VOORSPELLEN.ETS.SEASONALITY +FORECAST.ETS.STAT = FORECAST.ETS.STAT +FORECAST.LINEAR = VOORSPELLEN.LINEAR +FREQUENCY = INTERVAL +GAMMA = GAMMA +GAMMA.DIST = GAMMA.VERD.N +GAMMA.INV = GAMMA.INV.N +GAMMALN = GAMMA.LN +GAMMALN.PRECISE = GAMMA.LN.NAUWKEURIG +GAUSS = GAUSS +GEOMEAN = MEETK.GEM +GROWTH = GROEI +HARMEAN = HARM.GEM +HYPGEOM.DIST = HYPGEOM.VERD +INTERCEPT = SNIJPUNT +KURT = KURTOSIS +LARGE = GROOTSTE +LINEST = LIJNSCH +LOGEST = LOGSCH +LOGNORM.DIST = LOGNORM.VERD +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAX.ALS.VOORWAARDEN +MEDIAN = MEDIAAN +MIN = MIN +MINA = MINA +MINIFS = MIN.ALS.VOORWAARDEN +MODE.MULT = MODUS.MEERV +MODE.SNGL = MODUS.ENKELV +NEGBINOM.DIST = NEGBINOM.VERD +NORM.DIST = NORM.VERD.N +NORM.INV = NORM.INV.N +NORM.S.DIST = NORM.S.VERD +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIEL.EXC +PERCENTILE.INC = PERCENTIEL.INC +PERCENTRANK.EXC = PROCENTRANG.EXC +PERCENTRANK.INC = PROCENTRANG.INC +PERMUT = PERMUTATIES +PERMUTATIONA = PERMUTATIE.A +PHI = PHI +POISSON.DIST = POISSON.VERD +PROB = KANS +QUARTILE.EXC = KWARTIEL.EXC +QUARTILE.INC = KWARTIEL.INC +RANK.AVG = RANG.GEMIDDELDE +RANK.EQ = RANG.GELIJK +RSQ = R.KWADRAAT +SKEW = SCHEEFHEID +SKEW.P = SCHEEFHEID.P +SLOPE = RICHTING +SMALL = KLEINSTE +STANDARDIZE = NORMALISEREN +STDEV.P = STDEV.P +STDEV.S = STDEV.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STAND.FOUT.YX +T.DIST = T.DIST +T.DIST.2T = T.VERD.2T +T.DIST.RT = T.VERD.RECHTS +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = GETRIMD.GEM +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.VERD +Z.TEST = Z.TEST ## -## Statistical functions Statistische functies +## Tekstfuncties (Text Functions) ## -AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde -AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten -AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden -AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria -AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen -BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie -BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling -BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling -CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling -CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling -CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets -CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie -CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen -COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst -COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst -COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik -COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium -COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria -COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties -CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium -DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat -EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling -FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling -FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling -FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie -FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie -FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend -FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix -FTEST = F.TOETS ## Geeft als resultaat een F-toets -GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling -GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling -GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x) -GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde -GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend -HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde -HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling -INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as -KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling -LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling -LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend -LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend -LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling -LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling -MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten -MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden -MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen -MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten -MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden -MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling -NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling -NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling -NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling -NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling -NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling -PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson -PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik -PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling -PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten -POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling -PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden -QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling -RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen -RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt -SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling -SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn -SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling -STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde -STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef -STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden -STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie -STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden -STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie -TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling -TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling -TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend -TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling -TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets -VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef -VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden -VARP = VARP ## Berekent de variantie op basis van de volledige populatie -VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden -WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling -ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets +BAHTTEXT = BAHT.TEKST +CHAR = TEKEN +CLEAN = WISSEN.CONTROL +CODE = CODE +CONCAT = TEKST.SAMENV +DOLLAR = EURO +EXACT = GELIJK +FIND = VIND.ALLES +FIXED = VAST +ISTHAIDIGIT = IS.THAIS.CIJFER +LEFT = LINKS +LEN = LENGTE +LOWER = KLEINE.LETTERS +MID = DEEL +NUMBERSTRING = GETALNOTATIE +NUMBERVALUE = NUMERIEKE.WAARDE +PHONETIC = FONETISCH +PROPER = BEGINLETTERS +REPLACE = VERVANGEN +REPT = HERHALING +RIGHT = RECHTS +SEARCH = VIND.SPEC +SUBSTITUTE = SUBSTITUEREN +T = T +TEXT = TEKST +TEXTJOIN = TEKST.COMBINEREN +THAIDIGIT = THAIS.CIJFER +THAINUMSOUND = THAIS.GETAL.GELUID +THAINUMSTRING = THAIS.GETAL.REEKS +THAISTRINGLENGTH = THAIS.REEKS.LENGTE +TRIM = SPATIES.WISSEN +UNICHAR = UNITEKEN +UNICODE = UNICODE +UPPER = HOOFDLETTERS +VALUE = WAARDE +## +## Webfuncties (Web Functions) +## +ENCODEURL = URL.CODEREN +FILTERXML = XML.FILTEREN +WEBSERVICE = WEBSERVICE ## -## Text functions Tekstfuncties +## Compatibiliteitsfuncties (Compatibility Functions) ## -ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens) -BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht) -CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code -CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst -CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks -CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment -DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro) -EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn -FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op -JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens) -LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks -LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks -LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks -LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks -LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters -MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft -MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft -PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op -PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter -REPLACE = VERVANG ## Vervangt tekens binnen een tekst -REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst -REPT = HERHALING ## Herhaalt een tekst een aantal malen -RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks -RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks -SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) -SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks -T = T ## Converteert de argumenten naar tekst -TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst -TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst -UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters -VALUE = WAARDE ## Converteert tekst naar een getal +BETADIST = BETAVERD +BETAINV = BETAINV +BINOMDIST = BINOMIALE.VERD +CEILING = AFRONDEN.BOVEN +CHIDIST = CHI.KWADRAAT +CHIINV = CHI.KWADRAAT.INV +CHITEST = CHI.TOETS +CONCATENATE = TEKST.SAMENVOEGEN +CONFIDENCE = BETROUWBAARHEID +COVAR = COVARIANTIE +CRITBINOM = CRIT.BINOM +EXPONDIST = EXPON.VERD +FDIST = F.VERDELING +FINV = F.INVERSE +FLOOR = AFRONDEN.BENEDEN +FORECAST = VOORSPELLEN +FTEST = F.TOETS +GAMMADIST = GAMMA.VERD +GAMMAINV = GAMMA.INV +HYPGEOMDIST = HYPERGEO.VERD +LOGINV = LOG.NORM.INV +LOGNORMDIST = LOG.NORM.VERD +MODE = MODUS +NEGBINOMDIST = NEG.BINOM.VERD +NORMDIST = NORM.VERD +NORMINV = NORM.INV +NORMSDIST = STAND.NORM.VERD +NORMSINV = STAND.NORM.INV +PERCENTILE = PERCENTIEL +PERCENTRANK = PERCENT.RANG +POISSON = POISSON +QUARTILE = KWARTIEL +RANK = RANG +STDEV = STDEV +STDEVP = STDEVP +TDIST = T.VERD +TINV = TINV +TTEST = T.TOETS +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = Z.TOETS diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config deleted file mode 100644 index c7f4152a..00000000 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/config +++ /dev/null @@ -1,24 +0,0 @@ -## -## PhpSpreadsheet -## - -ArgumentSeparator = ; - - -## -## (For future use) -## -currencySymbol = kr - - -## -## Excel Error Codes (For future use) - -## -NULL = #NULL! -DIV0 = #DIV/0! -VALUE = #VERDI! -REF = #REF! -NAME = #NAVN? -NUM = #NUM! -NA = #I/T diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions deleted file mode 100644 index ab2a3793..00000000 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/no/functions +++ /dev/null @@ -1,416 +0,0 @@ -## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ -## -## - - -## -## Add-in and Automation functions Funksjonene Tillegg og Automatisering -## -GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport - - -## -## Cube functions Kubefunksjoner -## -CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon. -CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben. -CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet. -CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene. -CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel. -CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett. -CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube. - - -## -## Database functions Databasefunksjoner -## -DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter -DCOUNT = DANTALL ## Teller celler som inneholder tall i en database -DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database -DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår -DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter -DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter -DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database -DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter -DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen -DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene -DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter -DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen - - -## -## Date and time functions Dato- og tidsfunksjoner -## -DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato -DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer -DAY = DAG ## Konverterer et serienummer til en dag i måneden -DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager -EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen -EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder -HOUR = TIME ## Konverterer et serienummer til en time -MINUTE = MINUTT ## Konverterer et serienummer til et minutt -MONTH = MÅNED ## Konverterer et serienummer til en måned -NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer -NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett -SECOND = SEKUND ## Konverterer et serienummer til et sekund -TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett -TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer -TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato -WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag -WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år -WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager -YEAR = ÅR ## Konverterer et serienummer til et år -YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato - - -## -## Engineering functions Tekniske funksjoner -## -BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x) -BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x) -BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x) -BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x) -BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall -BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall -BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall -COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall -CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet -DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall -DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall -DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall -DELTA = DELTA ## Undersøker om to verdier er like -ERF = FEILF ## Returnerer feilfunksjonen -ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen -GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi -HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall -HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet -HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall -IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall -IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall -IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer -IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall -IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall -IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall -IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall -IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall -IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall -IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall -IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens -IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall -IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall -IMSIN = IMSIN ## Returnerer sinus til et komplekst tall -IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall -IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall -IMSUM = IMSUMMER ## Returnerer summen av komplekse tall -OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall -OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall -OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall - - -## -## Financial functions Økonomiske funksjoner -## -ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente -ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall -AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient -AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode -COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen -COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen -COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato -COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen -COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen -COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen -CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder -CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder -DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning -DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir -DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir -DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall -DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk -DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk -EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen -FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering -FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser -INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir -IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode -IRR = IR ## Returnerer internrenten for en serie kontantstrømmer -ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode -MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00 -MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser -NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats -NPER = PERIODER ## Returnerer antall perioder for en investering -NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats -ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode -ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode -ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode -ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode -PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet -PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode -PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning -PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir -PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall -PV = NÅVERDI ## Returnerer nåverdien av en investering -RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet -RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir -SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode -SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode -TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon -TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon -TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon -VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning -XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske -XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske -YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente -YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel -YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato - - -## -## Information functions Informasjonsfunksjoner -## -CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle -ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype -INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø -ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom -ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T -ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi -ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall -ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi -ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T -ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst -ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall -ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall -ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse -ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst -N = N ## Returnerer en verdi som er konvertert til et tall -NA = IT ## Returnerer feilverdien #I/T -TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi - - -## -## Logical functions Logiske funksjoner -## -AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN -FALSE = USANN ## Returnerer den logiske verdien USANN -IF = HVIS ## Angir en logisk test som skal utføres -IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen. -NOT = IKKE ## Reverserer logikken til argumentet -OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN -TRUE = SANN ## Returnerer den logiske verdien SANN - - -## -## Lookup and reference functions Oppslag- og referansefunksjoner -## -ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark -AREAS = OMRÅDER ## Returnerer antall områder i en referanse -CHOOSE = VELG ## Velger en verdi fra en liste med verdier -COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse -COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse -HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen -HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett -INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise -INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi -LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise -MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise -OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse -ROW = RAD ## Returnerer radnummeret for en referanse -ROWS = RADER ## Returnerer antall rader i en referanse -RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).) -TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise -VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle - - -## -## Math and trigonometry functions Matematikk- og trigonometrifunksjoner -## -ABS = ABS ## Returnerer absoluttverdien til et tall -ACOS = ARCCOS ## Returnerer arcus cosinus til et tall -ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall -ASIN = ARCSIN ## Returnerer arcus sinus til et tall -ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall -ATAN = ARCTAN ## Returnerer arcus tangens til et tall -ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater -ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall -CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum -COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter -COS = COS ## Returnerer cosinus til et tall -COSH = COSH ## Returnerer den hyperbolske cosinus til et tall -DEGREES = GRADER ## Konverterer radianer til grader -EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall -EXP = EKSP ## Returnerer e opphøyd i en angitt potens -FACT = FAKULTET ## Returnerer fakultet til et tall -FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet -FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null -GCD = SFF ## Returnerer høyeste felles divisor -INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall -LCM = MFM ## Returnerer minste felles multiplum -LN = LN ## Returnerer den naturlige logaritmen til et tall -LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall -LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall -MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise -MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise -MMULT = MMULT ## Returnerer matriseproduktet av to matriser -MOD = REST ## Returnerer resten fra en divisjon -MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum -MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall -ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall -PI = PI ## Returnerer verdien av pi -POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens -PRODUCT = PRODUKT ## Multipliserer argumentene -QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon -RADIANS = RADIANER ## Konverterer grader til radianer -RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1 -RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område -ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst -ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre -ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null -ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null -SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen -SIGN = FORTEGN ## Returnerer fortegnet for et tall -SIN = SIN ## Returnerer sinus til en gitt vinkel -SINH = SINH ## Returnerer den hyperbolske sinus til et tall -SQRT = ROT ## Returnerer en positiv kvadratrot -SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi) -SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database -SUM = SUMMER ## Legger sammen argumentene -SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår -SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår -SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter -SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene -SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser -SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser -SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser -TAN = TAN ## Returnerer tangens for et tall -TANH = TANH ## Returnerer den hyperbolske tangens for et tall -TRUNC = AVKORT ## Korter av et tall til et heltall - - -## -## Statistical functions Statistiske funksjoner -## -AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien -AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene -AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier -AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår -AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår. -BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen -BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling -BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen -CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling -CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen -CHITEST = KJI.TEST ## Utfører testen for uavhengighet -CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon -CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett -COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten -COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten -COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område. -COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår -COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår -COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik -CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi -DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik -EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen -FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen -FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen -FISHER = FISHER ## Returnerer Fisher-transformasjonen -FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen -FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend -FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise -FTEST = FTEST ## Returnerer resultatet av en F-test -GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen -GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen -GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x) -GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien -GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend -HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien -HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen -INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen -KURT = KURT ## Returnerer kurtosen til et datasett -LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett -LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend -LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend -LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen -LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen -MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste -MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier -MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt -MIN = MIN ## Returnerer minimumsverdien i en argumentliste -MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier -MODE = MODUS ## Returnerer den vanligste verdien i et datasett -NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen -NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen -NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen -NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling -NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen -PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson -PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område -PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett -PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter -POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling -PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser -QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett -RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke -RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r) -SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling -SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen -SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett -STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi -STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg -STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier -STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen -STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier -STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen -TDIST = TFORDELING ## Returnerer en Student t-fordeling -TINV = TINV ## Returnerer den inverse Student t-fordelingen -TREND = TREND ## Returnerer verdier langs en lineær trend -TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett -TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test -VAR = VARIANS ## Estimerer varians basert på et utvalg -VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier -VARP = VARIANSP ## Beregner varians basert på hele populasjonen -VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier -WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen -ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test - - -## -## Text functions Tekstfunksjoner -## -ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn -BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht) -CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret -CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten -CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng -CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement -DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar) -EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like -FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) -FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) -FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler -JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn -LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi -LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi -LEN = LENGDE ## Returnerer antall tegn i en tekststreng -LENB = LENGDEB ## Returnerer antall tegn i en tekststreng -LOWER = SMÅ ## Konverterer tekst til små bokstaver -MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir -MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir -PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng -PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav -REPLACE = ERSTATT ## Erstatter tegn i en tekst -REPLACEB = ERSTATTB ## Erstatter tegn i en tekst -REPT = GJENTA ## Gjentar tekst et gitt antall ganger -RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi -RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi -SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) -SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) -SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng -T = T ## Konverterer argumentene til tekst -TEXT = TEKST ## Formaterer et tall og konverterer det til tekst -TRIM = TRIMME ## Fjerner mellomrom fra tekst -UPPER = STORE ## Konverterer tekst til store bokstaver -VALUE = VERDI ## Konverterer et tekstargument til et tall diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config index 00f8b9a3..1d8468ba 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Jezyk polski (Polish) ## -## (For future use) -## -currencySymbol = zł +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #ZERO! -DIV0 = #DZIEL/0! -VALUE = #ARG! -REF = #ADR! -NAME = #NAZWA? -NUM = #LICZBA! -NA = #N/D! +NULL = #ZERO! +DIV0 = #DZIEL/0! +VALUE = #ARG! +REF = #ADR! +NAME = #NAZWA? +NUM = #LICZBA! +NA = #N/D! diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions index 907a4ff0..d1b43b2e 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pl/functions @@ -1,416 +1,536 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Jezyk polski (Polish) ## +############################################################ ## -## Add-in and Automation functions Funkcje dodatków i automatyzacji +## Funkcje baz danych (Cube Functions) ## -GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej. - +CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU +CUBEMEMBER = ELEMENT.MODUŁU +CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU +CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU +CUBESET = ZESTAW.MODUŁÓW +CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU +CUBEVALUE = WARTOŚĆ.MODUŁU ## -## Cube functions Funkcje modułów +## Funkcje baz danych (Database Functions) ## -CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji. -CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module. -CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu. -CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów. -CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel. -CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu. -CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu. - +DAVERAGE = BD.ŚREDNIA +DCOUNT = BD.ILE.REKORDÓW +DCOUNTA = BD.ILE.REKORDÓW.A +DGET = BD.POLE +DMAX = BD.MAX +DMIN = BD.MIN +DPRODUCT = BD.ILOCZYN +DSTDEV = BD.ODCH.STANDARD +DSTDEVP = BD.ODCH.STANDARD.POPUL +DSUM = BD.SUMA +DVAR = BD.WARIANCJA +DVARP = BD.WARIANCJA.POPUL ## -## Database functions Funkcje baz danych +## Funkcje daty i godziny (Date & Time Functions) ## -DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych. -DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych. -DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych. -DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria. -DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych. -DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych. -DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych. -DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych. -DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych. -DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria. -DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych. -DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych. - +DATE = DATA +DATEDIF = DATA.RÓŻNICA +DATESTRING = DATA.CIĄG.ZNAK +DATEVALUE = DATA.WARTOŚĆ +DAY = DZIEŃ +DAYS = DNI +DAYS360 = DNI.360 +EDATE = NR.SER.DATY +EOMONTH = NR.SER.OST.DN.MIES +HOUR = GODZINA +ISOWEEKNUM = ISO.NUM.TYG +MINUTE = MINUTA +MONTH = MIESIĄC +NETWORKDAYS = DNI.ROBOCZE +NETWORKDAYS.INTL = DNI.ROBOCZE.NIESTAND +NOW = TERAZ +SECOND = SEKUNDA +THAIDAYOFWEEK = TAJ.DZIEŃ.TYGODNIA +THAIMONTHOFYEAR = TAJ.MIESIĄC.ROKU +THAIYEAR = TAJ.ROK +TIME = CZAS +TIMEVALUE = CZAS.WARTOŚĆ +TODAY = DZIŚ +WEEKDAY = DZIEŃ.TYG +WEEKNUM = NUM.TYG +WORKDAY = DZIEŃ.ROBOCZY +WORKDAY.INTL = DZIEŃ.ROBOCZY.NIESTAND +YEAR = ROK +YEARFRAC = CZĘŚĆ.ROKU ## -## Date and time functions Funkcje dat, godzin i czasu +## Funkcje inżynierskie (Engineering Functions) ## -DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty. -DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną. -DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca. -DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego. -EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej. -EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej. -HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę. -MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę. -MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc. -NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami. -NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny. -SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę. -TIME = CZAS ## Zwraca liczbę seryjną określonego czasu. -TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną. -TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej. -WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia. -WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku. -WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej. -YEAR = ROK ## Konwertuje liczbę seryjną na rok. -YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową. - +BESSELI = BESSEL.I +BESSELJ = BESSEL.J +BESSELK = BESSEL.K +BESSELY = BESSEL.Y +BIN2DEC = DWÓJK.NA.DZIES +BIN2HEX = DWÓJK.NA.SZESN +BIN2OCT = DWÓJK.NA.ÓSM +BITAND = BITAND +BITLSHIFT = BIT.PRZESUNIĘCIE.W.LEWO +BITOR = BITOR +BITRSHIFT = BIT.PRZESUNIĘCIE.W.PRAWO +BITXOR = BITXOR +COMPLEX = LICZBA.ZESP +CONVERT = KONWERTUJ +DEC2BIN = DZIES.NA.DWÓJK +DEC2HEX = DZIES.NA.SZESN +DEC2OCT = DZIES.NA.ÓSM +DELTA = CZY.RÓWNE +ERF = FUNKCJA.BŁ +ERF.PRECISE = FUNKCJA.BŁ.DOKŁ +ERFC = KOMP.FUNKCJA.BŁ +ERFC.PRECISE = KOMP.FUNKCJA.BŁ.DOKŁ +GESTEP = SPRAWDŹ.PRÓG +HEX2BIN = SZESN.NA.DWÓJK +HEX2DEC = SZESN.NA.DZIES +HEX2OCT = SZESN.NA.ÓSM +IMABS = MODUŁ.LICZBY.ZESP +IMAGINARY = CZ.UROJ.LICZBY.ZESP +IMARGUMENT = ARG.LICZBY.ZESP +IMCONJUGATE = SPRZĘŻ.LICZBY.ZESP +IMCOS = COS.LICZBY.ZESP +IMCOSH = COSH.LICZBY.ZESP +IMCOT = COT.LICZBY.ZESP +IMCSC = CSC.LICZBY.ZESP +IMCSCH = CSCH.LICZBY.ZESP +IMDIV = ILORAZ.LICZB.ZESP +IMEXP = EXP.LICZBY.ZESP +IMLN = LN.LICZBY.ZESP +IMLOG10 = LOG10.LICZBY.ZESP +IMLOG2 = LOG2.LICZBY.ZESP +IMPOWER = POTĘGA.LICZBY.ZESP +IMPRODUCT = ILOCZYN.LICZB.ZESP +IMREAL = CZ.RZECZ.LICZBY.ZESP +IMSEC = SEC.LICZBY.ZESP +IMSECH = SECH.LICZBY.ZESP +IMSIN = SIN.LICZBY.ZESP +IMSINH = SINH.LICZBY.ZESP +IMSQRT = PIERWIASTEK.LICZBY.ZESP +IMSUB = RÓŻN.LICZB.ZESP +IMSUM = SUMA.LICZB.ZESP +IMTAN = TAN.LICZBY.ZESP +OCT2BIN = ÓSM.NA.DWÓJK +OCT2DEC = ÓSM.NA.DZIES +OCT2HEX = ÓSM.NA.SZESN ## -## Engineering functions Funkcje inżynierskie +## Funkcje finansowe (Financial Functions) ## -BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x). -BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x). -BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x). -BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x). -BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej. -BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej. -BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej. -COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną. -CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny. -DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową. -DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej. -DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej. -DELTA = DELTA ## Sprawdza, czy dwie wartości są równe. -ERF = ERF ## Zwraca wartość funkcji błędu. -ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu. -GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa. -HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej. -HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej. -HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej. -IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej. -IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej. -IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach. -IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej. -IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej. -IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych. -IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej. -IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej. -IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej. -IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2. -IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej. -IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych. -IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej. -IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej. -IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej. -IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych. -IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych. -OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej. -OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej. -OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej. - +ACCRINT = NAL.ODS +ACCRINTM = NAL.ODS.WYKUP +AMORDEGRC = AMORT.NIELIN +AMORLINC = AMORT.LIN +COUPDAYBS = WYPŁ.DNI.OD.POCZ +COUPDAYS = WYPŁ.DNI +COUPDAYSNC = WYPŁ.DNI.NAST +COUPNCD = WYPŁ.DATA.NAST +COUPNUM = WYPŁ.LICZBA +COUPPCD = WYPŁ.DATA.POPRZ +CUMIPMT = SPŁAC.ODS +CUMPRINC = SPŁAC.KAPIT +DB = DB +DDB = DDB +DISC = STOPA.DYSK +DOLLARDE = CENA.DZIES +DOLLARFR = CENA.UŁAM +DURATION = ROCZ.PRZYCH +EFFECT = EFEKTYWNA +FV = FV +FVSCHEDULE = WART.PRZYSZŁ.KAP +INTRATE = STOPA.PROC +IPMT = IPMT +IRR = IRR +ISPMT = ISPMT +MDURATION = ROCZ.PRZYCH.M +MIRR = MIRR +NOMINAL = NOMINALNA +NPER = NPER +NPV = NPV +ODDFPRICE = CENA.PIERW.OKR +ODDFYIELD = RENT.PIERW.OKR +ODDLPRICE = CENA.OST.OKR +ODDLYIELD = RENT.OST.OKR +PDURATION = O.CZAS.TRWANIA +PMT = PMT +PPMT = PPMT +PRICE = CENA +PRICEDISC = CENA.DYSK +PRICEMAT = CENA.WYKUP +PV = PV +RATE = RATE +RECEIVED = KWOTA.WYKUP +RRI = RÓWNOW.STOPA.PROC +SLN = SLN +SYD = SYD +TBILLEQ = RENT.EKW.BS +TBILLPRICE = CENA.BS +TBILLYIELD = RENT.BS +VDB = VDB +XIRR = XIRR +XNPV = XNPV +YIELD = RENTOWNOŚĆ +YIELDDISC = RENT.DYSK +YIELDMAT = RENT.WYKUP ## -## Financial functions Funkcje finansowe +## Funkcje informacyjne (Information Functions) ## -ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym. -ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu. -AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji. -AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego. -COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego. -COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego. -COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy. -COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym. -COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu. -COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym. -CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami. -CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami. -DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej. -DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika. -DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego. -DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej. -DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej. -DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania. -EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej. -FV = FV ## Zwraca przyszłą wartość lokaty. -FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych. -INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego. -IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres. -IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych. -ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty. -MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł. -MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy. -NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej. -NPER = NPER ## Zwraca liczbę okresów dla lokaty. -NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej. -ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem. -ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem. -ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem. -ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem. -PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej. -PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu. -PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym. -PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego. -PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu. -PV = PV ## Zwraca wartość bieżącą lokaty. -RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej. -RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego. -SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową. -SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji. -TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego. -TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego. -TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego. -VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną. -XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. -XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. -YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym. -YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego. -YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie. - +CELL = KOMÓRKA +ERROR.TYPE = NR.BŁĘDU +INFO = INFO +ISBLANK = CZY.PUSTA +ISERR = CZY.BŁ +ISERROR = CZY.BŁĄD +ISEVEN = CZY.PARZYSTE +ISFORMULA = CZY.FORMUŁA +ISLOGICAL = CZY.LOGICZNA +ISNA = CZY.BRAK +ISNONTEXT = CZY.NIE.TEKST +ISNUMBER = CZY.LICZBA +ISODD = CZY.NIEPARZYSTE +ISREF = CZY.ADR +ISTEXT = CZY.TEKST +N = N +NA = BRAK +SHEET = ARKUSZ +SHEETS = ARKUSZE +TYPE = TYP ## -## Information functions Funkcje informacyjne +## Funkcje logiczne (Logical Functions) ## -CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki. -ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu. -INFO = INFO ## Zwraca informację o aktualnym środowisku pracy. -ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta. -ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!. -ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu. -ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta. -ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną. -ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!. -ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem. -ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą. -ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta. -ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem. -ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem. -N = L ## Zwraca wartość przekonwertowaną na postać liczbową. -NA = BRAK ## Zwraca wartość błędu #N/D!. -TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości. - +AND = ORAZ +FALSE = FAŁSZ +IF = JEŻELI +IFERROR = JEŻELI.BŁĄD +IFNA = JEŻELI.ND +IFS = WARUNKI +NOT = NIE +OR = LUB +SWITCH = PRZEŁĄCZ +TRUE = PRAWDA +XOR = XOR ## -## Logical functions Funkcje logiczne +## Funkcje wyszukiwania i odwołań (Lookup & Reference Functions) ## -AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA. -FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ. -IF = JEŻELI ## Określa warunek logiczny do sprawdzenia. -IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły. -NOT = NIE ## Odwraca wartość logiczną argumentu. -OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA. -TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA. - +ADDRESS = ADRES +AREAS = OBSZARY +CHOOSE = WYBIERZ +COLUMN = NR.KOLUMNY +COLUMNS = LICZBA.KOLUMN +FORMULATEXT = FORMUŁA.TEKST +GETPIVOTDATA = WEŹDANETABELI +HLOOKUP = WYSZUKAJ.POZIOMO +HYPERLINK = HIPERŁĄCZE +INDEX = INDEKS +INDIRECT = ADR.POŚR +LOOKUP = WYSZUKAJ +MATCH = PODAJ.POZYCJĘ +OFFSET = PRZESUNIĘCIE +ROW = WIERSZ +ROWS = ILE.WIERSZY +RTD = DANE.CZASU.RZECZ +TRANSPOSE = TRANSPONUJ +VLOOKUP = WYSZUKAJ.PIONOWO ## -## Lookup and reference functions Funkcje wyszukiwania i odwołań +## Funkcje matematyczne i trygonometryczne (Math & Trig Functions) ## -ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową. -AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu. -CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości. -COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania. -COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania. -HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki. -HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie. -INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy. -INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową. -LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy. -MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy. -OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania. -ROW = WIERSZ ## Zwraca numer wiersza odwołania. -ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania. -RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).). -TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę. -VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki. - +ABS = MODUŁ.LICZBY +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGUJ +ARABIC = ARABSKIE +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = PODSTAWA +CEILING.MATH = ZAOKR.W.GÓRĘ.MATEMATYCZNE +CEILING.PRECISE = ZAOKR.W.GÓRĘ.DOKŁ +COMBIN = KOMBINACJE +COMBINA = KOMBINACJE.A +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DZIESIĘTNA +DEGREES = STOPNIE +ECMA.CEILING = ECMA.ZAOKR.W.GÓRĘ +EVEN = ZAOKR.DO.PARZ +EXP = EXP +FACT = SILNIA +FACTDOUBLE = SILNIA.DWUKR +FLOOR.MATH = ZAOKR.W.DÓŁ.MATEMATYCZNE +FLOOR.PRECISE = ZAOKR.W.DÓŁ.DOKŁ +GCD = NAJW.WSP.DZIEL +INT = ZAOKR.DO.CAŁK +ISO.CEILING = ISO.ZAOKR.W.GÓRĘ +LCM = NAJMN.WSP.WIEL +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = WYZNACZNIK.MACIERZY +MINVERSE = MACIERZ.ODW +MMULT = MACIERZ.ILOCZYN +MOD = MOD +MROUND = ZAOKR.DO.WIELOKR +MULTINOMIAL = WIELOMIAN +MUNIT = MACIERZ.JEDNOSTKOWA +ODD = ZAOKR.DO.NPARZ +PI = PI +POWER = POTĘGA +PRODUCT = ILOCZYN +QUOTIENT = CZ.CAŁK.DZIELENIA +RADIANS = RADIANY +RAND = LOS +RANDBETWEEN = LOS.ZAKR +ROMAN = RZYMSKIE +ROUND = ZAOKR +ROUNDBAHTDOWN = ZAOKR.DÓŁ.BAT +ROUNDBAHTUP = ZAOKR.GÓRA.BAT +ROUNDDOWN = ZAOKR.DÓŁ +ROUNDUP = ZAOKR.GÓRA +SEC = SEC +SECH = SECH +SERIESSUM = SUMA.SZER.POT +SIGN = ZNAK.LICZBY +SIN = SIN +SINH = SINH +SQRT = PIERWIASTEK +SQRTPI = PIERW.PI +SUBTOTAL = SUMY.CZĘŚCIOWE +SUM = SUMA +SUMIF = SUMA.JEŻELI +SUMIFS = SUMA.WARUNKÓW +SUMPRODUCT = SUMA.ILOCZYNÓW +SUMSQ = SUMA.KWADRATÓW +SUMX2MY2 = SUMA.X2.M.Y2 +SUMX2PY2 = SUMA.X2.P.Y2 +SUMXMY2 = SUMA.XMY.2 +TAN = TAN +TANH = TANH +TRUNC = LICZBA.CAŁK ## -## Math and trigonometry functions Funkcje matematyczne i trygonometryczne +## Funkcje statystyczne (Statistical Functions) ## -ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby. -ACOS = ACOS ## Zwraca arcus cosinus liczby. -ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby. -ASIN = ASIN ## Zwraca arcus sinus liczby. -ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby. -ATAN = ATAN ## Zwraca arcus tangens liczby. -ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y. -ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby. -CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności. -COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów. -COS = COS ## Zwraca cosinus liczby. -COSH = COSH ## Zwraca cosinus hiperboliczny liczby. -DEGREES = STOPNIE ## Konwertuje radiany na stopnie. -EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej. -EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę. -FACT = SILNIA ## Zwraca silnię liczby. -FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby. -FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. -GCD = GCD ## Zwraca największy wspólny dzielnik. -INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej. -LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność. -LN = LN ## Zwraca logarytm naturalny podanej liczby. -LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie. -LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby. -MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy. -MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy. -MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic. -MOD = MOD ## Zwraca resztę z dzielenia. -MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności. -MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb. -ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej. -PI = PI ## Zwraca wartość liczby Pi. -POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi. -PRODUCT = ILOCZYN ## Mnoży argumenty. -QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity). -RADIANS = RADIANY ## Konwertuje stopnie na radiany. -RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1. -RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty. -ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst. -ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr. -ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. -ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera. -SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru. -SIGN = ZNAK.LICZBY ## Zwraca znak liczby. -SIN = SIN ## Zwraca sinus danego kąta. -SINH = SINH ## Zwraca sinus hiperboliczny liczby. -SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy. -SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi). -SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych. -SUM = SUMA ## Dodaje argumenty. -SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium. -SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów. -SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy. -SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów. -SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach. -SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach. -SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach. -TAN = TAN ## Zwraca tangens liczby. -TANH = TANH ## Zwraca tangens hiperboliczny liczby. -TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej. - +AVEDEV = ODCH.ŚREDNIE +AVERAGE = ŚREDNIA +AVERAGEA = ŚREDNIA.A +AVERAGEIF = ŚREDNIA.JEŻELI +AVERAGEIFS = ŚREDNIA.WARUNKÓW +BETA.DIST = ROZKŁ.BETA +BETA.INV = ROZKŁ.BETA.ODWR +BINOM.DIST = ROZKŁ.DWUM +BINOM.DIST.RANGE = ROZKŁ.DWUM.ZAKRES +BINOM.INV = ROZKŁ.DWUM.ODWR +CHISQ.DIST = ROZKŁ.CHI +CHISQ.DIST.RT = ROZKŁ.CHI.PS +CHISQ.INV = ROZKŁ.CHI.ODWR +CHISQ.INV.RT = ROZKŁ.CHI.ODWR.PS +CHISQ.TEST = CHI.TEST +CONFIDENCE.NORM = UFNOŚĆ.NORM +CONFIDENCE.T = UFNOŚĆ.T +CORREL = WSP.KORELACJI +COUNT = ILE.LICZB +COUNTA = ILE.NIEPUSTYCH +COUNTBLANK = LICZ.PUSTE +COUNTIF = LICZ.JEŻELI +COUNTIFS = LICZ.WARUNKI +COVARIANCE.P = KOWARIANCJA.POPUL +COVARIANCE.S = KOWARIANCJA.PRÓBKI +DEVSQ = ODCH.KWADRATOWE +EXPON.DIST = ROZKŁ.EXP +F.DIST = ROZKŁ.F +F.DIST.RT = ROZKŁ.F.PS +F.INV = ROZKŁ.F.ODWR +F.INV.RT = ROZKŁ.F.ODWR.PS +F.TEST = F.TEST +FISHER = ROZKŁAD.FISHER +FISHERINV = ROZKŁAD.FISHER.ODW +FORECAST.ETS = REGLINX.ETS +FORECAST.ETS.CONFINT = REGLINX.ETS.CONFINT +FORECAST.ETS.SEASONALITY = REGLINX.ETS.SEZONOWOŚĆ +FORECAST.ETS.STAT = REGLINX.ETS.STATYSTYKA +FORECAST.LINEAR = REGLINX.LINIOWA +FREQUENCY = CZĘSTOŚĆ +GAMMA = GAMMA +GAMMA.DIST = ROZKŁ.GAMMA +GAMMA.INV = ROZKŁ.GAMMA.ODWR +GAMMALN = ROZKŁAD.LIN.GAMMA +GAMMALN.PRECISE = ROZKŁAD.LIN.GAMMA.DOKŁ +GAUSS = GAUSS +GEOMEAN = ŚREDNIA.GEOMETRYCZNA +GROWTH = REGEXPW +HARMEAN = ŚREDNIA.HARMONICZNA +HYPGEOM.DIST = ROZKŁ.HIPERGEOM +INTERCEPT = ODCIĘTA +KURT = KURTOZA +LARGE = MAX.K +LINEST = REGLINP +LOGEST = REGEXPP +LOGNORM.DIST = ROZKŁ.LOG +LOGNORM.INV = ROZKŁ.LOG.ODWR +MAX = MAX +MAXA = MAX.A +MAXIFS = MAKS.WARUNKÓW +MEDIAN = MEDIANA +MIN = MIN +MINA = MIN.A +MINIFS = MIN.WARUNKÓW +MODE.MULT = WYST.NAJCZĘŚCIEJ.TABL +MODE.SNGL = WYST.NAJCZĘŚCIEJ.WART +NEGBINOM.DIST = ROZKŁ.DWUM.PRZEC +NORM.DIST = ROZKŁ.NORMALNY +NORM.INV = ROZKŁ.NORMALNY.ODWR +NORM.S.DIST = ROZKŁ.NORMALNY.S +NORM.S.INV = ROZKŁ.NORMALNY.S.ODWR +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTYL.PRZEDZ.OTW +PERCENTILE.INC = PERCENTYL.PRZEDZ.ZAMK +PERCENTRANK.EXC = PROC.POZ.PRZEDZ.OTW +PERCENTRANK.INC = PROC.POZ.PRZEDZ.ZAMK +PERMUT = PERMUTACJE +PERMUTATIONA = PERMUTACJE.A +PHI = PHI +POISSON.DIST = ROZKŁ.POISSON +PROB = PRAWDPD +QUARTILE.EXC = KWARTYL.PRZEDZ.OTW +QUARTILE.INC = KWARTYL.PRZEDZ.ZAMK +RANK.AVG = POZYCJA.ŚR +RANK.EQ = POZYCJA.NAJW +RSQ = R.KWADRAT +SKEW = SKOŚNOŚĆ +SKEW.P = SKOŚNOŚĆ.P +SLOPE = NACHYLENIE +SMALL = MIN.K +STANDARDIZE = NORMALIZUJ +STDEV.P = ODCH.STAND.POPUL +STDEV.S = ODCH.STANDARD.PRÓBKI +STDEVA = ODCH.STANDARDOWE.A +STDEVPA = ODCH.STANDARD.POPUL.A +STEYX = REGBŁSTD +T.DIST = ROZKŁ.T +T.DIST.2T = ROZKŁ.T.DS +T.DIST.RT = ROZKŁ.T.PS +T.INV = ROZKŁ.T.ODWR +T.INV.2T = ROZKŁ.T.ODWR.DS +T.TEST = T.TEST +TREND = REGLINW +TRIMMEAN = ŚREDNIA.WEWN +VAR.P = WARIANCJA.POP +VAR.S = WARIANCJA.PRÓBKI +VARA = WARIANCJA.A +VARPA = WARIANCJA.POPUL.A +WEIBULL.DIST = ROZKŁ.WEIBULL +Z.TEST = Z.TEST ## -## Statistical functions Funkcje statystyczne +## Funkcje tekstowe (Text Functions) ## -AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej. -AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów. -AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria. -AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów. -BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta. -BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta. -BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa. -CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. -CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. -CHITEST = TEST.CHI ## Zwraca test niezależności. -CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji. -CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych. -COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów. -COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów. -COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie. -COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria. -COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów. -COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń. -CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej. -DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń. -EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy. -FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F. -FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F. -FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera. -FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera. -FORECAST = REGLINX ## Zwraca wartość trendu liniowego. -FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową. -FTEST = TEST.F ## Zwraca wynik testu F. -GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma. -GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma. -GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x). -GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną. -GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego. -HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną. -HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny. -INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej. -KURT = KURTOZA ## Zwraca kurtozę zbioru danych. -LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych. -LINEST = REGLINP ## Zwraca parametry trendu liniowego. -LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego. -LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego. -LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego. -MAX = MAX ## Zwraca maksymalną wartość listy argumentów. -MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -MEDIAN = MEDIANA ## Zwraca medianę podanych liczb. -MIN = MIN ## Zwraca minimalną wartość listy argumentów. -MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. -MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych. -NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy. -NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany. -NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego. -NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany. -NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego. -PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona. -PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie. -PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych. -PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów. -POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona. -PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami. -QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych. -RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb. -RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona. -SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu. -SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej. -SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych. -STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną. -STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki. -STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. -STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji. -STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych. -STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji. -TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta. -TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta. -TREND = REGLINW ## Zwraca wartości trendu liniowego. -TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych. -TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta. -VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki. -VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. -VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji. -VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych. -WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla. -ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z. +BAHTTEXT = BAT.TEKST +CHAR = ZNAK +CLEAN = OCZYŚĆ +CODE = KOD +CONCAT = ZŁĄCZ.TEKST +DOLLAR = KWOTA +EXACT = PORÓWNAJ +FIND = ZNAJDŹ +FIXED = ZAOKR.DO.TEKST +ISTHAIDIGIT = CZY.CYFRA.TAJ +LEFT = LEWY +LEN = DŁ +LOWER = LITERY.MAŁE +MID = FRAGMENT.TEKSTU +NUMBERSTRING = LICZBA.CIĄG.ZNAK +NUMBERVALUE = WARTOŚĆ.LICZBOWA +PROPER = Z.WIELKIEJ.LITERY +REPLACE = ZASTĄP +REPT = POWT +RIGHT = PRAWY +SEARCH = SZUKAJ.TEKST +SUBSTITUTE = PODSTAW +T = T +TEXT = TEKST +TEXTJOIN = POŁĄCZ.TEKSTY +THAIDIGIT = TAJ.CYFRA +THAINUMSOUND = TAJ.DŹWIĘK.NUM +THAINUMSTRING = TAJ.CIĄG.NUM +THAISTRINGLENGTH = TAJ.DŁUGOŚĆ.CIĄGU +TRIM = USUŃ.ZBĘDNE.ODSTĘPY +UNICHAR = ZNAK.UNICODE +UNICODE = UNICODE +UPPER = LITERY.WIELKIE +VALUE = WARTOŚĆ +## +## Funkcje sieci Web (Web Functions) +## +ENCODEURL = ENCODEURL +FILTERXML = FILTERXML +WEBSERVICE = WEBSERVICE ## -## Text functions Funkcje tekstowe +## Funkcje zgodności (Compatibility Functions) ## -ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe). -BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht). -CHAR = ZNAK ## Zwraca znak o podanym numerze kodu. -CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane. -CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym. -CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst. -DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar). -EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych. -FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). -FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). -FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych. -JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe). -LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej. -LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej. -LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego. -LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego. -LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery. -MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. -MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. -PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego. -PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą. -REPLACE = ZASTĄP ## Zastępuje znaki w tekście. -REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście. -REPT = POWT ## Powiela tekst daną liczbę razy. -RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej. -RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej. -SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). -SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). -SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym. -T = T ## Konwertuje argumenty na tekst. -TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst. -TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu. -UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery. -VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę. +BETADIST = ROZKŁAD.BETA +BETAINV = ROZKŁAD.BETA.ODW +BINOMDIST = ROZKŁAD.DWUM +CEILING = ZAOKR.W.GÓRĘ +CHIDIST = ROZKŁAD.CHI +CHIINV = ROZKŁAD.CHI.ODW +CHITEST = TEST.CHI +CONCATENATE = ZŁĄCZ.TEKSTY +CONFIDENCE = UFNOŚĆ +COVAR = KOWARIANCJA +CRITBINOM = PRÓG.ROZKŁAD.DWUM +EXPONDIST = ROZKŁAD.EXP +FDIST = ROZKŁAD.F +FINV = ROZKŁAD.F.ODW +FLOOR = ZAOKR.W.DÓŁ +FORECAST = REGLINX +FTEST = TEST.F +GAMMADIST = ROZKŁAD.GAMMA +GAMMAINV = ROZKŁAD.GAMMA.ODW +HYPGEOMDIST = ROZKŁAD.HIPERGEOM +LOGINV = ROZKŁAD.LOG.ODW +LOGNORMDIST = ROZKŁAD.LOG +MODE = WYST.NAJCZĘŚCIEJ +NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC +NORMDIST = ROZKŁAD.NORMALNY +NORMINV = ROZKŁAD.NORMALNY.ODW +NORMSDIST = ROZKŁAD.NORMALNY.S +NORMSINV = ROZKŁAD.NORMALNY.S.ODW +PERCENTILE = PERCENTYL +PERCENTRANK = PROCENT.POZYCJA +POISSON = ROZKŁAD.POISSON +QUARTILE = KWARTYL +RANK = POZYCJA +STDEV = ODCH.STANDARDOWE +STDEVP = ODCH.STANDARD.POPUL +TDIST = ROZKŁAD.T +TINV = ROZKŁAD.T.ODW +TTEST = TEST.T +VAR = WARIANCJA +VARP = WARIANCJA.POPUL +WEIBULL = ROZKŁAD.WEIBULL +ZTEST = TEST.Z diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config index 904f99f1..c39057c7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Português Brasileiro (Brazilian Portuguese) ## -## (For future use) -## -currencySymbol = R$ +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NULO! -DIV0 = #DIV/0! -VALUE = #VALOR! -REF = #REF! -NAME = #NOME? -NUM = #NÚM! -NA = #N/D +NULL = #NULO! +DIV0 +VALUE = #VALOR! +REF +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions index a062a7fa..feba30d9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/br/functions @@ -1,408 +1,527 @@ +############################################################ ## -## Add-in and Automation functions Funções Suplemento e Automação +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica +## Português Brasileiro (Brazilian Portuguese) +## +############################################################ ## -## Cube functions Funções de Cubo +## Funções de cubo (Cube Functions) ## -CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização. -CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo. -CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro. -CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos. -CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel. -CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto. -CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo. - +CUBEKPIMEMBER = MEMBROKPICUBO +CUBEMEMBER = MEMBROCUBO +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = CONTAGEMCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Database functions Funções de banco de dados +## Funções de banco de dados (Database Functions) ## -DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados -DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados -DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados -DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico -DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados -DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados -DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados -DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados -DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados -DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério -DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados -DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados - +DAVERAGE = BDMÉDIA +DCOUNT = BDCONTAR +DCOUNTA = BDCONTARA +DGET = BDEXTRAIR +DMAX = BDMÁX +DMIN = BDMÍN +DPRODUCT = BDMULTIPL +DSTDEV = BDEST +DSTDEVP = BDDESVPA +DSUM = BDSOMA +DVAR = BDVAREST +DVARP = BDVARP ## -## Date and time functions Funções de data e hora +## Funções de data e hora (Date & Time Functions) ## -DATE = DATA ## Retorna o número de série de uma data específica -DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série -DAY = DIA ## Converte um número de série em um dia do mês -DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias -EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial -EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses -HOUR = HORA ## Converte um número de série em uma hora -MINUTE = MINUTO ## Converte um número de série em um minuto -MONTH = MÊS ## Converte um número de série em um mês -NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas -NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais -SECOND = SEGUNDO ## Converte um número de série em um segundo -TIME = HORA ## Retorna o número de série de uma hora específica -TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série -TODAY = HOJE ## Retorna o número de série da data de hoje -WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana -WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano -WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis -YEAR = ANO ## Converte um número de série em um ano -YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final - +DATE = DATA +DATEDIF = DATADIF +DATESTRING = DATA.SÉRIE +DATEVALUE = DATA.VALOR +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = DATAM +EOMONTH = FIMMÊS +HOUR = HORA +ISOWEEKNUM = NÚMSEMANAISO +MINUTE = MINUTO +MONTH = MÊS +NETWORKDAYS = DIATRABALHOTOTAL +NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL +NOW = AGORA +SECOND = SEGUNDO +TIME = TEMPO +TIMEVALUE = VALOR.TEMPO +TODAY = HOJE +WEEKDAY = DIA.DA.SEMANA +WEEKNUM = NÚMSEMANA +WORKDAY = DIATRABALHO +WORKDAY.INTL = DIATRABALHO.INTL +YEAR = ANO +YEARFRAC = FRAÇÃOANO ## -## Engineering functions Funções de engenharia +## Funções de engenharia (Engineering Functions) ## -BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada -BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x) -BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada -BESSELY = BESSELY ## Retorna a função de Bessel Yn(x) -BIN2DEC = BIN2DEC ## Converte um número binário em decimal -BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal -BIN2OCT = BIN2OCT ## Converte um número binário em octal -COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo -CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro -DEC2BIN = DECABIN ## Converte um número decimal em binário -DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal -DEC2OCT = DECAOCT ## Converte um número decimal em octal -DELTA = DELTA ## Testa se dois valores são iguais -ERF = FUNERRO ## Retorna a função de erro -ERFC = FUNERROCOMPL ## Retorna a função de erro complementar -GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite -HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário -HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal -HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal -IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo -IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo -IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos -IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo -IMCOS = IMCOS ## Retorna o cosseno de um número complexo -IMDIV = IMDIV ## Retorna o quociente de dois números complexos -IMEXP = IMEXP ## Retorna o exponencial de um número complexo -IMLN = IMLN ## Retorna o logaritmo natural de um número complexo -IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo -IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo -IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira -IMPRODUCT = IMPROD ## Retorna o produto de números complexos -IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo -IMSIN = IMSENO ## Retorna o seno de um número complexo -IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo -IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos -IMSUM = IMSOMA ## Retorna a soma de números complexos -OCT2BIN = OCTABIN ## Converte um número octal em binário -OCT2DEC = OCTADEC ## Converte um número octal em decimal -OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINADEC +BIN2HEX = BINAHEX +BIN2OCT = BINAOCT +BITAND = BITAND +BITLSHIFT = DESLOCESQBIT +BITOR = BITOR +BITRSHIFT = DESLOCDIRBIT +BITXOR = BITXOR +COMPLEX = COMPLEXO +CONVERT = CONVERTER +DEC2BIN = DECABIN +DEC2HEX = DECAHEX +DEC2OCT = DECAOCT +DELTA = DELTA +ERF = FUNERRO +ERF.PRECISE = FUNERRO.PRECISO +ERFC = FUNERROCOMPL +ERFC.PRECISE = FUNERROCOMPL.PRECISO +GESTEP = DEGRAU +HEX2BIN = HEXABIN +HEX2DEC = HEXADEC +HEX2OCT = HEXAOCT +IMABS = IMABS +IMAGINARY = IMAGINÁRIO +IMARGUMENT = IMARG +IMCONJUGATE = IMCONJ +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCOSEC +IMCSCH = IMCOSECH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOT +IMPRODUCT = IMPROD +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSENO +IMSINH = IMSENH +IMSQRT = IMRAIZ +IMSUB = IMSUBTR +IMSUM = IMSOMA +IMTAN = IMTAN +OCT2BIN = OCTABIN +OCT2DEC = OCTADEC +OCT2HEX = OCTAHEX ## -## Financial functions Funções financeiras +## Funções financeiras (Financial Functions) ## -ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros -ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento -AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação -AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil -COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação -COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação -COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom -COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação -COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento -COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação -CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos -CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos -DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo -DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você -DISC = DESC ## Retorna a taxa de desconto de um título -DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal -DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária -DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos -EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva -FV = VF ## Retorna o valor futuro de um investimento -FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas -INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido -IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período -IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa -ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento -MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100 -MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas -NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual -NPER = NPER ## Retorna o número de períodos de um investimento -NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto -ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido -ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido -ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido -ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido -PMT = PGTO ## Retorna o pagamento periódico de uma anuidade -PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento -PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos -PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado -PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento -PV = VP ## Retorna o valor presente de um investimento -RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade -RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido -SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período -SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado -TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro -TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro -TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro -VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante -XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico -XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico -YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos -YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro -YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento - +ACCRINT = JUROSACUM +ACCRINTM = JUROSACUMV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = CUPDIASINLIQ +COUPDAYS = CUPDIAS +COUPDAYSNC = CUPDIASPRÓX +COUPNCD = CUPDATAPRÓX +COUPNUM = CUPNÚM +COUPPCD = CUPDATAANT +CUMIPMT = PGTOJURACUM +CUMPRINC = PGTOCAPACUM +DB = BD +DDB = BDD +DISC = DESC +DOLLARDE = MOEDADEC +DOLLARFR = MOEDAFRA +DURATION = DURAÇÃO +EFFECT = EFETIVA +FV = VF +FVSCHEDULE = VFPLANO +INTRATE = TAXAJUROS +IPMT = IPGTO +IRR = TIR +ISPMT = ÉPGTO +MDURATION = MDURAÇÃO +MIRR = MTIR +NOMINAL = NOMINAL +NPER = NPER +NPV = VPL +ODDFPRICE = PREÇOPRIMINC +ODDFYIELD = LUCROPRIMINC +ODDLPRICE = PREÇOÚLTINC +ODDLYIELD = LUCROÚLTINC +PDURATION = DURAÇÃOP +PMT = PGTO +PPMT = PPGTO +PRICE = PREÇO +PRICEDISC = PREÇODESC +PRICEMAT = PREÇOVENC +PV = VP +RATE = TAXA +RECEIVED = RECEBER +RRI = TAXAJURO +SLN = DPD +SYD = SDA +TBILLEQ = OTN +TBILLPRICE = OTNVALOR +TBILLYIELD = OTNLUCRO +VDB = BDV +XIRR = XTIR +XNPV = XVPL +YIELD = LUCRO +YIELDDISC = LUCRODESC +YIELDMAT = LUCROVENC ## -## Information functions Funções de informação +## Funções de informação (Information Functions) ## -CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula -ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro -INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual -ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio -ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D -ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro -ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par -ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico -ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D -ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto -ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número -ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar -ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência -ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto -N = N ## Retorna um valor convertido em um número -NA = NÃO.DISP ## Retorna o valor de erro #N/D -TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor - +CELL = CÉL +ERROR.TYPE = TIPO.ERRO +INFO = INFORMAÇÃO +ISBLANK = ÉCÉL.VAZIA +ISERR = ÉERRO +ISERROR = ÉERROS +ISEVEN = ÉPAR +ISFORMULA = ÉFÓRMULA +ISLOGICAL = ÉLÓGICO +ISNA = É.NÃO.DISP +ISNONTEXT = É.NÃO.TEXTO +ISNUMBER = ÉNÚM +ISODD = ÉIMPAR +ISREF = ÉREF +ISTEXT = ÉTEXTO +N = N +NA = NÃO.DISP +SHEET = PLAN +SHEETS = PLANS +TYPE = TIPO ## -## Logical functions Funções lógicas +## Funções lógicas (Logical Functions) ## -AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS -FALSE = FALSO ## Retorna o valor lógico FALSO -IF = SE ## Especifica um teste lógico a ser executado -IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula -NOT = NÃO ## Inverte o valor lógico do argumento -OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO -TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SEERRO +IFNA = SENÃODISP +IFS = SES +NOT = NÃO +OR = OU +SWITCH = PARÂMETRO +TRUE = VERDADEIRO +XOR = XOR ## -## Lookup and reference functions Funções de pesquisa e referência +## Funções de pesquisa e referência (Lookup & Reference Functions) ## -ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha -AREAS = ÁREAS ## Retorna o número de áreas em uma referência -CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores -COLUMN = COL ## Retorna o número da coluna de uma referência -COLUMNS = COLS ## Retorna o número de colunas em uma referência -HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada -HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet -INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz -INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto -LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz -MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz -OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência -ROW = LIN ## Retorna o número da linha de uma referência -ROWS = LINS ## Retorna o número de linhas em uma referência -RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).) -TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz -VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula - +ADDRESS = ENDEREÇO +AREAS = ÁREAS +CHOOSE = ESCOLHER +COLUMN = COL +COLUMNS = COLS +FORMULATEXT = FÓRMULATEXTO +GETPIVOTDATA = INFODADOSTABELADINÂMICA +HLOOKUP = PROCH +HYPERLINK = HIPERLINK +INDEX = ÍNDICE +INDIRECT = INDIRETO +LOOKUP = PROC +MATCH = CORRESP +OFFSET = DESLOC +ROW = LIN +ROWS = LINS +RTD = RTD +TRANSPOSE = TRANSPOR +VLOOKUP = PROCV ## -## Math and trigonometry functions Funções matemáticas e trigonométricas +## Funções matemáticas e trigonométricas (Math & Trig Functions) ## -ABS = ABS ## Retorna o valor absoluto de um número -ACOS = ACOS ## Retorna o arco cosseno de um número -ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número -ASIN = ASEN ## Retorna o arco seno de um número -ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número -ATAN = ATAN ## Retorna o arco tangente de um número -ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas -ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número -CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância -COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos -COS = COS ## Retorna o cosseno de um número -COSH = COSH ## Retorna o cosseno hiperbólico de um número -DEGREES = GRAUS ## Converte radianos em graus -EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo -EXP = EXP ## Retorna e elevado à potência de um número especificado -FACT = FATORIAL ## Retorna o fatorial de um número -FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número -FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero -GCD = MDC ## Retorna o máximo divisor comum -INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo -LCM = MMC ## Retorna o mínimo múltiplo comum -LN = LN ## Retorna o logaritmo natural de um número -LOG = LOG ## Retorna o logaritmo de um número de uma base especificada -LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número -MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz -MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz -MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes -MOD = RESTO ## Retorna o resto da divisão -MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado -MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números -ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo -PI = PI ## Retorna o valor de Pi -POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência -PRODUCT = MULT ## Multiplica seus argumentos -QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão -RADIANS = RADIANOS ## Converte graus em radianos -RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1 -RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados -ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto -ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos -ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero -ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero -SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula -SIGN = SINAL ## Retorna o sinal de um número -SIN = SEN ## Retorna o seno de um ângulo dado -SINH = SENH ## Retorna o seno hiperbólico de um número -SQRT = RAIZ ## Retorna uma raiz quadrada positiva -SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi) -SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados -SUM = SOMA ## Soma seus argumentos -SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério -SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios -SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes -SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos -SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes -SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes -SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes -TAN = TAN ## Retorna a tangente de um número -TANH = TANH ## Retorna a tangente hiperbólica de um número -TRUNC = TRUNCAR ## Trunca um número para um inteiro +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = ARÁBICO +ASIN = ASEN +ASINH = ASENH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = TETO.MAT +CEILING.PRECISE = TETO.PRECISO +COMBIN = COMBIN +COMBINA = COMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = COSEC +CSCH = COSECH +DECIMAL = DECIMAL +DEGREES = GRAUS +ECMA.CEILING = ECMA.TETO +EVEN = PAR +EXP = EXP +FACT = FATORIAL +FACTDOUBLE = FATDUPLO +FLOOR.MATH = ARREDMULTB.MAT +FLOOR.PRECISE = ARREDMULTB.PRECISO +GCD = MDC +INT = INT +ISO.CEILING = ISO.TETO +LCM = MMC +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATRIZ.DETERM +MINVERSE = MATRIZ.INVERSO +MMULT = MATRIZ.MULT +MOD = MOD +MROUND = MARRED +MULTINOMIAL = MULTINOMIAL +MUNIT = MUNIT +ODD = ÍMPAR +PI = PI +POWER = POTÊNCIA +PRODUCT = MULT +QUOTIENT = QUOCIENTE +RADIANS = RADIANOS +RAND = ALEATÓRIO +RANDBETWEEN = ALEATÓRIOENTRE +ROMAN = ROMANO +ROUND = ARRED +ROUNDDOWN = ARREDONDAR.PARA.BAIXO +ROUNDUP = ARREDONDAR.PARA.CIMA +SEC = SEC +SECH = SECH +SERIESSUM = SOMASEQÜÊNCIA +SIGN = SINAL +SIN = SEN +SINH = SENH +SQRT = RAIZ +SQRTPI = RAIZPI +SUBTOTAL = SUBTOTAL +SUM = SOMA +SUMIF = SOMASE +SUMIFS = SOMASES +SUMPRODUCT = SOMARPRODUTO +SUMSQ = SOMAQUAD +SUMX2MY2 = SOMAX2DY2 +SUMX2PY2 = SOMAX2SY2 +SUMXMY2 = SOMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR +## +## Funções estatísticas (Statistical Functions) +## +AVEDEV = DESV.MÉDIO +AVERAGE = MÉDIA +AVERAGEA = MÉDIAA +AVERAGEIF = MÉDIASE +AVERAGEIFS = MÉDIASES +BETA.DIST = DIST.BETA +BETA.INV = INV.BETA +BINOM.DIST = DISTR.BINOM +BINOM.DIST.RANGE = INTERV.DISTR.BINOM +BINOM.INV = INV.BINOM +CHISQ.DIST = DIST.QUIQUA +CHISQ.DIST.RT = DIST.QUIQUA.CD +CHISQ.INV = INV.QUIQUA +CHISQ.INV.RT = INV.QUIQUA.CD +CHISQ.TEST = TESTE.QUIQUA +CONFIDENCE.NORM = INT.CONFIANÇA.NORM +CONFIDENCE.T = INT.CONFIANÇA.T +CORREL = CORREL +COUNT = CONT.NÚM +COUNTA = CONT.VALORES +COUNTBLANK = CONTAR.VAZIO +COUNTIF = CONT.SE +COUNTIFS = CONT.SES +COVARIANCE.P = COVARIAÇÃO.P +COVARIANCE.S = COVARIAÇÃO.S +DEVSQ = DESVQ +EXPON.DIST = DISTR.EXPON +F.DIST = DIST.F +F.DIST.RT = DIST.F.CD +F.INV = INV.F +F.INV.RT = INV.F.CD +F.TEST = TESTE.F +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PREVISÃO.ETS +FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE +FORECAST.ETS.STAT = PREVISÃO.ETS.STAT +FORECAST.LINEAR = PREVISÃO.LINEAR +FREQUENCY = FREQÜÊNCIA +GAMMA = GAMA +GAMMA.DIST = DIST.GAMA +GAMMA.INV = INV.GAMA +GAMMALN = LNGAMA +GAMMALN.PRECISE = LNGAMA.PRECISO +GAUSS = GAUSS +GEOMEAN = MÉDIA.GEOMÉTRICA +GROWTH = CRESCIMENTO +HARMEAN = MÉDIA.HARMÔNICA +HYPGEOM.DIST = DIST.HIPERGEOM.N +INTERCEPT = INTERCEPÇÃO +KURT = CURT +LARGE = MAIOR +LINEST = PROJ.LIN +LOGEST = PROJ.LOG +LOGNORM.DIST = DIST.LOGNORMAL.N +LOGNORM.INV = INV.LOGNORMAL +MAX = MÁXIMO +MAXA = MÁXIMOA +MAXIFS = MÁXIMOSES +MEDIAN = MED +MIN = MÍNIMO +MINA = MÍNIMOA +MINIFS = MÍNIMOSES +MODE.MULT = MODO.MULT +MODE.SNGL = MODO.ÚNICO +NEGBINOM.DIST = DIST.BIN.NEG.N +NORM.DIST = DIST.NORM.N +NORM.INV = INV.NORM.N +NORM.S.DIST = DIST.NORMP.N +NORM.S.INV = INV.NORMP.N +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = ORDEM.PORCENTUAL.EXC +PERCENTRANK.INC = ORDEM.PORCENTUAL.INC +PERMUT = PERMUT +PERMUTATIONA = PERMUTAS +PHI = PHI +POISSON.DIST = DIST.POISSON +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = ORDEM.MÉD +RANK.EQ = ORDEM.EQ +RSQ = RQUAD +SKEW = DISTORÇÃO +SKEW.P = DISTORÇÃO.P +SLOPE = INCLINAÇÃO +SMALL = MENOR +STANDARDIZE = PADRONIZAR +STDEV.P = DESVPAD.P +STDEV.S = DESVPAD.A +STDEVA = DESVPADA +STDEVPA = DESVPADPA +STEYX = EPADYX +T.DIST = DIST.T +T.DIST.2T = DIST.T.BC +T.DIST.RT = DIST.T.CD +T.INV = INV.T +T.INV.2T = INV.T.BC +T.TEST = TESTE.T +TREND = TENDÊNCIA +TRIMMEAN = MÉDIA.INTERNA +VAR.P = VAR.P +VAR.S = VAR.A +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DIST.WEIBULL +Z.TEST = TESTE.Z ## -## Statistical functions Funções estatísticas +## Funções de texto (Text Functions) ## -AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média -AVERAGE = MÉDIA ## Retorna a média dos argumentos -AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos -AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério -AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios. -BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta -BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada -BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual -CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada -CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada -CHITEST = TESTE.QUI ## Retorna o teste para independência -CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população -CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados -COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos -COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos -COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado -COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios -COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios -COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares -CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão -DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios -EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial -FDIST = DISTF ## Retorna a distribuição de probabilidade F -FINV = INVF ## Retorna o inverso da distribuição de probabilidades F -FISHER = FISHER ## Retorna a transformação Fisher -FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher -FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta -FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical -FTEST = TESTEF ## Retorna o resultado de um teste F -GAMMADIST = DISTGAMA ## Retorna a distribuição gama -GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama -GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x) -GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica -GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial -HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica -HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica -INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear -KURT = CURT ## Retorna a curtose de um conjunto de dados -LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados -LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear -LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial -LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal -LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa -MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos -MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos -MEDIAN = MED ## Retorna a mediana dos números indicados -MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos -MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos -MODE = MODO ## Retorna o valor mais comum em um conjunto de dados -NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa -NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal -NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal -NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão -NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão -PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson -PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo -PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados -PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos -POISSON = POISSON ## Retorna a distribuição Poisson -PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites -QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados -RANK = ORDEM ## Retorna a posição de um número em uma lista de números -RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson -SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição -SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear -SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados -STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado -STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra -STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos -STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total -STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos -STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão -TDIST = DISTT ## Retorna a distribuição t de Student -TINV = INVT ## Retorna o inverso da distribuição t de Student -TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear -TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados -TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student -VAR = VAR ## Estima a variância com base em uma amostra -VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos -VARP = VARP ## Calcula a variância com base na população inteira -VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos -WEIBULL = WEIBULL ## Retorna a distribuição Weibull -ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z +BAHTTEXT = BAHTTEXT +CHAR = CARACT +CLEAN = TIRAR +CODE = CÓDIGO +CONCAT = CONCAT +DOLLAR = MOEDA +EXACT = EXATO +FIND = PROCURAR +FIXED = DEF.NÚM.DEC +LEFT = ESQUERDA +LEN = NÚM.CARACT +LOWER = MINÚSCULA +MID = EXT.TEXTO +NUMBERSTRING = SEQÜÊNCIA.NÚMERO +NUMBERVALUE = VALORNUMÉRICO +PHONETIC = FONÉTICA +PROPER = PRI.MAIÚSCULA +REPLACE = MUDAR +REPT = REPT +RIGHT = DIREITA +SEARCH = LOCALIZAR +SUBSTITUTE = SUBSTITUIR +T = T +TEXT = TEXTO +TEXTJOIN = UNIRTEXTO +TRIM = ARRUMAR +UNICHAR = CARACTUNICODE +UNICODE = UNICODE +UPPER = MAIÚSCULA +VALUE = VALOR +## +## Funções da Web (Web Functions) +## +ENCODEURL = CODIFURL +FILTERXML = FILTROXML +WEBSERVICE = SERVIÇOWEB ## -## Text functions Funções de texto +## Funções de compatibilidade (Compatibility Functions) ## -ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único) -BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht) -CHAR = CARACT ## Retorna o caractere especificado pelo número de código -CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos -CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto -CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto -DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar) -EXACT = EXATO ## Verifica se dois valores de texto são idênticos -FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) -FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) -FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais -JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos) -LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto -LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto -LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto -LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto -LOWER = MINÚSCULA ## Converte texto para minúsculas -MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada -MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada -PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto -PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto -REPLACE = MUDAR ## Muda os caracteres dentro do texto -REPLACEB = MUDARB ## Muda os caracteres dentro do texto -REPT = REPT ## Repete o texto um determinado número de vezes -RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto -RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto -SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) -SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) -SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto -T = T ## Converte os argumentos em texto -TEXT = TEXTO ## Formata um número e o converte em texto -TRIM = ARRUMAR ## Remove espaços do texto -UPPER = MAIÚSCULA ## Converte o texto em maiúsculas -VALUE = VALOR ## Converte um argumento de texto em um número +BETADIST = DISTBETA +BETAINV = BETA.ACUM.INV +BINOMDIST = DISTRBINOM +CEILING = TETO +CHIDIST = DIST.QUI +CHIINV = INV.QUI +CHITEST = TESTE.QUI +CONCATENATE = CONCATENAR +CONFIDENCE = INT.CONFIANÇA +COVAR = COVAR +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTEXPON +FDIST = DISTF +FINV = INVF +FLOOR = ARREDMULTB +FORECAST = PREVISÃO +FTEST = TESTEF +GAMMADIST = DISTGAMA +GAMMAINV = INVGAMA +HYPGEOMDIST = DIST.HIPERGEOM +LOGINV = INVLOG +LOGNORMDIST = DIST.LOGNORMAL +MODE = MODO +NEGBINOMDIST = DIST.BIN.NEG +NORMDIST = DISTNORM +NORMINV = INV.NORM +NORMSDIST = DISTNORMP +NORMSINV = INV.NORMP +PERCENTILE = PERCENTIL +PERCENTRANK = ORDEM.PORCENTUAL +POISSON = POISSON +QUARTILE = QUARTIL +RANK = ORDEM +STDEV = DESVPAD +STDEVP = DESVPADP +TDIST = DISTT +TINV = INVT +TTEST = TESTET +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = TESTEZ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config index cd85c17a..e661830b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Português (Portuguese) ## -## (For future use) -## -currencySymbol = € +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #NULO! -DIV0 = #DIV/0! -VALUE = #VALOR! -REF = #REF! -NAME = #NOME? -NUM = #NÚM! -NA = #N/D +NULL = #NULO! +DIV0 +VALUE = #VALOR! +REF +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions index ba4eb471..8a94d826 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/pt/functions @@ -1,408 +1,537 @@ +############################################################ ## -## Add-in and Automation functions Funções de Suplemento e Automatização +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica +## Português (Portuguese) +## +############################################################ ## -## Cube functions Funções de cubo +## Funções de cubo (Cube Functions) ## -CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização. -CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo. -CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro. -CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos. -CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel. -CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto. -CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo. - +CUBEKPIMEMBER = MEMBROKPICUBO +CUBEMEMBER = MEMBROCUBO +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO +CUBESET = CONJUNTOCUBO +CUBESETCOUNT = CONTARCONJUNTOCUBO +CUBEVALUE = VALORCUBO ## -## Database functions Funções de base de dados +## Funções de base de dados (Database Functions) ## -DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas -DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados -DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados -DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados -DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas -DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas -DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados -DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas -DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas -DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios -DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas -DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas - +DAVERAGE = BDMÉDIA +DCOUNT = BDCONTAR +DCOUNTA = BDCONTAR.VAL +DGET = BDOBTER +DMAX = BDMÁX +DMIN = BDMÍN +DPRODUCT = BDMULTIPL +DSTDEV = BDDESVPAD +DSTDEVP = BDDESVPADP +DSUM = BDSOMA +DVAR = BDVAR +DVARP = BDVARP ## -## Date and time functions Funções de data e hora +## Funções de data e hora (Date & Time Functions) ## -DATE = DATA ## Devolve o número de série de uma determinada data -DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série -DAY = DIA ## Converte um número de série num dia do mês -DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias -EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início -EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado -HOUR = HORA ## Converte um número de série numa hora -MINUTE = MINUTO ## Converte um número de série num minuto -MONTH = MÊS ## Converte um número de série num mês -NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas -NOW = AGORA ## Devolve o número de série da data e hora actuais -SECOND = SEGUNDO ## Converte um número de série num segundo -TIME = TEMPO ## Devolve o número de série de um determinado tempo -TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série -TODAY = HOJE ## Devolve o número de série da data actual -WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana -WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano -WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado -YEAR = ANO ## Converte um número de série num ano -YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim - +DATE = DATA +DATEDIF = DATADIF +DATESTRING = DATA.CADEIA +DATEVALUE = DATA.VALOR +DAY = DIA +DAYS = DIAS +DAYS360 = DIAS360 +EDATE = DATAM +EOMONTH = FIMMÊS +HOUR = HORA +ISOWEEKNUM = NUMSEMANAISO +MINUTE = MINUTO +MONTH = MÊS +NETWORKDAYS = DIATRABALHOTOTAL +NETWORKDAYS.INTL = DIATRABALHOTOTAL.INTL +NOW = AGORA +SECOND = SEGUNDO +THAIDAYOFWEEK = DIA.DA.SEMANA.TAILANDÊS +THAIMONTHOFYEAR = MÊS.DO.ANO.TAILANDÊS +THAIYEAR = ANO.TAILANDÊS +TIME = TEMPO +TIMEVALUE = VALOR.TEMPO +TODAY = HOJE +WEEKDAY = DIA.SEMANA +WEEKNUM = NÚMSEMANA +WORKDAY = DIATRABALHO +WORKDAY.INTL = DIATRABALHO.INTL +YEAR = ANO +YEARFRAC = FRAÇÃOANO ## -## Engineering functions Funções de engenharia +## Funções de engenharia (Engineering Functions) ## -BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x) -BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x) -BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x) -BESSELY = BESSELY ## Devolve a função de Bessel Yn(x) -BIN2DEC = BINADEC ## Converte um número binário em decimal -BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal -BIN2OCT = BINAOCT ## Converte um número binário em octal -COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo -CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro -DEC2BIN = DECABIN ## Converte um número decimal em binário -DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal -DEC2OCT = DECAOCT ## Converte um número decimal em octal -DELTA = DELTA ## Testa se dois valores são iguais -ERF = FUNCERRO ## Devolve a função de erro -ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar -GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite -HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário -HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal -HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal -IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo -IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo -IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos -IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo -IMCOS = IMCOS ## Devolve o co-seno de um número complexo -IMDIV = IMDIV ## Devolve o quociente de dois números complexos -IMEXP = IMEXP ## Devolve o exponencial de um número complexo -IMLN = IMLN ## Devolve o logaritmo natural de um número complexo -IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo -IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo -IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira -IMPRODUCT = IMPROD ## Devolve o produto de números complexos -IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo -IMSIN = IMSENO ## Devolve o seno de um número complexo -IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo -IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos -IMSUM = IMSOMA ## Devolve a soma de números complexos -OCT2BIN = OCTABIN ## Converte um número octal em binário -OCT2DEC = OCTADEC ## Converte um número octal em decimal -OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BINADEC +BIN2HEX = BINAHEX +BIN2OCT = BINAOCT +BITAND = BIT.E +BITLSHIFT = BITDESL.ESQ +BITOR = BIT.OU +BITRSHIFT = BITDESL.DIR +BITXOR = BIT.XOU +COMPLEX = COMPLEXO +CONVERT = CONVERTER +DEC2BIN = DECABIN +DEC2HEX = DECAHEX +DEC2OCT = DECAOCT +DELTA = DELTA +ERF = FUNCERRO +ERF.PRECISE = FUNCERRO.PRECISO +ERFC = FUNCERROCOMPL +ERFC.PRECISE = FUNCERROCOMPL.PRECISO +GESTEP = DEGRAU +HEX2BIN = HEXABIN +HEX2DEC = HEXADEC +HEX2OCT = HEXAOCT +IMABS = IMABS +IMAGINARY = IMAGINÁRIO +IMARGUMENT = IMARG +IMCONJUGATE = IMCONJ +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEXP +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMPOT +IMPRODUCT = IMPROD +IMREAL = IMREAL +IMSEC = IMSEC +IMSECH = IMSECH +IMSIN = IMSENO +IMSINH = IMSENOH +IMSQRT = IMRAIZ +IMSUB = IMSUBTR +IMSUM = IMSOMA +IMTAN = IMTAN +OCT2BIN = OCTABIN +OCT2DEC = OCTADEC +OCT2HEX = OCTAHEX ## -## Financial functions Funções financeiras +## Funções financeiras (Financial Functions) ## -ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos -ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento -AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação -AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico -COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização -COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização -COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte -COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização -COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento -COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização -CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos -CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos -DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas -DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado -DISC = DESC ## Devolve a taxa de desconto de um título -DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal -DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção -DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos -EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva -FV = VF ## Devolve o valor futuro de um investimento -FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas -INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade -IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período -IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários -ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento -MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100 -MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes -NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual -NPER = NPER ## Devolve o número de períodos de um investimento -NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto -ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto -ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto -ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto -ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto -PMT = PGTO ## Devolve o pagamento periódico de uma anuidade -PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período -PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos -PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado -PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento -PV = VA ## Devolve o valor actual de um investimento -RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade -RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade -SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período -SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado -TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro -TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro -TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro -VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas -XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica -XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico -YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos -YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro -YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento - +ACCRINT = JUROSACUM +ACCRINTM = JUROSACUMV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = CUPDIASINLIQ +COUPDAYS = CUPDIAS +COUPDAYSNC = CUPDIASPRÓX +COUPNCD = CUPDATAPRÓX +COUPNUM = CUPNÚM +COUPPCD = CUPDATAANT +CUMIPMT = PGTOJURACUM +CUMPRINC = PGTOCAPACUM +DB = BD +DDB = BDD +DISC = DESC +DOLLARDE = MOEDADEC +DOLLARFR = MOEDAFRA +DURATION = DURAÇÃO +EFFECT = EFETIVA +FV = VF +FVSCHEDULE = VFPLANO +INTRATE = TAXAJUROS +IPMT = IPGTO +IRR = TIR +ISPMT = É.PGTO +MDURATION = MDURAÇÃO +MIRR = MTIR +NOMINAL = NOMINAL +NPER = NPER +NPV = VAL +ODDFPRICE = PREÇOPRIMINC +ODDFYIELD = LUCROPRIMINC +ODDLPRICE = PREÇOÚLTINC +ODDLYIELD = LUCROÚLTINC +PDURATION = PDURAÇÃO +PMT = PGTO +PPMT = PPGTO +PRICE = PREÇO +PRICEDISC = PREÇODESC +PRICEMAT = PREÇOVENC +PV = VA +RATE = TAXA +RECEIVED = RECEBER +RRI = DEVOLVERTAXAJUROS +SLN = AMORT +SYD = AMORTD +TBILLEQ = OTN +TBILLPRICE = OTNVALOR +TBILLYIELD = OTNLUCRO +VDB = BDV +XIRR = XTIR +XNPV = XVAL +YIELD = LUCRO +YIELDDISC = LUCRODESC +YIELDMAT = LUCROVENC ## -## Information functions Funções de informação +## Funções de informação (Information Functions) ## -CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula -ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro -INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual -ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco -ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D -ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro -ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par -ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico -ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D -ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto -ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número -ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar -ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência -ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto -N = N ## Devolve um valor convertido num número -NA = NÃO.DISP ## Devolve o valor de erro #N/D -TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor - +CELL = CÉL +ERROR.TYPE = TIPO.ERRO +INFO = INFORMAÇÃO +ISBLANK = É.CÉL.VAZIA +ISERR = É.ERROS +ISERROR = É.ERRO +ISEVEN = ÉPAR +ISFORMULA = É.FORMULA +ISLOGICAL = É.LÓGICO +ISNA = É.NÃO.DISP +ISNONTEXT = É.NÃO.TEXTO +ISNUMBER = É.NÚM +ISODD = ÉÍMPAR +ISREF = É.REF +ISTEXT = É.TEXTO +N = N +NA = NÃO.DISP +SHEET = FOLHA +SHEETS = FOLHAS +TYPE = TIPO ## -## Logical functions Funções lógicas +## Funções lógicas (Logical Functions) ## -AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO -FALSE = FALSO ## Devolve o valor lógico FALSO -IF = SE ## Especifica um teste lógico a ser executado -IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro -NOT = NÃO ## Inverte a lógica do respectivo argumento -OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO -TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO - +AND = E +FALSE = FALSO +IF = SE +IFERROR = SE.ERRO +IFNA = SEND +IFS = SE.S +NOT = NÃO +OR = OU +SWITCH = PARÂMETRO +TRUE = VERDADEIRO +XOR = XOU ## -## Lookup and reference functions Funções de pesquisa e referência +## Funções de pesquisa e referência (Lookup & Reference Functions) ## -ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto -AREAS = ÁREAS ## Devolve o número de áreas numa referência -CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores -COLUMN = COL ## Devolve o número da coluna de uma referência -COLUMNS = COLS ## Devolve o número de colunas numa referência -HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada -HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet -INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz -INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto -LOOKUP = PROC ## Procura valores num vector ou numa matriz -MATCH = CORRESP ## Procura valores numa referência ou numa matriz -OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência -ROW = LIN ## Devolve o número da linha de uma referência -ROWS = LINS ## Devolve o número de linhas numa referência -RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).) -TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz -VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula - +ADDRESS = ENDEREÇO +AREAS = ÁREAS +CHOOSE = SELECIONAR +COLUMN = COL +COLUMNS = COLS +FORMULATEXT = FÓRMULA.TEXTO +GETPIVOTDATA = OBTERDADOSDIN +HLOOKUP = PROCH +HYPERLINK = HIPERLIGAÇÃO +INDEX = ÍNDICE +INDIRECT = INDIRETO +LOOKUP = PROC +MATCH = CORRESP +OFFSET = DESLOCAMENTO +ROW = LIN +ROWS = LINS +RTD = RTD +TRANSPOSE = TRANSPOR +VLOOKUP = PROCV ## -## Math and trigonometry functions Funções matemáticas e trigonométricas +## Funções matemáticas e trigonométricas (Math & Trig Functions) ## -ABS = ABS ## Devolve o valor absoluto de um número -ACOS = ACOS ## Devolve o arco de co-seno de um número -ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número -ASIN = ASEN ## Devolve o arco de seno de um número -ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número -ATAN = ATAN ## Devolve o arco de tangente de um número -ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y -ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número -CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo -COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos -COS = COS ## Devolve o co-seno de um número -COSH = COSH ## Devolve o co-seno hiperbólico de um número -DEGREES = GRAUS ## Converte radianos em graus -EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo -EXP = EXP ## Devolve e elevado à potência de um determinado número -FACT = FACTORIAL ## Devolve o factorial de um número -FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número -FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero -GCD = MDC ## Devolve o maior divisor comum -INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo -LCM = MMC ## Devolve o mínimo múltiplo comum -LN = LN ## Devolve o logaritmo natural de um número -LOG = LOG ## Devolve o logaritmo de um número com uma base especificada -LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número -MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz -MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz -MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes -MOD = RESTO ## Devolve o resto da divisão -MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido -MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números -ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo -PI = PI ## Devolve o valor de pi -POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência -PRODUCT = PRODUTO ## Multiplica os respectivos argumentos -QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão -RADIANS = RADIANOS ## Converte graus em radianos -RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1 -RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados -ROMAN = ROMANO ## Converte um número árabe em romano, como texto -ROUND = ARRED ## Arredonda um número para um número de dígitos especificado -ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero -ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero -SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula -SIGN = SINAL ## Devolve o sinal de um número -SIN = SEN ## Devolve o seno de um determinado ângulo -SINH = SENH ## Devolve o seno hiperbólico de um número -SQRT = RAIZQ ## Devolve uma raiz quadrada positiva -SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi) -SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados -SUM = SOMA ## Adiciona os respectivos argumentos -SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério -SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios -SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes -SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos -SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes -SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes -SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes -TAN = TAN ## Devolve a tangente de um número -TANH = TANH ## Devolve a tangente hiperbólica de um número -TRUNC = TRUNCAR ## Trunca um número para um número inteiro +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = AGREGAR +ARABIC = ÁRABE +ASIN = ASEN +ASINH = ASENH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = BASE +CEILING.MATH = ARRED.EXCESSO.MAT +CEILING.PRECISE = ARRED.EXCESSO.PRECISO +COMBIN = COMBIN +COMBINA = COMBIN.R +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRAUS +ECMA.CEILING = ARRED.EXCESSO.ECMA +EVEN = PAR +EXP = EXP +FACT = FATORIAL +FACTDOUBLE = FATDUPLO +FLOOR.MATH = ARRED.DEFEITO.MAT +FLOOR.PRECISE = ARRED.DEFEITO.PRECISO +GCD = MDC +INT = INT +ISO.CEILING = ARRED.EXCESSO.ISO +LCM = MMC +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MATRIZ.DETERM +MINVERSE = MATRIZ.INVERSA +MMULT = MATRIZ.MULT +MOD = RESTO +MROUND = MARRED +MULTINOMIAL = POLINOMIAL +MUNIT = UNIDM +ODD = ÍMPAR +PI = PI +POWER = POTÊNCIA +PRODUCT = PRODUTO +QUOTIENT = QUOCIENTE +RADIANS = RADIANOS +RAND = ALEATÓRIO +RANDBETWEEN = ALEATÓRIOENTRE +ROMAN = ROMANO +ROUND = ARRED +ROUNDBAHTDOWN = ARREDOND.BAHT.BAIXO +ROUNDBAHTUP = ARREDOND.BAHT.CIMA +ROUNDDOWN = ARRED.PARA.BAIXO +ROUNDUP = ARRED.PARA.CIMA +SEC = SEC +SECH = SECH +SERIESSUM = SOMASÉRIE +SIGN = SINAL +SIN = SEN +SINH = SENH +SQRT = RAIZQ +SQRTPI = RAIZPI +SUBTOTAL = SUBTOTAL +SUM = SOMA +SUMIF = SOMA.SE +SUMIFS = SOMA.SE.S +SUMPRODUCT = SOMARPRODUTO +SUMSQ = SOMARQUAD +SUMX2MY2 = SOMAX2DY2 +SUMX2PY2 = SOMAX2SY2 +SUMXMY2 = SOMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = TRUNCAR +## +## Funções estatísticas (Statistical Functions) +## +AVEDEV = DESV.MÉDIO +AVERAGE = MÉDIA +AVERAGEA = MÉDIAA +AVERAGEIF = MÉDIA.SE +AVERAGEIFS = MÉDIA.SE.S +BETA.DIST = DIST.BETA +BETA.INV = INV.BETA +BINOM.DIST = DISTR.BINOM +BINOM.DIST.RANGE = DIST.BINOM.INTERVALO +BINOM.INV = INV.BINOM +CHISQ.DIST = DIST.CHIQ +CHISQ.DIST.RT = DIST.CHIQ.DIR +CHISQ.INV = INV.CHIQ +CHISQ.INV.RT = INV.CHIQ.DIR +CHISQ.TEST = TESTE.CHIQ +CONFIDENCE.NORM = INT.CONFIANÇA.NORM +CONFIDENCE.T = INT.CONFIANÇA.T +CORREL = CORREL +COUNT = CONTAR +COUNTA = CONTAR.VAL +COUNTBLANK = CONTAR.VAZIO +COUNTIF = CONTAR.SE +COUNTIFS = CONTAR.SE.S +COVARIANCE.P = COVARIÂNCIA.P +COVARIANCE.S = COVARIÂNCIA.S +DEVSQ = DESVQ +EXPON.DIST = DIST.EXPON +F.DIST = DIST.F +F.DIST.RT = DIST.F.DIR +F.INV = INV.F +F.INV.RT = INV.F.DIR +F.TEST = TESTE.F +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PREVISÃO.ETS +FORECAST.ETS.CONFINT = PREVISÃO.ETS.CONFINT +FORECAST.ETS.SEASONALITY = PREVISÃO.ETS.SAZONALIDADE +FORECAST.ETS.STAT = PREVISÃO.ETS.ESTATÍSTICA +FORECAST.LINEAR = PREVISÃO.LINEAR +FREQUENCY = FREQUÊNCIA +GAMMA = GAMA +GAMMA.DIST = DIST.GAMA +GAMMA.INV = INV.GAMA +GAMMALN = LNGAMA +GAMMALN.PRECISE = LNGAMA.PRECISO +GAUSS = GAUSS +GEOMEAN = MÉDIA.GEOMÉTRICA +GROWTH = CRESCIMENTO +HARMEAN = MÉDIA.HARMÓNICA +HYPGEOM.DIST = DIST.HIPGEOM +INTERCEPT = INTERCETAR +KURT = CURT +LARGE = MAIOR +LINEST = PROJ.LIN +LOGEST = PROJ.LOG +LOGNORM.DIST = DIST.NORMLOG +LOGNORM.INV = INV.NORMALLOG +MAX = MÁXIMO +MAXA = MÁXIMOA +MAXIFS = MÁXIMO.SE.S +MEDIAN = MED +MIN = MÍNIMO +MINA = MÍNIMOA +MINIFS = MÍNIMO.SE.S +MODE.MULT = MODO.MÚLT +MODE.SNGL = MODO.SIMPLES +NEGBINOM.DIST = DIST.BINOM.NEG +NORM.DIST = DIST.NORMAL +NORM.INV = INV.NORMAL +NORM.S.DIST = DIST.S.NORM +NORM.S.INV = INV.S.NORM +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXC +PERCENTILE.INC = PERCENTIL.INC +PERCENTRANK.EXC = ORDEM.PERCENTUAL.EXC +PERCENTRANK.INC = ORDEM.PERCENTUAL.INC +PERMUT = PERMUTAR +PERMUTATIONA = PERMUTAR.R +PHI = PHI +POISSON.DIST = DIST.POISSON +PROB = PROB +QUARTILE.EXC = QUARTIL.EXC +QUARTILE.INC = QUARTIL.INC +RANK.AVG = ORDEM.MÉD +RANK.EQ = ORDEM.EQ +RSQ = RQUAD +SKEW = DISTORÇÃO +SKEW.P = DISTORÇÃO.P +SLOPE = DECLIVE +SMALL = MENOR +STANDARDIZE = NORMALIZAR +STDEV.P = DESVPAD.P +STDEV.S = DESVPAD.S +STDEVA = DESVPADA +STDEVPA = DESVPADPA +STEYX = EPADYX +T.DIST = DIST.T +T.DIST.2T = DIST.T.2C +T.DIST.RT = DIST.T.DIR +T.INV = INV.T +T.INV.2T = INV.T.2C +T.TEST = TESTE.T +TREND = TENDÊNCIA +TRIMMEAN = MÉDIA.INTERNA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = DIST.WEIBULL +Z.TEST = TESTE.Z ## -## Statistical functions Funções estatísticas +## Funções de texto (Text Functions) ## -AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados -AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos -AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos -AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério -AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios -BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta -BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica -BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual -CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada -CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada -CHITEST = TESTE.CHI ## Devolve o teste para independência -CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população -CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados -COUNT = CONTAR ## Conta os números que existem na lista de argumentos -COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos -COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo -COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados -COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios -COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares -CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério -DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios -EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial -FDIST = DISTF ## Devolve a distribuição da probabilidade F -FINV = INVF ## Devolve o inverso da distribuição da probabilidade F -FISHER = FISHER ## Devolve a transformação Fisher -FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher -FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear -FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical -FTEST = TESTEF ## Devolve o resultado de um teste F -GAMMADIST = DISTGAMA ## Devolve a distribuição gama -GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa -GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x) -GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica -GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial -HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica -HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica -INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear -KURT = CURT ## Devolve a curtose de um conjunto de dados -LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados -LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear -LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial -LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica -LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa -MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos -MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos -MEDIAN = MED ## Devolve a mediana dos números indicados -MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos -MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos -MODE = MODA ## Devolve o valor mais comum num conjunto de dados -NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa -NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal -NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal -NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão -NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão -PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson -PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo -PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados -PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos -POISSON = POISSON ## Devolve a distribuição de Poisson -PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites -QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados -RANK = ORDEM ## Devolve a ordem de um número numa lista numérica -RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson -SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição -SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear -SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados -STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado -STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra -STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos -STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total -STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos -STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão -TDIST = DISTT ## Devolve a distribuição t de Student -TINV = INVT ## Devolve o inverso da distribuição t de Student -TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear -TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados -TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student -VAR = VAR ## Calcula a variância com base numa amostra -VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos -VARP = VARP ## Calcula a variância com base na população total -VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos -WEIBULL = WEIBULL ## Devolve a distribuição Weibull -ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z +BAHTTEXT = TEXTO.BAHT +CHAR = CARÁT +CLEAN = LIMPARB +CODE = CÓDIGO +CONCAT = CONCAT +DOLLAR = MOEDA +EXACT = EXATO +FIND = LOCALIZAR +FIXED = FIXA +ISTHAIDIGIT = É.DÍGITO.TAILANDÊS +LEFT = ESQUERDA +LEN = NÚM.CARAT +LOWER = MINÚSCULAS +MID = SEG.TEXTO +NUMBERSTRING = NÚMERO.CADEIA +NUMBERVALUE = VALOR.NÚMERO +PHONETIC = FONÉTICA +PROPER = INICIAL.MAIÚSCULA +REPLACE = SUBSTITUIR +REPT = REPETIR +RIGHT = DIREITA +SEARCH = PROCURAR +SUBSTITUTE = SUBST +T = T +TEXT = TEXTO +TEXTJOIN = UNIRTEXTO +THAIDIGIT = DÍGITO.TAILANDÊS +THAINUMSOUND = SOM.NÚM.TAILANDÊS +THAINUMSTRING = CADEIA.NÚM.TAILANDÊS +THAISTRINGLENGTH = COMP.CADEIA.TAILANDÊS +TRIM = COMPACTAR +UNICHAR = UNICARÁT +UNICODE = UNICODE +UPPER = MAIÚSCULAS +VALUE = VALOR +## +## Funções da Web (Web Functions) +## +ENCODEURL = CODIFICAÇÃOURL +FILTERXML = FILTRARXML +WEBSERVICE = SERVIÇOWEB ## -## Text functions Funções de texto +## Funções de compatibilidade (Compatibility Functions) ## -ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único) -BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht) -CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código -CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis -CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto -CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto -DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro) -EXACT = EXACTO ## Verifica se dois valores de texto são idênticos -FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) -FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) -FIXED = FIXA ## Formata um número como texto com um número fixo de decimais -JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo) -LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto -LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto -LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto -LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto -LOWER = MINÚSCULAS ## Converte o texto em minúsculas -MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada -MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada -PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto -PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto -REPLACE = SUBSTITUIR ## Substitui caracteres no texto -REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto -REPT = REPETIR ## Repete texto um determinado número de vezes -RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto -RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto -SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) -SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) -SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto -T = T ## Converte os respectivos argumentos em texto -TEXT = TEXTO ## Formata um número e converte-o em texto -TRIM = COMPACTAR ## Remove espaços do texto -UPPER = MAIÚSCULAS ## Converte texto em maiúsculas -VALUE = VALOR ## Converte um argumento de texto num número +BETADIST = DISTBETA +BETAINV = BETA.ACUM.INV +BINOMDIST = DISTRBINOM +CEILING = ARRED.EXCESSO +CHIDIST = DIST.CHI +CHIINV = INV.CHI +CHITEST = TESTE.CHI +CONCATENATE = CONCATENAR +CONFIDENCE = INT.CONFIANÇA +COVAR = COVAR +CRITBINOM = CRIT.BINOM +EXPONDIST = DISTEXPON +FDIST = DISTF +FINV = INVF +FLOOR = ARRED.DEFEITO +FORECAST = PREVISÃO +FTEST = TESTEF +GAMMADIST = DISTGAMA +GAMMAINV = INVGAMA +HYPGEOMDIST = DIST.HIPERGEOM +LOGINV = INVLOG +LOGNORMDIST = DIST.NORMALLOG +MODE = MODA +NEGBINOMDIST = DIST.BIN.NEG +NORMDIST = DIST.NORM +NORMINV = INV.NORM +NORMSDIST = DIST.NORMP +NORMSINV = INV.NORMP +PERCENTILE = PERCENTIL +PERCENTRANK = ORDEM.PERCENTUAL +POISSON = POISSON +QUARTILE = QUARTIL +RANK = ORDEM +STDEV = DESVPAD +STDEVP = DESVPADP +TDIST = DISTT +TINV = INVT +TTEST = TESTET +VAR = VAR +VARP = VARP +WEIBULL = WEIBULL +ZTEST = TESTEZ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config index 9ee9e6cc..2a5a0db8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## русский язык (Russian) ## -## (For future use) -## -currencySymbol = р +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #ПУСТО! -DIV0 = #ДЕЛ/0! -VALUE = #ЗНАЧ! -REF = #ССЫЛ! -NAME = #ИМЯ? -NUM = #ЧИСЛО! -NA = #Н/Д +NULL = #ПУСТО! +DIV0 = #ДЕЛ/0! +VALUE = #ЗНАЧ! +REF = #ССЫЛКА! +NAME = #ИМЯ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions index 3597dbf8..9f05d5af 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/ru/functions @@ -1,416 +1,555 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from information provided by web-junior (http://www.web-junior.net/) +## PhpSpreadsheet - function name translations ## +## русский язык (Russian) ## +############################################################ ## -## Add-in and Automation functions Функции надстроек и автоматизации +## Функции кубов (Cube Functions) ## -GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы. - +CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП +CUBEMEMBER = КУБЭЛЕМЕНТ +CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА +CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ +CUBESET = КУБМНОЖ +CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ +CUBEVALUE = КУБЗНАЧЕНИЕ ## -## Cube functions Функции Куб +## Функции для работы с базами данных (Database Functions) ## -CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации. -CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе. -CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента. -CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов. -CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel. -CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества. -CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба. - +DAVERAGE = ДСРЗНАЧ +DCOUNT = БСЧЁТ +DCOUNTA = БСЧЁТА +DGET = БИЗВЛЕЧЬ +DMAX = ДМАКС +DMIN = ДМИН +DPRODUCT = БДПРОИЗВЕД +DSTDEV = ДСТАНДОТКЛ +DSTDEVP = ДСТАНДОТКЛП +DSUM = БДСУММ +DVAR = БДДИСП +DVARP = БДДИСПП ## -## Database functions Функции для работы с базами данных +## Функции даты и времени (Date & Time Functions) ## -DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных. -DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных. -DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных. -DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию. -DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных. -DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных. -DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию. -DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных. -DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных -DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию. -DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных -DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных - +DATE = ДАТА +DATEDIF = РАЗНДАТ +DATESTRING = СТРОКАДАННЫХ +DATEVALUE = ДАТАЗНАЧ +DAY = ДЕНЬ +DAYS = ДНИ +DAYS360 = ДНЕЙ360 +EDATE = ДАТАМЕС +EOMONTH = КОНМЕСЯЦА +HOUR = ЧАС +ISOWEEKNUM = НОМНЕДЕЛИ.ISO +MINUTE = МИНУТЫ +MONTH = МЕСЯЦ +NETWORKDAYS = ЧИСТРАБДНИ +NETWORKDAYS.INTL = ЧИСТРАБДНИ.МЕЖД +NOW = ТДАТА +SECOND = СЕКУНДЫ +THAIDAYOFWEEK = ТАЙДЕНЬНЕД +THAIMONTHOFYEAR = ТАЙМЕСЯЦ +THAIYEAR = ТАЙГОД +TIME = ВРЕМЯ +TIMEVALUE = ВРЕМЗНАЧ +TODAY = СЕГОДНЯ +WEEKDAY = ДЕНЬНЕД +WEEKNUM = НОМНЕДЕЛИ +WORKDAY = РАБДЕНЬ +WORKDAY.INTL = РАБДЕНЬ.МЕЖД +YEAR = ГОД +YEARFRAC = ДОЛЯГОДА ## -## Date and time functions Функции даты и времени +## Инженерные функции (Engineering Functions) ## -DATE = ДАТА ## Возвращает заданную дату в числовом формате. -DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат. -DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца. -DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года. -EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты. -EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев. -HOUR = ЧАС ## Преобразует дату в числовом формате в часы. -MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты. -MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы. -NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами. -NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате. -SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды. -TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате. -TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат. -TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате. -WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели. -WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата. -WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней. -YEAR = ГОД ## Преобразует дату в числовом формате в год. -YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами. - +BESSELI = БЕССЕЛЬ.I +BESSELJ = БЕССЕЛЬ.J +BESSELK = БЕССЕЛЬ.K +BESSELY = БЕССЕЛЬ.Y +BIN2DEC = ДВ.В.ДЕС +BIN2HEX = ДВ.В.ШЕСТН +BIN2OCT = ДВ.В.ВОСЬМ +BITAND = БИТ.И +BITLSHIFT = БИТ.СДВИГЛ +BITOR = БИТ.ИЛИ +BITRSHIFT = БИТ.СДВИГП +BITXOR = БИТ.ИСКЛИЛИ +COMPLEX = КОМПЛЕКСН +CONVERT = ПРЕОБР +DEC2BIN = ДЕС.В.ДВ +DEC2HEX = ДЕС.В.ШЕСТН +DEC2OCT = ДЕС.В.ВОСЬМ +DELTA = ДЕЛЬТА +ERF = ФОШ +ERF.PRECISE = ФОШ.ТОЧН +ERFC = ДФОШ +ERFC.PRECISE = ДФОШ.ТОЧН +GESTEP = ПОРОГ +HEX2BIN = ШЕСТН.В.ДВ +HEX2DEC = ШЕСТН.В.ДЕС +HEX2OCT = ШЕСТН.В.ВОСЬМ +IMABS = МНИМ.ABS +IMAGINARY = МНИМ.ЧАСТЬ +IMARGUMENT = МНИМ.АРГУМЕНТ +IMCONJUGATE = МНИМ.СОПРЯЖ +IMCOS = МНИМ.COS +IMCOSH = МНИМ.COSH +IMCOT = МНИМ.COT +IMCSC = МНИМ.CSC +IMCSCH = МНИМ.CSCH +IMDIV = МНИМ.ДЕЛ +IMEXP = МНИМ.EXP +IMLN = МНИМ.LN +IMLOG10 = МНИМ.LOG10 +IMLOG2 = МНИМ.LOG2 +IMPOWER = МНИМ.СТЕПЕНЬ +IMPRODUCT = МНИМ.ПРОИЗВЕД +IMREAL = МНИМ.ВЕЩ +IMSEC = МНИМ.SEC +IMSECH = МНИМ.SECH +IMSIN = МНИМ.SIN +IMSINH = МНИМ.SINH +IMSQRT = МНИМ.КОРЕНЬ +IMSUB = МНИМ.РАЗН +IMSUM = МНИМ.СУММ +IMTAN = МНИМ.TAN +OCT2BIN = ВОСЬМ.В.ДВ +OCT2DEC = ВОСЬМ.В.ДЕС +OCT2HEX = ВОСЬМ.В.ШЕСТН ## -## Engineering functions Инженерные функции +## Финансовые функции (Financial Functions) ## -BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x). -BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x). -BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x). -BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x). -BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное. -BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное. -BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное. -COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число. -CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую. -DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное. -DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное. -DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное. -DELTA = ДЕЛЬТА ## Проверяет равенство двух значений. -ERF = ФОШ ## Возвращает функцию ошибки. -ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки. -GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения. -HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное. -HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное. -HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное. -IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа. -IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа. -IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах. -IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число. -IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа. -IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел. -IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа. -IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа. -IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа. -IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа. -IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень. -IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел. -IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа. -IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа. -IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа. -IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел. -IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел. -OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное. -OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное. -OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное. - +ACCRINT = НАКОПДОХОД +ACCRINTM = НАКОПДОХОДПОГАШ +AMORDEGRC = АМОРУМ +AMORLINC = АМОРУВ +COUPDAYBS = ДНЕЙКУПОНДО +COUPDAYS = ДНЕЙКУПОН +COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ +COUPNCD = ДАТАКУПОНПОСЛЕ +COUPNUM = ЧИСЛКУПОН +COUPPCD = ДАТАКУПОНДО +CUMIPMT = ОБЩПЛАТ +CUMPRINC = ОБЩДОХОД +DB = ФУО +DDB = ДДОБ +DISC = СКИДКА +DOLLARDE = РУБЛЬ.ДЕС +DOLLARFR = РУБЛЬ.ДРОБЬ +DURATION = ДЛИТ +EFFECT = ЭФФЕКТ +FV = БС +FVSCHEDULE = БЗРАСПИС +INTRATE = ИНОРМА +IPMT = ПРПЛТ +IRR = ВСД +ISPMT = ПРОЦПЛАТ +MDURATION = МДЛИТ +MIRR = МВСД +NOMINAL = НОМИНАЛ +NPER = КПЕР +NPV = ЧПС +ODDFPRICE = ЦЕНАПЕРВНЕРЕГ +ODDFYIELD = ДОХОДПЕРВНЕРЕГ +ODDLPRICE = ЦЕНАПОСЛНЕРЕГ +ODDLYIELD = ДОХОДПОСЛНЕРЕГ +PDURATION = ПДЛИТ +PMT = ПЛТ +PPMT = ОСПЛТ +PRICE = ЦЕНА +PRICEDISC = ЦЕНАСКИДКА +PRICEMAT = ЦЕНАПОГАШ +PV = ПС +RATE = СТАВКА +RECEIVED = ПОЛУЧЕНО +RRI = ЭКВ.СТАВКА +SLN = АПЛ +SYD = АСЧ +TBILLEQ = РАВНОКЧЕК +TBILLPRICE = ЦЕНАКЧЕК +TBILLYIELD = ДОХОДКЧЕК +USDOLLAR = ДОЛЛСША +VDB = ПУО +XIRR = ЧИСТВНДОХ +XNPV = ЧИСТНЗ +YIELD = ДОХОД +YIELDDISC = ДОХОДСКИДКА +YIELDMAT = ДОХОДПОГАШ ## -## Financial functions Финансовые функции +## Информационные функции (Information Functions) ## -ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов. -ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения. -AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации. -AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода. -COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения. -COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения. -COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона. -COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения. -COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу. -COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения. -CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами. -CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами. -DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка. -DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод. -DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг. -DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом. -DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби. -DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам. -EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки. -FV = БС ## Возвращает будущую стоимость инвестиции. -FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов. -INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг. -IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период. -IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств. -ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции. -MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей. -MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки. -NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку. -NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада. -NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования. -ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом. -ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом. -ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом. -ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом. -PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета. -PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период. -PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов. -PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка. -PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения. -PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции. -RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период. -RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг. -SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период. -SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел. -TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку. -TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека. -TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку. -VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса. -XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер. -XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими. -YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов. -YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки). -YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения. - +CELL = ЯЧЕЙКА +ERROR.TYPE = ТИП.ОШИБКИ +INFO = ИНФОРМ +ISBLANK = ЕПУСТО +ISERR = ЕОШ +ISERROR = ЕОШИБКА +ISEVEN = ЕЧЁТН +ISFORMULA = ЕФОРМУЛА +ISLOGICAL = ЕЛОГИЧ +ISNA = ЕНД +ISNONTEXT = ЕНЕТЕКСТ +ISNUMBER = ЕЧИСЛО +ISODD = ЕНЕЧЁТ +ISREF = ЕССЫЛКА +ISTEXT = ЕТЕКСТ +N = Ч +NA = НД +SHEET = ЛИСТ +SHEETS = ЛИСТЫ +TYPE = ТИП ## -## Information functions Информационные функции +## Логические функции (Logical Functions) ## -CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки. -ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки. -INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде. -ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку. -ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д. -ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки. -ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом. -ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение. -ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д. -ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом. -ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число. -ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом. -ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой. -ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом. -N = Ч ## Возвращает значение, преобразованное в число. -NA = НД ## Возвращает значение ошибки #Н/Д. -TYPE = ТИП ## Возвращает число, обозначающее тип данных значения. - +AND = И +FALSE = ЛОЖЬ +IF = ЕСЛИ +IFERROR = ЕСЛИОШИБКА +IFNA = ЕСНД +IFS = УСЛОВИЯ +NOT = НЕ +OR = ИЛИ +SWITCH = ПЕРЕКЛЮЧ +TRUE = ИСТИНА +XOR = ИСКЛИЛИ ## -## Logical functions Логические функции +## Функции ссылки и поиска (Lookup & Reference Functions) ## -AND = И ## Renvoie VRAI si tous ses arguments sont VRAI. -FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ. -IF = ЕСЛИ ## Выполняет проверку условия. -IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления. -NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное. -OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА. -TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА. - +ADDRESS = АДРЕС +AREAS = ОБЛАСТИ +CHOOSE = ВЫБОР +COLUMN = СТОЛБЕЦ +COLUMNS = ЧИСЛСТОЛБ +FILTER = ФИЛЬТР +FORMULATEXT = Ф.ТЕКСТ +GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ +HLOOKUP = ГПР +HYPERLINK = ГИПЕРССЫЛКА +INDEX = ИНДЕКС +INDIRECT = ДВССЫЛ +LOOKUP = ПРОСМОТР +MATCH = ПОИСКПОЗ +OFFSET = СМЕЩ +ROW = СТРОКА +ROWS = ЧСТРОК +RTD = ДРВ +SORT = СОРТ +SORTBY = СОРТПО +TRANSPOSE = ТРАНСП +UNIQUE = УНИК +VLOOKUP = ВПР +XLOOKUP = ПРОСМОТРX +XMATCH = ПОИСКПОЗX ## -## Lookup and reference functions Функции ссылки и поиска +## Математические и тригонометрические функции (Math & Trig Functions) ## -ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста. -AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке. -CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу. -COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка. -COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке. -HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки -HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете. -INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива. -INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением. -LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве. -MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве. -OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки. -ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой. -ROWS = ЧСТРОК ## Возвращает количество строк в ссылке. -RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).). -TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив. -VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце. - +ABS = ABS +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = АГРЕГАТ +ARABIC = АРАБСКОЕ +ASIN = ASIN +ASINH = ASINH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = ОСНОВАНИЕ +CEILING.MATH = ОКРВВЕРХ.МАТ +CEILING.PRECISE = ОКРВВЕРХ.ТОЧН +COMBIN = ЧИСЛКОМБ +COMBINA = ЧИСЛКОМБА +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = ДЕС +DEGREES = ГРАДУСЫ +ECMA.CEILING = ECMA.ОКРВВЕРХ +EVEN = ЧЁТН +EXP = EXP +FACT = ФАКТР +FACTDOUBLE = ДВФАКТР +FLOOR.MATH = ОКРВНИЗ.МАТ +FLOOR.PRECISE = ОКРВНИЗ.ТОЧН +GCD = НОД +INT = ЦЕЛОЕ +ISO.CEILING = ISO.ОКРВВЕРХ +LCM = НОК +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = МОПРЕД +MINVERSE = МОБР +MMULT = МУМНОЖ +MOD = ОСТАТ +MROUND = ОКРУГЛТ +MULTINOMIAL = МУЛЬТИНОМ +MUNIT = МЕДИН +ODD = НЕЧЁТ +PI = ПИ +POWER = СТЕПЕНЬ +PRODUCT = ПРОИЗВЕД +QUOTIENT = ЧАСТНОЕ +RADIANS = РАДИАНЫ +RAND = СЛЧИС +RANDARRAY = СЛУЧМАССИВ +RANDBETWEEN = СЛУЧМЕЖДУ +ROMAN = РИМСКОЕ +ROUND = ОКРУГЛ +ROUNDBAHTDOWN = ОКРУГЛБАТВНИЗ +ROUNDBAHTUP = ОКРУГЛБАТВВЕРХ +ROUNDDOWN = ОКРУГЛВНИЗ +ROUNDUP = ОКРУГЛВВЕРХ +SEC = SEC +SECH = SECH +SERIESSUM = РЯД.СУММ +SEQUENCE = ПОСЛЕДОВ +SIGN = ЗНАК +SIN = SIN +SINH = SINH +SQRT = КОРЕНЬ +SQRTPI = КОРЕНЬПИ +SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ +SUM = СУММ +SUMIF = СУММЕСЛИ +SUMIFS = СУММЕСЛИМН +SUMPRODUCT = СУММПРОИЗВ +SUMSQ = СУММКВ +SUMX2MY2 = СУММРАЗНКВ +SUMX2PY2 = СУММСУММКВ +SUMXMY2 = СУММКВРАЗН +TAN = TAN +TANH = TANH +TRUNC = ОТБР ## -## Math and trigonometry functions Математические и тригонометрические функции +## Статистические функции (Statistical Functions) ## -ABS = ABS ## Возвращает модуль (абсолютную величину) числа. -ACOS = ACOS ## Возвращает арккосинус числа. -ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа. -ASIN = ASIN ## Возвращает арксинус числа. -ASINH = ASINH ## Возвращает гиперболический арксинус числа. -ATAN = ATAN ## Возвращает арктангенс числа. -ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y. -ATANH = ATANH ## Возвращает гиперболический арктангенс числа. -CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению. -COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов. -COS = COS ## Возвращает косинус числа. -COSH = COSH ## Возвращает гиперболический косинус числа. -DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы. -EVEN = ЧЁТН ## Округляет число до ближайшего четного целого. -EXP = EXP ## Возвращает число e, возведенное в указанную степень. -FACT = ФАКТР ## Возвращает факториал числа. -FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа. -FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. -GCD = НОД ## Возвращает наибольший общий делитель. -INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого. -LCM = НОК ## Возвращает наименьшее общее кратное. -LN = LN ## Возвращает натуральный логарифм числа. -LOG = LOG ## Возвращает логарифм числа по заданному основанию. -LOG10 = LOG10 ## Возвращает десятичный логарифм числа. -MDETERM = МОПРЕД ## Возвращает определитель матрицы массива. -MINVERSE = МОБР ## Возвращает обратную матрицу массива. -MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов. -MOD = ОСТАТ ## Возвращает остаток от деления. -MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью. -MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел. -ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого. -PI = ПИ ## Возвращает число пи. -POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень. -PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов. -QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении. -RADIANS = РАДИАНЫ ## Преобразует градусы в радианы. -RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1. -RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами. -ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста. -ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов. -ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. -ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения. -SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле. -SIGN = ЗНАК ## Возвращает знак числа. -SIN = SIN ## Возвращает синус заданного угла. -SINH = SINH ## Возвращает гиперболический синус числа. -SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня. -SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ). -SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных. -SUM = СУММ ## Суммирует аргументы. -SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию. -SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям. -SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов. -SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов. -SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах. -SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов. -SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах. -TAN = TAN ## Возвращает тангенс числа. -TANH = TANH ## Возвращает гиперболический тангенс числа. -TRUNC = ОТБР ## Отбрасывает дробную часть числа. - +AVEDEV = СРОТКЛ +AVERAGE = СРЗНАЧ +AVERAGEA = СРЗНАЧА +AVERAGEIF = СРЗНАЧЕСЛИ +AVERAGEIFS = СРЗНАЧЕСЛИМН +BETA.DIST = БЕТА.РАСП +BETA.INV = БЕТА.ОБР +BINOM.DIST = БИНОМ.РАСП +BINOM.DIST.RANGE = БИНОМ.РАСП.ДИАП +BINOM.INV = БИНОМ.ОБР +CHISQ.DIST = ХИ2.РАСП +CHISQ.DIST.RT = ХИ2.РАСП.ПХ +CHISQ.INV = ХИ2.ОБР +CHISQ.INV.RT = ХИ2.ОБР.ПХ +CHISQ.TEST = ХИ2.ТЕСТ +CONFIDENCE.NORM = ДОВЕРИТ.НОРМ +CONFIDENCE.T = ДОВЕРИТ.СТЬЮДЕНТ +CORREL = КОРРЕЛ +COUNT = СЧЁТ +COUNTA = СЧЁТЗ +COUNTBLANK = СЧИТАТЬПУСТОТЫ +COUNTIF = СЧЁТЕСЛИ +COUNTIFS = СЧЁТЕСЛИМН +COVARIANCE.P = КОВАРИАЦИЯ.Г +COVARIANCE.S = КОВАРИАЦИЯ.В +DEVSQ = КВАДРОТКЛ +EXPON.DIST = ЭКСП.РАСП +F.DIST = F.РАСП +F.DIST.RT = F.РАСП.ПХ +F.INV = F.ОБР +F.INV.RT = F.ОБР.ПХ +F.TEST = F.ТЕСТ +FISHER = ФИШЕР +FISHERINV = ФИШЕРОБР +FORECAST.ETS = ПРЕДСКАЗ.ETS +FORECAST.ETS.CONFINT = ПРЕДСКАЗ.ЕTS.ДОВИНТЕРВАЛ +FORECAST.ETS.SEASONALITY = ПРЕДСКАЗ.ETS.СЕЗОННОСТЬ +FORECAST.ETS.STAT = ПРЕДСКАЗ.ETS.СТАТ +FORECAST.LINEAR = ПРЕДСКАЗ.ЛИНЕЙН +FREQUENCY = ЧАСТОТА +GAMMA = ГАММА +GAMMA.DIST = ГАММА.РАСП +GAMMA.INV = ГАММА.ОБР +GAMMALN = ГАММАНЛОГ +GAMMALN.PRECISE = ГАММАНЛОГ.ТОЧН +GAUSS = ГАУСС +GEOMEAN = СРГЕОМ +GROWTH = РОСТ +HARMEAN = СРГАРМ +HYPGEOM.DIST = ГИПЕРГЕОМ.РАСП +INTERCEPT = ОТРЕЗОК +KURT = ЭКСЦЕСС +LARGE = НАИБОЛЬШИЙ +LINEST = ЛИНЕЙН +LOGEST = ЛГРФПРИБЛ +LOGNORM.DIST = ЛОГНОРМ.РАСП +LOGNORM.INV = ЛОГНОРМ.ОБР +MAX = МАКС +MAXA = МАКСА +MAXIFS = МАКСЕСЛИ +MEDIAN = МЕДИАНА +MIN = МИН +MINA = МИНА +MINIFS = МИНЕСЛИ +MODE.MULT = МОДА.НСК +MODE.SNGL = МОДА.ОДН +NEGBINOM.DIST = ОТРБИНОМ.РАСП +NORM.DIST = НОРМ.РАСП +NORM.INV = НОРМ.ОБР +NORM.S.DIST = НОРМ.СТ.РАСП +NORM.S.INV = НОРМ.СТ.ОБР +PEARSON = PEARSON +PERCENTILE.EXC = ПРОЦЕНТИЛЬ.ИСКЛ +PERCENTILE.INC = ПРОЦЕНТИЛЬ.ВКЛ +PERCENTRANK.EXC = ПРОЦЕНТРАНГ.ИСКЛ +PERCENTRANK.INC = ПРОЦЕНТРАНГ.ВКЛ +PERMUT = ПЕРЕСТ +PERMUTATIONA = ПЕРЕСТА +PHI = ФИ +POISSON.DIST = ПУАССОН.РАСП +PROB = ВЕРОЯТНОСТЬ +QUARTILE.EXC = КВАРТИЛЬ.ИСКЛ +QUARTILE.INC = КВАРТИЛЬ.ВКЛ +RANK.AVG = РАНГ.СР +RANK.EQ = РАНГ.РВ +RSQ = КВПИРСОН +SKEW = СКОС +SKEW.P = СКОС.Г +SLOPE = НАКЛОН +SMALL = НАИМЕНЬШИЙ +STANDARDIZE = НОРМАЛИЗАЦИЯ +STDEV.P = СТАНДОТКЛОН.Г +STDEV.S = СТАНДОТКЛОН.В +STDEVA = СТАНДОТКЛОНА +STDEVPA = СТАНДОТКЛОНПА +STEYX = СТОШYX +T.DIST = СТЬЮДЕНТ.РАСП +T.DIST.2T = СТЬЮДЕНТ.РАСП.2Х +T.DIST.RT = СТЬЮДЕНТ.РАСП.ПХ +T.INV = СТЬЮДЕНТ.ОБР +T.INV.2T = СТЬЮДЕНТ.ОБР.2Х +T.TEST = СТЬЮДЕНТ.ТЕСТ +TREND = ТЕНДЕНЦИЯ +TRIMMEAN = УРЕЗСРЕДНЕЕ +VAR.P = ДИСП.Г +VAR.S = ДИСП.В +VARA = ДИСПА +VARPA = ДИСПРА +WEIBULL.DIST = ВЕЙБУЛЛ.РАСП +Z.TEST = Z.ТЕСТ ## -## Statistical functions Статистические функции +## Текстовые функции (Text Functions) ## -AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего. -AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов. -AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения. -AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию. -AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям. -BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения. -BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения. -BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения. -CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат. -CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат. -CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость. -CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности. -CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных. -COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов. -COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов. -COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне -COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию -COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям. -COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений -CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию. -DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений. -EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение. -FDIST = FРАСП ## Возвращает F-распределение вероятности. -FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности. -FISHER = ФИШЕР ## Возвращает преобразование Фишера. -FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера. -FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда. -FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива. -FTEST = ФТЕСТ ## Возвращает результат F-теста. -GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение. -GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение. -GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x). -GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое. -GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом. -HARMEAN = СРГАРМ ## Возвращает среднее гармоническое. -HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение. -INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии. -KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных. -LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных. -LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда. -LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда. -LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение. -LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение. -MAX = МАКС ## Возвращает наибольшее значение в списке аргументов. -MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения. -MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел. -MIN = МИН ## Возвращает наименьшее значение в списке аргументов. -MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения. -MODE = МОДА ## Возвращает значение моды множества данных. -NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение. -NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения. -NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение. -NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение. -NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения. -PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона. -PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона. -PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных. -PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов. -POISSON = ПУАССОН ## Возвращает распределение Пуассона. -PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов. -QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных. -RANK = РАНГ ## Возвращает ранг числа в списке чисел. -RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона. -SKEW = СКОС ## Возвращает асимметрию распределения. -SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии. -SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных. -STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение. -STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке. -STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения. -STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности. -STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения. -STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии. -TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента. -TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента. -TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом. -TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных. -TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента. -VAR = ДИСП ## Оценивает дисперсию по выборке. -VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения. -VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности. -VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения. -WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла. -ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста. +ARRAYTOTEXT = МАССИВВТЕКСТ +BAHTTEXT = БАТТЕКСТ +CHAR = СИМВОЛ +CLEAN = ПЕЧСИМВ +CODE = КОДСИМВ +CONCAT = СЦЕП +DBCS = БДЦС +DOLLAR = РУБЛЬ +EXACT = СОВПАД +FIND = НАЙТИ +FINDB = НАЙТИБ +FIXED = ФИКСИРОВАННЫЙ +ISTHAIDIGIT = ЕТАЙЦИФРЫ +LEFT = ЛЕВСИМВ +LEFTB = ЛЕВБ +LEN = ДЛСТР +LENB = ДЛИНБ +LOWER = СТРОЧН +MID = ПСТР +MIDB = ПСТРБ +NUMBERSTRING = СТРОКАЧИСЕЛ +NUMBERVALUE = ЧЗНАЧ +PROPER = ПРОПНАЧ +REPLACE = ЗАМЕНИТЬ +REPLACEB = ЗАМЕНИТЬБ +REPT = ПОВТОР +RIGHT = ПРАВСИМВ +RIGHTB = ПРАВБ +SEARCH = ПОИСК +SEARCHB = ПОИСКБ +SUBSTITUTE = ПОДСТАВИТЬ +T = Т +TEXT = ТЕКСТ +TEXTJOIN = ОБЪЕДИНИТЬ +THAIDIGIT = ТАЙЦИФРА +THAINUMSOUND = ТАЙЧИСЛОВЗВУК +THAINUMSTRING = ТАЙЧИСЛОВСТРОКУ +THAISTRINGLENGTH = ТАЙДЛИНАСТРОКИ +TRIM = СЖПРОБЕЛЫ +UNICHAR = ЮНИСИМВ +UNICODE = UNICODE +UPPER = ПРОПИСН +VALUE = ЗНАЧЕН +VALUETOTEXT = ЗНАЧЕНИЕВТЕКСТ +## +## Веб-функции (Web Functions) +## +ENCODEURL = КОДИР.URL +FILTERXML = ФИЛЬТР.XML +WEBSERVICE = ВЕБСЛУЖБА ## -## Text functions Текстовые функции +## Функции совместимости (Compatibility Functions) ## -ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые). -BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ). -CHAR = СИМВОЛ ## Возвращает знак с заданным кодом. -CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста. -CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке. -CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один. -DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат. -EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений. -FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). -FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). -FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков. -JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые). -LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения. -LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения. -LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке. -LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке. -LOWER = СТРОЧН ## Преобразует все буквы текста в строчные. -MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. -MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. -PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки. -PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную. -REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте. -REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте. -REPT = ПОВТОР ## Повторяет текст заданное число раз. -RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки. -RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки. -SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра). -SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра). -SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым. -T = Т ## Преобразует аргументы в текст. -TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст. -TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы. -UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные. -VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число. +BETADIST = БЕТАРАСП +BETAINV = БЕТАОБР +BINOMDIST = БИНОМРАСП +CEILING = ОКРВВЕРХ +CHIDIST = ХИ2РАСП +CHIINV = ХИ2ОБР +CHITEST = ХИ2ТЕСТ +CONCATENATE = СЦЕПИТЬ +CONFIDENCE = ДОВЕРИТ +COVAR = КОВАР +CRITBINOM = КРИТБИНОМ +EXPONDIST = ЭКСПРАСП +FDIST = FРАСП +FINV = FРАСПОБР +FLOOR = ОКРВНИЗ +FORECAST = ПРЕДСКАЗ +FTEST = ФТЕСТ +GAMMADIST = ГАММАРАСП +GAMMAINV = ГАММАОБР +HYPGEOMDIST = ГИПЕРГЕОМЕТ +LOGINV = ЛОГНОРМОБР +LOGNORMDIST = ЛОГНОРМРАСП +MODE = МОДА +NEGBINOMDIST = ОТРБИНОМРАСП +NORMDIST = НОРМРАСП +NORMINV = НОРМОБР +NORMSDIST = НОРМСТРАСП +NORMSINV = НОРМСТОБР +PERCENTILE = ПЕРСЕНТИЛЬ +PERCENTRANK = ПРОЦЕНТРАНГ +POISSON = ПУАССОН +QUARTILE = КВАРТИЛЬ +RANK = РАНГ +STDEV = СТАНДОТКЛОН +STDEVP = СТАНДОТКЛОНП +TDIST = СТЬЮДРАСП +TINV = СТЬЮДРАСПОБР +TTEST = ТТЕСТ +VAR = ДИСП +VARP = ДИСПР +WEIBULL = ВЕЙБУЛЛ +ZTEST = ZТЕСТ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config index bf72cc4f..c7440f71 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Svenska (Swedish) ## -## (For future use) -## -currencySymbol = kr +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #Skärning! -DIV0 = #Division/0! -VALUE = #Värdefel! -REF = #Referens! -NAME = #Namn? -NUM = #Ogiltigt! -NA = #Saknas! +NULL = #SKÄRNING! +DIV0 = #DIVISION/0! +VALUE = #VÄRDEFEL! +REF = #REFERENS! +NAME = #NAMN? +NUM = #OGILTIGT! +NA = #SAKNAS! diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions index 73b2deb5..2531b4c1 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/sv/functions @@ -1,408 +1,532 @@ +############################################################ ## -## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner +## PhpSpreadsheet - function name translations ## -GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport +## Svenska (Swedish) +## +############################################################ ## -## Cube functions Kubfunktioner +## Kubfunktioner (Cube Functions) ## -CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat. -CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben. -CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen. -CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna. -CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel. -CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning. -CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub. - +CUBEKPIMEMBER = KUBKPIMEDLEM +CUBEMEMBER = KUBMEDLEM +CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP +CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM +CUBESET = KUBUPPSÄTTNING +CUBESETCOUNT = KUBUPPSÄTTNINGANTAL +CUBEVALUE = KUBVÄRDE ## -## Database functions Databasfunktioner +## Databasfunktioner (Database Functions) ## -DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna -DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas -DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas -DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren -DMAX = DMAX ## Returnerar det största värdet från databasposterna -DMIN = DMIN ## Returnerar det minsta värdet från databasposterna -DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret -DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna -DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter -DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret -DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna -DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter - +DAVERAGE = DMEDEL +DCOUNT = DANTAL +DCOUNTA = DANTALV +DGET = DHÄMTA +DMAX = DMAX +DMIN = DMIN +DPRODUCT = DPRODUKT +DSTDEV = DSTDAV +DSTDEVP = DSTDAVP +DSUM = DSUMMA +DVAR = DVARIANS +DVARP = DVARIANSP ## -## Date and time functions Tid- och datumfunktioner +## Tid- och datumfunktioner (Date & Time Functions) ## -DATE = DATUM ## Returnerar ett serienummer för ett visst datum -DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer -DAY = DAG ## Konverterar ett serienummer till dag i månaden -DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår -EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet -EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare -HOUR = TIMME ## Konverterar ett serienummer till en timme -MINUTE = MINUT ## Konverterar ett serienummer till en minut -MONTH = MÅNAD ## Konverterar ett serienummer till en månad -NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum -NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid -SECOND = SEKUND ## Konverterar ett serienummer till en sekund -TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid -TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer -TODAY = IDAG ## Returnerar serienumret för dagens datum -WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan -WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer -WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare -YEAR = ÅR ## Konverterar ett serienummer till ett år -YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum - +DATE = DATUM +DATEVALUE = DATUMVÄRDE +DAY = DAG +DAYS = DAGAR +DAYS360 = DAGAR360 +EDATE = EDATUM +EOMONTH = SLUTMÅNAD +HOUR = TIMME +ISOWEEKNUM = ISOVECKONR +MINUTE = MINUT +MONTH = MÅNAD +NETWORKDAYS = NETTOARBETSDAGAR +NETWORKDAYS.INTL = NETTOARBETSDAGAR.INT +NOW = NU +SECOND = SEKUND +THAIDAYOFWEEK = THAIVECKODAG +THAIMONTHOFYEAR = THAIMÅNAD +THAIYEAR = THAIÅR +TIME = KLOCKSLAG +TIMEVALUE = TIDVÄRDE +TODAY = IDAG +WEEKDAY = VECKODAG +WEEKNUM = VECKONR +WORKDAY = ARBETSDAGAR +WORKDAY.INTL = ARBETSDAGAR.INT +YEAR = ÅR +YEARFRAC = ÅRDEL ## -## Engineering functions Tekniska funktioner +## Tekniska funktioner (Engineering Functions) ## -BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x) -BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x) -BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x) -BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x) -BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt -BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt -BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt -COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal -CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat -DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt -DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt -DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt -DELTA = DELTA ## Testar om två värden är lika -ERF = FELF ## Returnerar felfunktionen -ERFC = FELFK ## Returnerar den komplementära felfunktionen -GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde -HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt -HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt -HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt -IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal -IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal -IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer -IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat -IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal -IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal -IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal -IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal -IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal -IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal -IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent -IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal -IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal -IMSIN = IMSIN ## Returnerar sinus för ett komplext tal -IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal -IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal -IMSUM = IMSUM ## Returnerar summan av komplexa tal -OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt -OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt -OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN.TILL.DEC +BIN2HEX = BIN.TILL.HEX +BIN2OCT = BIN.TILL.OKT +BITAND = BITOCH +BITLSHIFT = BITVSKIFT +BITOR = BITELLER +BITRSHIFT = BITHSKIFT +BITXOR = BITXELLER +COMPLEX = KOMPLEX +CONVERT = KONVERTERA +DEC2BIN = DEC.TILL.BIN +DEC2HEX = DEC.TILL.HEX +DEC2OCT = DEC.TILL.OKT +DELTA = DELTA +ERF = FELF +ERF.PRECISE = FELF.EXAKT +ERFC = FELFK +ERFC.PRECISE = FELFK.EXAKT +GESTEP = SLSTEG +HEX2BIN = HEX.TILL.BIN +HEX2DEC = HEX.TILL.DEC +HEX2OCT = HEX.TILL.OKT +IMABS = IMABS +IMAGINARY = IMAGINÄR +IMARGUMENT = IMARGUMENT +IMCONJUGATE = IMKONJUGAT +IMCOS = IMCOS +IMCOSH = IMCOSH +IMCOT = IMCOT +IMCSC = IMCSC +IMCSCH = IMCSCH +IMDIV = IMDIV +IMEXP = IMEUPPHÖJT +IMLN = IMLN +IMLOG10 = IMLOG10 +IMLOG2 = IMLOG2 +IMPOWER = IMUPPHÖJT +IMPRODUCT = IMPRODUKT +IMREAL = IMREAL +IMSEC = IMSEK +IMSECH = IMSEKH +IMSIN = IMSIN +IMSINH = IMSINH +IMSQRT = IMROT +IMSUB = IMDIFF +IMSUM = IMSUM +IMTAN = IMTAN +OCT2BIN = OKT.TILL.BIN +OCT2DEC = OKT.TILL.DEC +OCT2HEX = OKT.TILL.HEX ## -## Financial functions Finansiella funktioner +## Finansiella funktioner (Financial Functions) ## -ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta -ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen -AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient -AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod -COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen -COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet -COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum -COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen -COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen -COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen -CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder -CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder -DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning -DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger -DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper -DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal -DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk -DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar -EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen -FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering -FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer -INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper -IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period -IRR = IR ## Returnerar internräntan för en serie betalningar -ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod -MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr -MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor -NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen -NPER = PERIODER ## Returnerar antalet perioder för en investering -NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta -ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period -ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period -ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period -ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period -PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet -PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period -PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta -PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper -PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen -PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar -RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet -RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper -SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period -SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period -TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel -TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel -TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel -VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning) -XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska -XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska -YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta -YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel -YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen - +ACCRINT = UPPLRÄNTA +ACCRINTM = UPPLOBLRÄNTA +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPDAGBB +COUPDAYS = KUPDAGB +COUPDAYSNC = KUPDAGNK +COUPNCD = KUPNKD +COUPNUM = KUPANT +COUPPCD = KUPFKD +CUMIPMT = KUMRÄNTA +CUMPRINC = KUMPRIS +DB = DB +DDB = DEGAVSKR +DISC = DISK +DOLLARDE = DECTAL +DOLLARFR = BRÅK +DURATION = LÖPTID +EFFECT = EFFRÄNTA +FV = SLUTVÄRDE +FVSCHEDULE = FÖRRÄNTNING +INTRATE = ÅRSRÄNTA +IPMT = RBETALNING +IRR = IR +ISPMT = RALÅN +MDURATION = MLÖPTID +MIRR = MODIR +NOMINAL = NOMRÄNTA +NPER = PERIODER +NPV = NETNUVÄRDE +ODDFPRICE = UDDAFPRIS +ODDFYIELD = UDDAFAVKASTNING +ODDLPRICE = UDDASPRIS +ODDLYIELD = UDDASAVKASTNING +PDURATION = PLÖPTID +PMT = BETALNING +PPMT = AMORT +PRICE = PRIS +PRICEDISC = PRISDISK +PRICEMAT = PRISFÖRF +PV = NUVÄRDE +RATE = RÄNTA +RECEIVED = BELOPP +RRI = AVKPÅINVEST +SLN = LINAVSKR +SYD = ÅRSAVSKR +TBILLEQ = SSVXEKV +TBILLPRICE = SSVXPRIS +TBILLYIELD = SSVXRÄNTA +VDB = VDEGRAVSKR +XIRR = XIRR +XNPV = XNUVÄRDE +YIELD = NOMAVK +YIELDDISC = NOMAVKDISK +YIELDMAT = NOMAVKFÖRF ## -## Information functions Informationsfunktioner +## Informationsfunktioner (Information Functions) ## -CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell -ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde -INFO = INFO ## Returnerar information om operativsystemet -ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt -ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS! -ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde -ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt -ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde -ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS! -ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text -ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal -ISODD = ÄRUDDA ## Returnerar SANT om talet är udda -ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens -ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text -N = N ## Returnerar ett värde omvandlat till ett tal -NA = SAKNAS ## Returnerar felvärdet #SAKNAS! -TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp - +CELL = CELL +ERROR.TYPE = FEL.TYP +INFO = INFO +ISBLANK = ÄRTOM +ISERR = ÄRF +ISERROR = ÄRFEL +ISEVEN = ÄRJÄMN +ISFORMULA = ÄRFORMEL +ISLOGICAL = ÄRLOGISK +ISNA = ÄRSAKNAD +ISNONTEXT = ÄREJTEXT +ISNUMBER = ÄRTAL +ISODD = ÄRUDDA +ISREF = ÄRREF +ISTEXT = ÄRTEXT +N = N +NA = SAKNAS +SHEET = BLAD +SHEETS = ANTALBLAD +TYPE = VÄRDETYP ## -## Logical functions Logiska funktioner +## Logiska funktioner (Logical Functions) ## -AND = OCH ## Returnerar SANT om alla argument är sanna -FALSE = FALSKT ## Returnerar det logiska värdet FALSKT -IF = OM ## Anger vilket logiskt test som ska utföras -IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln -NOT = ICKE ## Inverterar logiken för argumenten -OR = ELLER ## Returnerar SANT om något argument är SANT -TRUE = SANT ## Returnerar det logiska värdet SANT - +AND = OCH +FALSE = FALSKT +IF = OM +IFERROR = OMFEL +IFNA = OMSAKNAS +IFS = IFS +NOT = ICKE +OR = ELLER +SWITCH = VÄXLA +TRUE = SANT +XOR = XELLER ## -## Lookup and reference functions Sök- och referensfunktioner +## Sök- och referensfunktioner (Lookup & Reference Functions) ## -ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad -AREAS = OMRÅDEN ## Returnerar antalet områden i en referens -CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden -COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens -COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens -HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell -HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet -INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris -INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde -LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris -MATCH = PASSA ## Letar upp värden i en referens eller matris -OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens -ROW = RAD ## Returnerar radnumret för en referens -ROWS = RADER ## Returnerar antalet rader i en referens -RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).) -TRANSPOSE = TRANSPONERA ## Transponerar en matris -VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell - +ADDRESS = ADRESS +AREAS = OMRÅDEN +CHOOSE = VÄLJ +COLUMN = KOLUMN +COLUMNS = KOLUMNER +FORMULATEXT = FORMELTEXT +GETPIVOTDATA = HÄMTA.PIVOTDATA +HLOOKUP = LETAKOLUMN +HYPERLINK = HYPERLÄNK +INDEX = INDEX +INDIRECT = INDIREKT +LOOKUP = LETAUPP +MATCH = PASSA +OFFSET = FÖRSKJUTNING +ROW = RAD +ROWS = RADER +RTD = RTD +TRANSPOSE = TRANSPONERA +VLOOKUP = LETARAD ## -## Math and trigonometry functions Matematiska och trigonometriska funktioner +## Matematiska och trigonometriska funktioner (Math & Trig Functions) ## -ABS = ABS ## Returnerar absolutvärdet av ett tal -ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal -ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal -ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal -ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal -ATAN = ARCTAN ## Returnerar arcus tangens för ett tal -ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat -ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal -CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel -COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt -COS = COS ## Returnerar cosinus för ett tal -COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal -DEGREES = GRADER ## Omvandlar radianer till grader -EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal -EXP = EXP ## Returnerar e upphöjt till ett givet tal -FACT = FAKULTET ## Returnerar fakulteten för ett tal -FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal -FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll -GCD = SGD ## Returnerar den största gemensamma nämnaren -INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal -LCM = MGM ## Returnerar den minsta gemensamma multipeln -LN = LN ## Returnerar den naturliga logaritmen för ett tal -LOG = LOG ## Returnerar logaritmen för ett tal för en given bas -LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal -MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris -MINVERSE = MINVERT ## Returnerar matrisinversen av en matris -MMULT = MMULT ## Returnerar matrisprodukten av två matriser -MOD = REST ## Returnerar resten vid en division -MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel -MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal -ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal -PI = PI ## Returnerar värdet pi -POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent -PRODUCT = PRODUKT ## Multiplicerar argumenten -QUOTIENT = KVOT ## Returnerar heltalsdelen av en division -RADIANS = RADIANER ## Omvandlar grader till radianer -RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1 -RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger -ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text -ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror -ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll -ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll -SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln -SIGN = TECKEN ## Returnerar tecknet för ett tal -SIN = SIN ## Returnerar sinus för en given vinkel -SINH = SINH ## Returnerar hyperbolisk sinus för ett tal -SQRT = ROT ## Returnerar den positiva kvadratroten -SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi) -SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas -SUM = SUMMA ## Summerar argumenten -SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor -SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier -SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter -SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater -SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser -SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser -SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser -TAN = TAN ## Returnerar tangens för ett tal -TANH = TANH ## Returnerar hyperbolisk tangens för ett tal -TRUNC = AVKORTA ## Avkortar ett tal till ett heltal +ABS = ABS +ACOS = ARCCOS +ACOSH = ARCCOSH +ACOT = ARCCOT +ACOTH = ARCCOTH +AGGREGATE = MÄNGD +ARABIC = ARABISKA +ASIN = ARCSIN +ASINH = ARCSINH +ATAN = ARCTAN +ATAN2 = ARCTAN2 +ATANH = ARCTANH +BASE = BAS +CEILING.MATH = RUNDA.UPP.MATEMATISKT +CEILING.PRECISE = RUNDA.UPP.EXAKT +COMBIN = KOMBIN +COMBINA = KOMBINA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = DECIMAL +DEGREES = GRADER +ECMA.CEILING = ECMA.RUNDA.UPP +EVEN = JÄMN +EXP = EXP +FACT = FAKULTET +FACTDOUBLE = DUBBELFAKULTET +FLOOR.MATH = RUNDA.NER.MATEMATISKT +FLOOR.PRECISE = RUNDA.NER.EXAKT +GCD = SGD +INT = HELTAL +ISO.CEILING = ISO.RUNDA.UPP +LCM = MGM +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = MDETERM +MINVERSE = MINVERT +MMULT = MMULT +MOD = REST +MROUND = MAVRUNDA +MULTINOMIAL = MULTINOMIAL +MUNIT = MENHET +ODD = UDDA +PI = PI +POWER = UPPHÖJT.TILL +PRODUCT = PRODUKT +QUOTIENT = KVOT +RADIANS = RADIANER +RAND = SLUMP +RANDBETWEEN = SLUMP.MELLAN +ROMAN = ROMERSK +ROUND = AVRUNDA +ROUNDBAHTDOWN = AVRUNDABAHTNEDÅT +ROUNDBAHTUP = AVRUNDABAHTUPPÅT +ROUNDDOWN = AVRUNDA.NEDÅT +ROUNDUP = AVRUNDA.UPPÅT +SEC = SEK +SECH = SEKH +SERIESSUM = SERIESUMMA +SIGN = TECKEN +SIN = SIN +SINH = SINH +SQRT = ROT +SQRTPI = ROTPI +SUBTOTAL = DELSUMMA +SUM = SUMMA +SUMIF = SUMMA.OM +SUMIFS = SUMMA.OMF +SUMPRODUCT = PRODUKTSUMMA +SUMSQ = KVADRATSUMMA +SUMX2MY2 = SUMMAX2MY2 +SUMX2PY2 = SUMMAX2PY2 +SUMXMY2 = SUMMAXMY2 +TAN = TAN +TANH = TANH +TRUNC = AVKORTA +## +## Statistiska funktioner (Statistical Functions) +## +AVEDEV = MEDELAVV +AVERAGE = MEDEL +AVERAGEA = AVERAGEA +AVERAGEIF = MEDEL.OM +AVERAGEIFS = MEDEL.OMF +BETA.DIST = BETA.FÖRD +BETA.INV = BETA.INV +BINOM.DIST = BINOM.FÖRD +BINOM.DIST.RANGE = BINOM.FÖRD.INTERVALL +BINOM.INV = BINOM.INV +CHISQ.DIST = CHI2.FÖRD +CHISQ.DIST.RT = CHI2.FÖRD.RT +CHISQ.INV = CHI2.INV +CHISQ.INV.RT = CHI2.INV.RT +CHISQ.TEST = CHI2.TEST +CONFIDENCE.NORM = KONFIDENS.NORM +CONFIDENCE.T = KONFIDENS.T +CORREL = KORREL +COUNT = ANTAL +COUNTA = ANTALV +COUNTBLANK = ANTAL.TOMMA +COUNTIF = ANTAL.OM +COUNTIFS = ANTAL.OMF +COVARIANCE.P = KOVARIANS.P +COVARIANCE.S = KOVARIANS.S +DEVSQ = KVADAVV +EXPON.DIST = EXPON.FÖRD +F.DIST = F.FÖRD +F.DIST.RT = F.FÖRD.RT +F.INV = F.INV +F.INV.RT = F.INV.RT +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERINV +FORECAST.ETS = PROGNOS.ETS +FORECAST.ETS.CONFINT = PROGNOS.ETS.KONFINT +FORECAST.ETS.SEASONALITY = PROGNOS.ETS.SÄSONGSBEROENDE +FORECAST.ETS.STAT = PROGNOS.ETS.STAT +FORECAST.LINEAR = PROGNOS.LINJÄR +FREQUENCY = FREKVENS +GAMMA = GAMMA +GAMMA.DIST = GAMMA.FÖRD +GAMMA.INV = GAMMA.INV +GAMMALN = GAMMALN +GAMMALN.PRECISE = GAMMALN.EXAKT +GAUSS = GAUSS +GEOMEAN = GEOMEDEL +GROWTH = EXPTREND +HARMEAN = HARMMEDEL +HYPGEOM.DIST = HYPGEOM.FÖRD +INTERCEPT = SKÄRNINGSPUNKT +KURT = TOPPIGHET +LARGE = STÖRSTA +LINEST = REGR +LOGEST = EXPREGR +LOGNORM.DIST = LOGNORM.FÖRD +LOGNORM.INV = LOGNORM.INV +MAX = MAX +MAXA = MAXA +MAXIFS = MAXIFS +MEDIAN = MEDIAN +MIN = MIN +MINA = MINA +MINIFS = MINIFS +MODE.MULT = TYPVÄRDE.FLERA +MODE.SNGL = TYPVÄRDE.ETT +NEGBINOM.DIST = NEGBINOM.FÖRD +NORM.DIST = NORM.FÖRD +NORM.INV = NORM.INV +NORM.S.DIST = NORM.S.FÖRD +NORM.S.INV = NORM.S.INV +PEARSON = PEARSON +PERCENTILE.EXC = PERCENTIL.EXK +PERCENTILE.INC = PERCENTIL.INK +PERCENTRANK.EXC = PROCENTRANG.EXK +PERCENTRANK.INC = PROCENTRANG.INK +PERMUT = PERMUT +PERMUTATIONA = PERMUTATIONA +PHI = PHI +POISSON.DIST = POISSON.FÖRD +PROB = SANNOLIKHET +QUARTILE.EXC = KVARTIL.EXK +QUARTILE.INC = KVARTIL.INK +RANK.AVG = RANG.MED +RANK.EQ = RANG.EKV +RSQ = RKV +SKEW = SNEDHET +SKEW.P = SNEDHET.P +SLOPE = LUTNING +SMALL = MINSTA +STANDARDIZE = STANDARDISERA +STDEV.P = STDAV.P +STDEV.S = STDAV.S +STDEVA = STDEVA +STDEVPA = STDEVPA +STEYX = STDFELYX +T.DIST = T.FÖRD +T.DIST.2T = T.FÖRD.2T +T.DIST.RT = T.FÖRD.RT +T.INV = T.INV +T.INV.2T = T.INV.2T +T.TEST = T.TEST +TREND = TREND +TRIMMEAN = TRIMMEDEL +VAR.P = VARIANS.P +VAR.S = VARIANS.S +VARA = VARA +VARPA = VARPA +WEIBULL.DIST = WEIBULL.FÖRD +Z.TEST = Z.TEST ## -## Statistical functions Statistiska funktioner +## Textfunktioner (Text Functions) ## -AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde -AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten -AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden -AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium -AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor. -BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen -BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning -BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen -CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen -CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen -CHITEST = CHI2TEST ## Returnerar oberoendetesten -CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde -CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder -COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten -COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten -COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område -COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor. -COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor. -COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser -CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde -DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser -EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen -FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen -FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen -FISHER = FISHER ## Returnerar Fisher-transformationen -FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen -FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje -FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris -FTEST = FTEST ## Returnerar resultatet av en F-test -GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen -GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen -GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x) -GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet -GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend -HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet -HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen -INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje -KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data -LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data -LINEST = REGR ## Returnerar parametrar till en linjär trendlinje -LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend -LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen -LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen -MAX = MAX ## Returnerar det största värdet i en lista av argument -MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden -MEDIAN = MEDIAN ## Returnerar medianen för angivna tal -MIN = MIN ## Returnerar det minsta värdet i en lista med argument -MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden -MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd -NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen -NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen -NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen -NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen -NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen -PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt -PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område -PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd -PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt -POISSON = POISSON ## Returnerar Poisson-fördelningen -PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser -QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data -RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal -RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient -SKEW = SNEDHET ## Returnerar snedheten för en fördelning -SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje -SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data -STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde -STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval -STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden -STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen -STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden -STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen -TDIST = TFÖRD ## Returnerar Students t-fördelning -TINV = TINV ## Returnerar inversen till Students t-fördelning -TREND = TREND ## Returnerar värden längs en linjär trend -TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd -TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test -VAR = VARIANS ## Uppskattar variansen baserat på ett urval -VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden -VARP = VARIANSP ## Beräknar variansen baserat på hela populationen -VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden -WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen -ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test +BAHTTEXT = BAHTTEXT +CHAR = TECKENKOD +CLEAN = STÄDA +CODE = KOD +CONCAT = SAMMAN +DOLLAR = VALUTA +EXACT = EXAKT +FIND = HITTA +FIXED = FASTTAL +LEFT = VÄNSTER +LEN = LÄNGD +LOWER = GEMENER +MID = EXTEXT +NUMBERVALUE = TALVÄRDE +PROPER = INITIAL +REPLACE = ERSÄTT +REPT = REP +RIGHT = HÖGER +SEARCH = SÖK +SUBSTITUTE = BYT.UT +T = T +TEXT = TEXT +TEXTJOIN = TEXTJOIN +THAIDIGIT = THAISIFFRA +THAINUMSOUND = THAITALLJUD +THAINUMSTRING = THAITALSTRÄNG +THAISTRINGLENGTH = THAISTRÄNGLÄNGD +TRIM = RENSA +UNICHAR = UNITECKENKOD +UNICODE = UNICODE +UPPER = VERSALER +VALUE = TEXTNUM +## +## Webbfunktioner (Web Functions) +## +ENCODEURL = KODAWEBBADRESS +FILTERXML = FILTRERAXML +WEBSERVICE = WEBBTJÄNST ## -## Text functions Textfunktioner +## Kompatibilitetsfunktioner (Compatibility Functions) ## -ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte) -BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht) -CHAR = TECKENKOD ## Returnerar tecknet som anges av kod -CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text -CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng -CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng -DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat -EXACT = EXAKT ## Kontrollerar om två textvärden är identiska -FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler) -FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler) -FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler -JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte) -LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng -LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng -LEN = LÄNGD ## Returnerar antalet tecken i en textsträng -LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng -LOWER = GEMENER ## Omvandlar text till gemener -MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger -MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger -PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng -PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal -REPLACE = ERSÄTT ## Ersätter tecken i text -REPLACEB = ERSÄTTB ## Ersätter tecken i text -REPT = REP ## Upprepar en text ett bestämt antal gånger -RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng -RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng -SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) -SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) -SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng -T = T ## Omvandlar argumenten till text -TEXT = TEXT ## Formaterar ett tal och omvandlar det till text -TRIM = RENSA ## Tar bort blanksteg från text -UPPER = VERSALER ## Omvandlar text till versaler -VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal +BETADIST = BETAFÖRD +BETAINV = BETAINV +BINOMDIST = BINOMFÖRD +CEILING = RUNDA.UPP +CHIDIST = CHI2FÖRD +CHIINV = CHI2INV +CHITEST = CHI2TEST +CONCATENATE = SAMMANFOGA +CONFIDENCE = KONFIDENS +COVAR = KOVAR +CRITBINOM = KRITBINOM +EXPONDIST = EXPONFÖRD +FDIST = FFÖRD +FINV = FINV +FLOOR = RUNDA.NER +FORECAST = PREDIKTION +FTEST = FTEST +GAMMADIST = GAMMAFÖRD +GAMMAINV = GAMMAINV +HYPGEOMDIST = HYPGEOMFÖRD +LOGINV = LOGINV +LOGNORMDIST = LOGNORMFÖRD +MODE = TYPVÄRDE +NEGBINOMDIST = NEGBINOMFÖRD +NORMDIST = NORMFÖRD +NORMINV = NORMINV +NORMSDIST = NORMSFÖRD +NORMSINV = NORMSINV +PERCENTILE = PERCENTIL +PERCENTRANK = PROCENTRANG +POISSON = POISSON +QUARTILE = KVARTIL +RANK = RANG +STDEV = STDAV +STDEVP = STDAVP +TDIST = TFÖRD +TINV = TINV +TTEST = TTEST +VAR = VARIANS +VARP = VARIANSP +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config index 266e000f..63d22fd0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/config @@ -1,24 +1,20 @@ +############################################################ ## -## PhpSpreadsheet +## PhpSpreadsheet - locale settings ## - -ArgumentSeparator = ; - - +## Türkçe (Turkish) ## -## (For future use) -## -currencySymbol = YTL +############################################################ +ArgumentSeparator = ; ## -## Excel Error Codes (For future use) - +## Error Codes ## -NULL = #BOŞ! -DIV0 = #SAYI/0! -VALUE = #DEĞER! -REF = #BAŞV! -NAME = #AD? -NUM = #SAYI! -NA = #YOK +NULL = #BOŞ! +DIV0 = #SAYI/0! +VALUE = #DEĞER! +REF = #BAŞV! +NAME = #AD? +NUM = #SAYI! +NA = #YOK diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions index f03563a7..f872274f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/locale/tr/functions @@ -1,416 +1,537 @@ +############################################################ ## -## PhpSpreadsheet -## -## Data in this file derived from https://www.excel-function-translation.com/ +## PhpSpreadsheet - function name translations ## +## Türkçe (Turkish) ## +############################################################ ## -## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları +## Küp işlevleri (Cube Functions) ## -GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir. - +CUBEKPIMEMBER = KÜPKPIÜYESİ +CUBEMEMBER = KÜPÜYESİ +CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ +CUBERANKEDMEMBER = DERECELİKÜPÜYESİ +CUBESET = KÜPKÜMESİ +CUBESETCOUNT = KÜPKÜMESAYISI +CUBEVALUE = KÜPDEĞERİ ## -## Cube functions Küp işlevleri +## Veritabanı işlevleri (Database Functions) ## -CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir. -CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır. -CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır. -CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır. -CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar. -CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir. -CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir. - +DAVERAGE = VSEÇORT +DCOUNT = VSEÇSAY +DCOUNTA = VSEÇSAYDOLU +DGET = VAL +DMAX = VSEÇMAK +DMIN = VSEÇMİN +DPRODUCT = VSEÇÇARP +DSTDEV = VSEÇSTDSAPMA +DSTDEVP = VSEÇSTDSAPMAS +DSUM = VSEÇTOPLA +DVAR = VSEÇVAR +DVARP = VSEÇVARS ## -## Database functions Veritabanı işlevleri +## Tarih ve saat işlevleri (Date & Time Functions) ## -DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir. -DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar. -DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar. -DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır. -DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir. -DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir. -DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar. -DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder. -DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar. -DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar. -DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder. -DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar. - +DATE = TARİH +DATEDIF = ETARİHLİ +DATESTRING = TARİHDİZİ +DATEVALUE = TARİHSAYISI +DAY = GÜN +DAYS = GÜNSAY +DAYS360 = GÜN360 +EDATE = SERİTARİH +EOMONTH = SERİAY +HOUR = SAAT +ISOWEEKNUM = ISOHAFTASAY +MINUTE = DAKİKA +MONTH = AY +NETWORKDAYS = TAMİŞGÜNÜ +NETWORKDAYS.INTL = TAMİŞGÜNÜ.ULUSL +NOW = ŞİMDİ +SECOND = SANİYE +THAIDAYOFWEEK = TAYHAFTANINGÜNÜ +THAIMONTHOFYEAR = TAYYILINAYI +THAIYEAR = TAYYILI +TIME = ZAMAN +TIMEVALUE = ZAMANSAYISI +TODAY = BUGÜN +WEEKDAY = HAFTANINGÜNÜ +WEEKNUM = HAFTASAY +WORKDAY = İŞGÜNÜ +WORKDAY.INTL = İŞGÜNÜ.ULUSL +YEAR = YIL +YEARFRAC = YILORAN ## -## Date and time functions Tarih ve saat işlevleri +## Mühendislik işlevleri (Engineering Functions) ## -DATE = TARİH ## Belirli bir tarihin seri numarasını verir. -DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür. -DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür. -DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar. -EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir. -EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir. -HOUR = SAAT ## Bir seri numarasını saate dönüştürür. -MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür. -MONTH = AY ## Bir seri numarasını aya dönüştürür. -NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir. -NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir. -SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür. -TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir. -TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür. -TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür. -WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür. -WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür. -WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir. -YEAR = YIL ## Bir seri numarasını yıla dönüştürür. -YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir. - +BESSELI = BESSELI +BESSELJ = BESSELJ +BESSELK = BESSELK +BESSELY = BESSELY +BIN2DEC = BIN2DEC +BIN2HEX = BIN2HEX +BIN2OCT = BIN2OCT +BITAND = BİTVE +BITLSHIFT = BİTSOLAKAYDIR +BITOR = BİTVEYA +BITRSHIFT = BİTSAĞAKAYDIR +BITXOR = BİTÖZELVEYA +COMPLEX = KARMAŞIK +CONVERT = ÇEVİR +DEC2BIN = DEC2BIN +DEC2HEX = DEC2HEX +DEC2OCT = DEC2OCT +DELTA = DELTA +ERF = HATAİŞLEV +ERF.PRECISE = HATAİŞLEV.DUYARLI +ERFC = TÜMHATAİŞLEV +ERFC.PRECISE = TÜMHATAİŞLEV.DUYARLI +GESTEP = BESINIR +HEX2BIN = HEX2BIN +HEX2DEC = HEX2DEC +HEX2OCT = HEX2OCT +IMABS = SANMUTLAK +IMAGINARY = SANAL +IMARGUMENT = SANBAĞ_DEĞİŞKEN +IMCONJUGATE = SANEŞLENEK +IMCOS = SANCOS +IMCOSH = SANCOSH +IMCOT = SANCOT +IMCSC = SANCSC +IMCSCH = SANCSCH +IMDIV = SANBÖL +IMEXP = SANÜS +IMLN = SANLN +IMLOG10 = SANLOG10 +IMLOG2 = SANLOG2 +IMPOWER = SANKUVVET +IMPRODUCT = SANÇARP +IMREAL = SANGERÇEK +IMSEC = SANSEC +IMSECH = SANSECH +IMSIN = SANSIN +IMSINH = SANSINH +IMSQRT = SANKAREKÖK +IMSUB = SANTOPLA +IMSUM = SANÇIKAR +IMTAN = SANTAN +OCT2BIN = OCT2BIN +OCT2DEC = OCT2DEC +OCT2HEX = OCT2HEX ## -## Engineering functions Mühendislik işlevleri +## Finansal işlevler (Financial Functions) ## -BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir. -BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir. -BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir. -BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir. -BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür. -BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür. -BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür. -COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür. -CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür. -DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür. -DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür. -DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür. -DELTA = DELTA ## İki değerin eşit olup olmadığını sınar. -ERF = HATAİŞLEV ## Hata işlevini verir. -ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir. -GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar. -HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür. -HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür. -HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür. -IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir. -IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir. -IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir. -IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir. -IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir. -IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir. -IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir. -IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir. -IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir. -IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir. -IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir. -IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir. -IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir. -IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir. -IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir. -IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir. -IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir. -OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür. -OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür. -OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür. - +ACCRINT = GERÇEKFAİZ +ACCRINTM = GERÇEKFAİZV +AMORDEGRC = AMORDEGRC +AMORLINC = AMORLINC +COUPDAYBS = KUPONGÜNBD +COUPDAYS = KUPONGÜN +COUPDAYSNC = KUPONGÜNDSK +COUPNCD = KUPONGÜNSKT +COUPNUM = KUPONSAYI +COUPPCD = KUPONGÜNÖKT +CUMIPMT = TOPÖDENENFAİZ +CUMPRINC = TOPANAPARA +DB = AZALANBAKİYE +DDB = ÇİFTAZALANBAKİYE +DISC = İNDİRİM +DOLLARDE = LİRAON +DOLLARFR = LİRAKES +DURATION = SÜRE +EFFECT = ETKİN +FV = GD +FVSCHEDULE = GDPROGRAM +INTRATE = FAİZORANI +IPMT = FAİZTUTARI +IRR = İÇ_VERİM_ORANI +ISPMT = ISPMT +MDURATION = MSÜRE +MIRR = D_İÇ_VERİM_ORANI +NOMINAL = NOMİNAL +NPER = TAKSİT_SAYISI +NPV = NBD +ODDFPRICE = TEKYDEĞER +ODDFYIELD = TEKYÖDEME +ODDLPRICE = TEKSDEĞER +ODDLYIELD = TEKSÖDEME +PDURATION = PSÜRE +PMT = DEVRESEL_ÖDEME +PPMT = ANA_PARA_ÖDEMESİ +PRICE = DEĞER +PRICEDISC = DEĞERİND +PRICEMAT = DEĞERVADE +PV = BD +RATE = FAİZ_ORANI +RECEIVED = GETİRİ +RRI = GERÇEKLEŞENYATIRIMGETİRİSİ +SLN = DA +SYD = YAT +TBILLEQ = HTAHEŞ +TBILLPRICE = HTAHDEĞER +TBILLYIELD = HTAHÖDEME +VDB = DAB +XIRR = AİÇVERİMORANI +XNPV = ANBD +YIELD = ÖDEME +YIELDDISC = ÖDEMEİND +YIELDMAT = ÖDEMEVADE ## -## Financial functions Finansal fonksiyonlar +## Bilgi işlevleri (Information Functions) ## -ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir. -ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir. -AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir. -AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir. -COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir. -COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir. -COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir. -COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir. -COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir. -COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir. -CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir. -CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir. -DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir. -DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir. -DISC = İNDİRİM ## Bir tahvilin indirim oranını verir. -DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür. -DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür. -DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir. -EFFECT = ETKİN ## Efektif yıllık faiz oranını verir. -FV = ANBD ## Bir yatırımın gelecekteki değerini verir. -FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir. -INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir. -IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir. -IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir. -ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar. -MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir. -MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir. -NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir. -NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir. -NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir. -ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir. -ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir. -ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir. -ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir. -PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir. -PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir. -PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir. -PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir. -PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir. -PV = BD ## Bir yatırımın bugünkü değerini verir. -RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir. -RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir. -SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir. -SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir. -TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir. -TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir. -TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir. -VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir. -XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir. -XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir. -YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir. -YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun. -YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir. - +CELL = HÜCRE +ERROR.TYPE = HATA.TİPİ +INFO = BİLGİ +ISBLANK = EBOŞSA +ISERR = EHATA +ISERROR = EHATALIYSA +ISEVEN = ÇİFTMİ +ISFORMULA = EFORMÜLSE +ISLOGICAL = EMANTIKSALSA +ISNA = EYOKSA +ISNONTEXT = EMETİNDEĞİLSE +ISNUMBER = ESAYIYSA +ISODD = TEKMİ +ISREF = EREFSE +ISTEXT = EMETİNSE +N = S +NA = YOKSAY +SHEET = SAYFA +SHEETS = SAYFALAR +TYPE = TÜR ## -## Information functions Bilgi fonksiyonları +## Mantıksal işlevler (Logical Functions) ## -CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir. -ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir. -INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir. -ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir. -ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir. -ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir. -ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir. -ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir. -ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir. -ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir. -ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir. -ISODD = TEKTİR ## Sayı tekse, DOĞRU verir. -ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir. -ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir. -N = N ## Sayıya dönüştürülmüş bir değer verir. -NA = YOKSAY ## #YOK hata değerini verir. -TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir. - +AND = VE +FALSE = YANLIŞ +IF = EĞER +IFERROR = EĞERHATA +IFNA = EĞERYOKSA +IFS = ÇOKEĞER +NOT = DEĞİL +OR = YADA +SWITCH = İLKEŞLEŞEN +TRUE = DOĞRU +XOR = ÖZELVEYA ## -## Logical functions Mantıksal fonksiyonlar +## Arama ve başvuru işlevleri (Lookup & Reference Functions) ## -AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir. -FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir. -IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir. -IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir. -NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir. -OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir. -TRUE = DOĞRU ## DOĞRU mantıksal değerini verir. - +ADDRESS = ADRES +AREAS = ALANSAY +CHOOSE = ELEMAN +COLUMN = SÜTUN +COLUMNS = SÜTUNSAY +FORMULATEXT = FORMÜLMETNİ +GETPIVOTDATA = ÖZETVERİAL +HLOOKUP = YATAYARA +HYPERLINK = KÖPRÜ +INDEX = İNDİS +INDIRECT = DOLAYLI +LOOKUP = ARA +MATCH = KAÇINCI +OFFSET = KAYDIR +ROW = SATIR +ROWS = SATIRSAY +RTD = GZV +TRANSPOSE = DEVRİK_DÖNÜŞÜM +VLOOKUP = DÜŞEYARA ## -## Lookup and reference functions Arama ve Başvuru fonksiyonları +## Matematik ve trigonometri işlevleri (Math & Trig Functions) ## -ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir. -AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence. -CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer. -COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir. -COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir. -HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir. -HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur. -INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır. -INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir. -LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar. -MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar. -OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir. -ROW = SATIR ## Bir başvurunun satır sayısını verir. -ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir. -RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır. -TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir. -VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder. - +ABS = MUTLAK +ACOS = ACOS +ACOSH = ACOSH +ACOT = ACOT +ACOTH = ACOTH +AGGREGATE = TOPLAMA +ARABIC = ARAP +ASIN = ASİN +ASINH = ASİNH +ATAN = ATAN +ATAN2 = ATAN2 +ATANH = ATANH +BASE = TABAN +CEILING.MATH = TAVANAYUVARLA.MATEMATİK +CEILING.PRECISE = TAVANAYUVARLA.DUYARLI +COMBIN = KOMBİNASYON +COMBINA = KOMBİNASYONA +COS = COS +COSH = COSH +COT = COT +COTH = COTH +CSC = CSC +CSCH = CSCH +DECIMAL = ONDALIK +DEGREES = DERECE +ECMA.CEILING = ECMA.TAVAN +EVEN = ÇİFT +EXP = ÜS +FACT = ÇARPINIM +FACTDOUBLE = ÇİFTFAKTÖR +FLOOR.MATH = TABANAYUVARLA.MATEMATİK +FLOOR.PRECISE = TABANAYUVARLA.DUYARLI +GCD = OBEB +INT = TAMSAYI +ISO.CEILING = ISO.TAVAN +LCM = OKEK +LN = LN +LOG = LOG +LOG10 = LOG10 +MDETERM = DETERMİNANT +MINVERSE = DİZEY_TERS +MMULT = DÇARP +MOD = MOD +MROUND = KYUVARLA +MULTINOMIAL = ÇOKTERİMLİ +MUNIT = BİRİMMATRİS +ODD = TEK +PI = Pİ +POWER = KUVVET +PRODUCT = ÇARPIM +QUOTIENT = BÖLÜM +RADIANS = RADYAN +RAND = S_SAYI_ÜRET +RANDBETWEEN = RASTGELEARADA +ROMAN = ROMEN +ROUND = YUVARLA +ROUNDBAHTDOWN = BAHTAŞAĞIYUVARLA +ROUNDBAHTUP = BAHTYUKARIYUVARLA +ROUNDDOWN = AŞAĞIYUVARLA +ROUNDUP = YUKARIYUVARLA +SEC = SEC +SECH = SECH +SERIESSUM = SERİTOPLA +SIGN = İŞARET +SIN = SİN +SINH = SİNH +SQRT = KAREKÖK +SQRTPI = KAREKÖKPİ +SUBTOTAL = ALTTOPLAM +SUM = TOPLA +SUMIF = ETOPLA +SUMIFS = ÇOKETOPLA +SUMPRODUCT = TOPLA.ÇARPIM +SUMSQ = TOPKARE +SUMX2MY2 = TOPX2EY2 +SUMX2PY2 = TOPX2AY2 +SUMXMY2 = TOPXEY2 +TAN = TAN +TANH = TANH +TRUNC = NSAT ## -## Math and trigonometry functions Matematik ve trigonometri fonksiyonları +## İstatistik işlevleri (Statistical Functions) ## -ABS = MUTLAK ## Bir sayının mutlak değerini verir. -ACOS = ACOS ## Bir sayının ark kosinüsünü verir. -ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir. -ASIN = ASİN ## Bir sayının ark sinüsünü verir. -ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir. -ATAN = ATAN ## Bir sayının ark tanjantını verir. -ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir. -ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir. -CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar. -COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir. -COS = COS ## Bir sayının kosinüsünü verir. -COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir. -DEGREES = DERECE ## Radyanları dereceye dönüştürür. -EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar. -EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir. -FACT = ÇARPINIM ## Bir sayının faktörünü verir. -FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir. -FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. -GCD = OBEB ## En büyük ortak böleni verir. -INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar. -LCM = OKEK ## En küçük ortak katı verir. -LN = LN ## Bir sayının doğal logaritmasını verir. -LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir. -LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir. -MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir. -MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir. -MMULT = DÇARP ## İki dizinin dizey çarpımını verir. -MOD = MODÜLO ## Bölmeden kalanı verir. -MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir. -MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir. -ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar. -PI = Pİ ## Pi değerini verir. -POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir. -PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar. -QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir. -RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür. -RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir. -RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir. -ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir. -ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar. -ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. -ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar. -SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir. -SIGN = İŞARET ## Bir sayının işaretini verir. -SIN = SİN ## Verilen bir açının sinüsünü verir. -SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir. -SQRT = KAREKÖK ## Pozitif bir karekök verir. -SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir. -SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir. -SUM = TOPLA ## Bağımsız değişkenlerini toplar. -SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar. -SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler. -SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir. -SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir. -SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir. -SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir. -SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir. -TAN = TAN ## Bir sayının tanjantını verir. -TANH = TANH ## Bir sayının hiperbolik tanjantını verir. -TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar. - +AVEDEV = ORTSAP +AVERAGE = ORTALAMA +AVERAGEA = ORTALAMAA +AVERAGEIF = EĞERORTALAMA +AVERAGEIFS = ÇOKEĞERORTALAMA +BETA.DIST = BETA.DAĞ +BETA.INV = BETA.TERS +BINOM.DIST = BİNOM.DAĞ +BINOM.DIST.RANGE = BİNOM.DAĞ.ARALIK +BINOM.INV = BİNOM.TERS +CHISQ.DIST = KİKARE.DAĞ +CHISQ.DIST.RT = KİKARE.DAĞ.SAĞK +CHISQ.INV = KİKARE.TERS +CHISQ.INV.RT = KİKARE.TERS.SAĞK +CHISQ.TEST = KİKARE.TEST +CONFIDENCE.NORM = GÜVENİLİRLİK.NORM +CONFIDENCE.T = GÜVENİLİRLİK.T +CORREL = KORELASYON +COUNT = BAĞ_DEĞ_SAY +COUNTA = BAĞ_DEĞ_DOLU_SAY +COUNTBLANK = BOŞLUKSAY +COUNTIF = EĞERSAY +COUNTIFS = ÇOKEĞERSAY +COVARIANCE.P = KOVARYANS.P +COVARIANCE.S = KOVARYANS.S +DEVSQ = SAPKARE +EXPON.DIST = ÜSTEL.DAĞ +F.DIST = F.DAĞ +F.DIST.RT = F.DAĞ.SAĞK +F.INV = F.TERS +F.INV.RT = F.TERS.SAĞK +F.TEST = F.TEST +FISHER = FISHER +FISHERINV = FISHERTERS +FORECAST.ETS = TAHMİN.ETS +FORECAST.ETS.CONFINT = TAHMİN.ETS.GVNARAL +FORECAST.ETS.SEASONALITY = TAHMİN.ETS.MEVSİMSELLİK +FORECAST.ETS.STAT = TAHMİN.ETS.İSTAT +FORECAST.LINEAR = TAHMİN.DOĞRUSAL +FREQUENCY = SIKLIK +GAMMA = GAMA +GAMMA.DIST = GAMA.DAĞ +GAMMA.INV = GAMA.TERS +GAMMALN = GAMALN +GAMMALN.PRECISE = GAMALN.DUYARLI +GAUSS = GAUSS +GEOMEAN = GEOORT +GROWTH = BÜYÜME +HARMEAN = HARORT +HYPGEOM.DIST = HİPERGEOM.DAĞ +INTERCEPT = KESMENOKTASI +KURT = BASIKLIK +LARGE = BÜYÜK +LINEST = DOT +LOGEST = LOT +LOGNORM.DIST = LOGNORM.DAĞ +LOGNORM.INV = LOGNORM.TERS +MAX = MAK +MAXA = MAKA +MAXIFS = ÇOKEĞERMAK +MEDIAN = ORTANCA +MIN = MİN +MINA = MİNA +MINIFS = ÇOKEĞERMİN +MODE.MULT = ENÇOK_OLAN.ÇOK +MODE.SNGL = ENÇOK_OLAN.TEK +NEGBINOM.DIST = NEGBİNOM.DAĞ +NORM.DIST = NORM.DAĞ +NORM.INV = NORM.TERS +NORM.S.DIST = NORM.S.DAĞ +NORM.S.INV = NORM.S.TERS +PEARSON = PEARSON +PERCENTILE.EXC = YÜZDEBİRLİK.HRC +PERCENTILE.INC = YÜZDEBİRLİK.DHL +PERCENTRANK.EXC = YÜZDERANK.HRC +PERCENTRANK.INC = YÜZDERANK.DHL +PERMUT = PERMÜTASYON +PERMUTATIONA = PERMÜTASYONA +PHI = PHI +POISSON.DIST = POISSON.DAĞ +PROB = OLASILIK +QUARTILE.EXC = DÖRTTEBİRLİK.HRC +QUARTILE.INC = DÖRTTEBİRLİK.DHL +RANK.AVG = RANK.ORT +RANK.EQ = RANK.EŞİT +RSQ = RKARE +SKEW = ÇARPIKLIK +SKEW.P = ÇARPIKLIK.P +SLOPE = EĞİM +SMALL = KÜÇÜK +STANDARDIZE = STANDARTLAŞTIRMA +STDEV.P = STDSAPMA.P +STDEV.S = STDSAPMA.S +STDEVA = STDSAPMAA +STDEVPA = STDSAPMASA +STEYX = STHYX +T.DIST = T.DAĞ +T.DIST.2T = T.DAĞ.2K +T.DIST.RT = T.DAĞ.SAĞK +T.INV = T.TERS +T.INV.2T = T.TERS.2K +T.TEST = T.TEST +TREND = EĞİLİM +TRIMMEAN = KIRPORTALAMA +VAR.P = VAR.P +VAR.S = VAR.S +VARA = VARA +VARPA = VARSA +WEIBULL.DIST = WEIBULL.DAĞ +Z.TEST = Z.TEST ## -## Statistical functions İstatistiksel fonksiyonlar +## Metin işlevleri (Text Functions) ## -AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir. -AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir. -AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir. -AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar. -AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar. -BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir. -BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir. -BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir. -CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir. -CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir. -CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir. -CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir. -CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir. -COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar. -COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar. -COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar. -COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar. -COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar. -COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir. -CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir. -DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir. -EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir. -FDIST = FDAĞ ## F olasılık dağılımını verir. -FINV = FTERS ## F olasılık dağılımının tersini verir. -FISHER = FISHER ## Fisher dönüşümünü verir. -FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir. -FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir. -FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir. -FTEST = FTEST ## Bir F-test'in sonucunu verir. -GAMMADIST = GAMADAĞ ## Gama dağılımını verir. -GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir. -GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir. -GEOMEAN = GEOORT ## Geometrik ortayı verir. -GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir. -HARMEAN = HARORT ## Harmonik ortayı verir. -HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir. -INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir. -KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir. -LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir. -LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir. -LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir. -LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir. -LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir. -MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir. -MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir. -MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir. -MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir. -MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir. -MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir. -NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir. -NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir. -NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir. -NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir. -NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir. -PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir. -PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir. -PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir. -PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir. -POISSON = POISSON ## Poisson dağılımını verir. -PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir. -QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir. -RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir. -RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir. -SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir. -SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir. -SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir. -STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir. -STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder. -STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. -STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar. -STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. -STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir. -TDIST = TDAĞ ## T-dağılımını verir. -TINV = TTERS ## T-dağılımının tersini verir. -TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir. -TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir. -TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir. -VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder. -VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. -VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar. -VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. -WEIBULL = WEIBULL ## Weibull dağılımını hesaplar. -ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar. +BAHTTEXT = BAHTMETİN +CHAR = DAMGA +CLEAN = TEMİZ +CODE = KOD +CONCAT = ARALIKBİRLEŞTİR +DOLLAR = LİRA +EXACT = ÖZDEŞ +FIND = BUL +FIXED = SAYIDÜZENLE +ISTHAIDIGIT = TAYRAKAMIYSA +LEFT = SOLDAN +LEN = UZUNLUK +LOWER = KÜÇÜKHARF +MID = PARÇAAL +NUMBERSTRING = SAYIDİZİ +NUMBERVALUE = SAYIDEĞERİ +PHONETIC = SES +PROPER = YAZIM.DÜZENİ +REPLACE = DEĞİŞTİR +REPT = YİNELE +RIGHT = SAĞDAN +SEARCH = MBUL +SUBSTITUTE = YERİNEKOY +T = M +TEXT = METNEÇEVİR +TEXTJOIN = METİNBİRLEŞTİR +THAIDIGIT = TAYRAKAM +THAINUMSOUND = TAYSAYISES +THAINUMSTRING = TAYSAYIDİZE +THAISTRINGLENGTH = TAYDİZEUZUNLUĞU +TRIM = KIRP +UNICHAR = UNICODEKARAKTERİ +UNICODE = UNICODE +UPPER = BÜYÜKHARF +VALUE = SAYIYAÇEVİR +## +## Metin işlevleri (Web Functions) +## +ENCODEURL = URLKODLA +FILTERXML = XMLFİLTRELE +WEBSERVICE = WEBHİZMETİ ## -## Text functions Metin fonksiyonları +## Uyumluluk işlevleri (Compatibility Functions) ## -ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir. -BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür. -CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir. -CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır. -CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir. -CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir. -DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür. -EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler. -FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). -FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). -FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir. -JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir. -LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir. -LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir. -LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir. -LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir. -LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir. -MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. -MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. -PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar. -PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir. -REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir. -REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir. -REPT = YİNELE ## Metni belirtilen sayıda yineler. -RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir. -RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir. -SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). -SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). -SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar. -T = M ## Bağımsız değerlerini metne dönüştürür. -TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür. -TRIM = KIRP ## Metindeki boşlukları kaldırır. -UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir. -VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür. +BETADIST = BETADAĞ +BETAINV = BETATERS +BINOMDIST = BİNOMDAĞ +CEILING = TAVANAYUVARLA +CHIDIST = KİKAREDAĞ +CHIINV = KİKARETERS +CHITEST = KİKARETEST +CONCATENATE = BİRLEŞTİR +CONFIDENCE = GÜVENİRLİK +COVAR = KOVARYANS +CRITBINOM = KRİTİKBİNOM +EXPONDIST = ÜSTELDAĞ +FDIST = FDAĞ +FINV = FTERS +FLOOR = TABANAYUVARLA +FORECAST = TAHMİN +FTEST = FTEST +GAMMADIST = GAMADAĞ +GAMMAINV = GAMATERS +HYPGEOMDIST = HİPERGEOMDAĞ +LOGINV = LOGTERS +LOGNORMDIST = LOGNORMDAĞ +MODE = ENÇOK_OLAN +NEGBINOMDIST = NEGBİNOMDAĞ +NORMDIST = NORMDAĞ +NORMINV = NORMTERS +NORMSDIST = NORMSDAĞ +NORMSINV = NORMSTERS +PERCENTILE = YÜZDEBİRLİK +PERCENTRANK = YÜZDERANK +POISSON = POISSON +QUARTILE = DÖRTTEBİRLİK +RANK = RANK +STDEV = STDSAPMA +STDEVP = STDSAPMAS +TDIST = TDAĞ +TINV = TTERS +TTEST = TTEST +VAR = VAR +VARP = VARS +WEIBULL = WEIBULL +ZTEST = ZTEST diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php new file mode 100644 index 00000000..499d248c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/AddressHelper.php @@ -0,0 +1,153 @@ +setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - - return true; - } - - // Check for fraction + // Check for fractions if (preg_match('/^([+-]?)\s*(\d+)\s?\/\s*(\d+)$/', $value, $matches)) { - // Convert value to number - $value = $matches[2] / $matches[3]; - if ($matches[1] == '-') { - $value = 0 - $value; - } - $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode('??/??'); - - return true; + return $this->setProperFraction($matches, $cell); } elseif (preg_match('/^([+-]?)(\d*) +(\d*)\s?\/\s*(\d*)$/', $value, $matches)) { - // Convert value to number - $value = $matches[2] + ($matches[3] / $matches[4]); - if ($matches[1] == '-') { - $value = 0 - $value; - } - $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode('# ??/??'); - - return true; + return $this->setImproperFraction($matches, $cell); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $value)) { - // Convert value to number - $value = (float) str_replace('%', '', $value) / 100; - $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); - - return true; + return $this->setPercentage($value, $cell); } // Check for currency @@ -117,29 +83,12 @@ public function bindValue(Cell $cell, $value = null) // Check for time without seconds e.g. '9:45', '09:45' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { - // Convert value to number - [$h, $m] = explode(':', $value); - $days = $h / 24 + $m / 1440; - $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); - - return true; + return $this->setTimeHoursMinutes($value, $cell); } // Check for time with seconds '9:45:59', '09:45:59' if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { - // Convert value to number - [$h, $m, $s] = explode(':', $value); - $days = $h / 24 + $m / 1440 + $s / 86400; - // Convert value to number - $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); - // Set style - $cell->getWorksheet()->getStyle($cell->getCoordinate()) - ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); - - return true; + return $this->setTimeHoursMinutesSeconds($value, $cell); } // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' @@ -160,7 +109,6 @@ public function bindValue(Cell $cell, $value = null) // Check for newline character "\n" if (strpos($value, "\n") !== false) { - $value = StringHelper::sanitizeUTF8($value); $cell->setValueExplicit($value, DataType::TYPE_STRING); // Set style $cell->getWorksheet()->getStyle($cell->getCoordinate()) @@ -173,4 +121,90 @@ public function bindValue(Cell $cell, $value = null) // Not bound yet? Use parent... return parent::bindValue($cell, $value); } + + protected function setImproperFraction(array $matches, Cell $cell): bool + { + // Convert value to number + $value = $matches[2] + ($matches[3] / $matches[4]); + if ($matches[1] === '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); + + // Build the number format mask based on the size of the matched values + $dividend = str_repeat('?', strlen($matches[3])); + $divisor = str_repeat('?', strlen($matches[4])); + $fractionMask = "# {$dividend}/{$divisor}"; + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode($fractionMask); + + return true; + } + + protected function setProperFraction(array $matches, Cell $cell): bool + { + // Convert value to number + $value = $matches[2] / $matches[3]; + if ($matches[1] === '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, DataType::TYPE_NUMERIC); + + // Build the number format mask based on the size of the matched values + $dividend = str_repeat('?', strlen($matches[2])); + $divisor = str_repeat('?', strlen($matches[3])); + $fractionMask = "{$dividend}/{$divisor}"; + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode($fractionMask); + + return true; + } + + protected function setPercentage(string $value, Cell $cell): bool + { + // Convert value to number + $value = ((float) str_replace('%', '', $value)) / 100; + $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_PERCENTAGE_00); + + return true; + } + + protected function setTimeHoursMinutes(string $value, Cell $cell): bool + { + // Convert value to number + [$hours, $minutes] = explode(':', $value); + $hours = (int) $hours; + $minutes = (int) $minutes; + $days = ($hours / 24) + ($minutes / 1440); + $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME3); + + return true; + } + + protected function setTimeHoursMinutesSeconds(string $value, Cell $cell): bool + { + // Convert value to number + [$hours, $minutes, $seconds] = explode(':', $value); + $hours = (int) $hours; + $minutes = (int) $minutes; + $seconds = (int) $seconds; + $days = ($hours / 24) + ($minutes / 1440) + ($seconds / 86400); + $cell->setValueExplicit($days, DataType::TYPE_NUMERIC); + + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_TIME4); + + return true; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php index e618436e..76d5e86d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Cell.php @@ -3,12 +3,16 @@ namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use Throwable; class Cell { @@ -69,19 +73,20 @@ class Cell * * @return $this */ - public function updateInCollection() + public function updateInCollection(): self { $this->parent->update($this); return $this; } - public function detach() + public function detach(): void { + // @phpstan-ignore-next-line $this->parent = null; } - public function attach(Cells $parent) + public function attach(Cells $parent): void { $this->parent = $parent; } @@ -89,27 +94,24 @@ public function attach(Cells $parent) /** * Create a new Cell. * - * @param mixed $pValue - * @param string $pDataType - * @param Worksheet $pSheet - * - * @throws Exception + * @param mixed $value + * @param string $dataType */ - public function __construct($pValue, $pDataType, Worksheet $pSheet) + public function __construct($value, $dataType, Worksheet $worksheet) { // Initialise cell value - $this->value = $pValue; + $this->value = $value; // Set worksheet cache - $this->parent = $pSheet->getCellCollection(); + $this->parent = $worksheet->getCellCollection(); // Set datatype? - if ($pDataType !== null) { - if ($pDataType == DataType::TYPE_STRING2) { - $pDataType = DataType::TYPE_STRING; + if ($dataType !== null) { + if ($dataType == DataType::TYPE_STRING2) { + $dataType = DataType::TYPE_STRING; } - $this->dataType = $pDataType; - } elseif (!self::getValueBinder()->bindValue($this, $pValue)) { + $this->dataType = $dataType; + } elseif (!self::getValueBinder()->bindValue($this, $value)) { throw new Exception('Value could not be bound to cell.'); } } @@ -141,7 +143,16 @@ public function getRow() */ public function getCoordinate() { - return $this->parent->getCurrentCoordinate(); + try { + $coordinate = $this->parent->getCurrentCoordinate(); + } catch (Throwable $e) { + $coordinate = null; + } + if ($coordinate === null) { + throw new Exception('Coordinate no longer exists'); + } + + return $coordinate; } /** @@ -173,15 +184,13 @@ public function getFormattedValue() * * Sets the value for a cell, automatically determining the datatype using the value binder * - * @param mixed $pValue Value - * - * @throws Exception + * @param mixed $value Value * * @return $this */ - public function setValue($pValue) + public function setValue($value) { - if (!self::getValueBinder()->bindValue($this, $pValue)) { + if (!self::getValueBinder()->bindValue($this, $value)) { throw new Exception('Value could not be bound to cell.'); } @@ -191,58 +200,61 @@ public function setValue($pValue) /** * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder). * - * @param mixed $pValue Value - * @param string $pDataType Explicit data type, see DataType::TYPE_* - * - * @throws Exception + * @param mixed $value Value + * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return Cell */ - public function setValueExplicit($pValue, $pDataType) + public function setValueExplicit($value, $dataType) { // set the value according to data type - switch ($pDataType) { + switch ($dataType) { case DataType::TYPE_NULL: - $this->value = $pValue; + $this->value = $value; break; case DataType::TYPE_STRING2: - $pDataType = DataType::TYPE_STRING; + $dataType = DataType::TYPE_STRING; // no break case DataType::TYPE_STRING: // Synonym for string case DataType::TYPE_INLINE: // Rich text - $this->value = DataType::checkString($pValue); + $this->value = DataType::checkString($value); break; case DataType::TYPE_NUMERIC: - if (is_string($pValue) && !is_numeric($pValue)) { + if (is_string($value) && !is_numeric($value)) { throw new Exception('Invalid numeric value for datatype Numeric'); } - $this->value = 0 + $pValue; + $this->value = 0 + $value; break; case DataType::TYPE_FORMULA: - $this->value = (string) $pValue; + $this->value = (string) $value; break; case DataType::TYPE_BOOL: - $this->value = (bool) $pValue; + $this->value = (bool) $value; + + break; + case DataType::TYPE_ISO_DATE: + $this->value = SharedDate::convertIsoDate($value); + $dataType = DataType::TYPE_NUMERIC; break; case DataType::TYPE_ERROR: - $this->value = DataType::checkErrorCode($pValue); + $this->value = DataType::checkErrorCode($value); break; default: - throw new Exception('Invalid datatype: ' . $pDataType); + throw new Exception('Invalid datatype: ' . $dataType); break; } // set the datatype - $this->dataType = $pDataType; + $this->dataType = $dataType; return $this->updateInCollection(); } @@ -252,17 +264,19 @@ public function setValueExplicit($pValue, $pDataType) * * @param bool $resetLog Whether the calculation engine logger should be reset or not * - * @throws Exception - * * @return mixed */ public function getCalculatedValue($resetLog = true) { - if ($this->dataType == DataType::TYPE_FORMULA) { + if ($this->dataType === DataType::TYPE_FORMULA) { try { + $index = $this->getWorksheet()->getParent()->getActiveSheetIndex(); + $selected = $this->getWorksheet()->getSelectedCells(); $result = Calculation::getInstance( $this->getWorksheet()->getParent() )->calculateCellValue($this, $resetLog); + $this->getWorksheet()->setSelectedCells($selected); + $this->getWorksheet()->getParent()->setActiveSheetIndex($index); // We don't yet handle array returns if (is_array($result)) { while (is_array($result)) { @@ -272,6 +286,8 @@ public function getCalculatedValue($resetLog = true) } catch (Exception $ex) { if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { return $this->calculatedValue; // Fallback for calculations referencing external files. + } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) { + return ExcelError::NAME(); } throw new \PhpOffice\PhpSpreadsheet\Calculation\Exception( @@ -294,14 +310,14 @@ public function getCalculatedValue($resetLog = true) /** * Set old calculated value (cached). * - * @param mixed $pValue Value + * @param mixed $originalValue Value * * @return Cell */ - public function setCalculatedValue($pValue) + public function setCalculatedValue($originalValue) { - if ($pValue !== null) { - $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; + if ($originalValue !== null) { + $this->calculatedValue = (is_numeric($originalValue)) ? (float) $originalValue : $originalValue; } return $this->updateInCollection(); @@ -335,38 +351,32 @@ public function getDataType() /** * Set cell data type. * - * @param string $pDataType see DataType::TYPE_* + * @param string $dataType see DataType::TYPE_* * * @return Cell */ - public function setDataType($pDataType) + public function setDataType($dataType) { - if ($pDataType == DataType::TYPE_STRING2) { - $pDataType = DataType::TYPE_STRING; + if ($dataType == DataType::TYPE_STRING2) { + $dataType = DataType::TYPE_STRING; } - $this->dataType = $pDataType; + $this->dataType = $dataType; return $this->updateInCollection(); } /** * Identify if the cell contains a formula. - * - * @return bool */ - public function isFormula() + public function isFormula(): bool { - return $this->dataType == DataType::TYPE_FORMULA; + return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false; } /** * Does this cell contain Data validation rules? - * - * @throws Exception - * - * @return bool */ - public function hasDataValidation() + public function hasDataValidation(): bool { if (!isset($this->parent)) { throw new Exception('Cannot check for data validation when cell is not bound to a worksheet'); @@ -378,8 +388,6 @@ public function hasDataValidation() /** * Get Data validation rules. * - * @throws Exception - * * @return DataValidation */ public function getDataValidation() @@ -393,20 +401,14 @@ public function getDataValidation() /** * Set Data validation rules. - * - * @param DataValidation $pDataValidation - * - * @throws Exception - * - * @return Cell */ - public function setDataValidation(DataValidation $pDataValidation = null) + public function setDataValidation(?DataValidation $dataValidation = null): self { if (!isset($this->parent)) { throw new Exception('Cannot set data validation for cell that is not bound to a worksheet'); } - $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation); + $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation); return $this->updateInCollection(); } @@ -426,8 +428,6 @@ public function hasValidValue() /** * Does this cell contain a Hyperlink? * - * @throws Exception - * * @return bool */ public function hasHyperlink() @@ -442,8 +442,6 @@ public function hasHyperlink() /** * Get Hyperlink. * - * @throws Exception - * * @return Hyperlink */ public function getHyperlink() @@ -458,19 +456,15 @@ public function getHyperlink() /** * Set Hyperlink. * - * @param Hyperlink $pHyperlink - * - * @throws Exception - * * @return Cell */ - public function setHyperlink(Hyperlink $pHyperlink = null) + public function setHyperlink(?Hyperlink $hyperlink = null) { if (!isset($this->parent)) { throw new Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); } - $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink); + $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink); return $this->updateInCollection(); } @@ -492,7 +486,17 @@ public function getParent() */ public function getWorksheet() { - return $this->parent->getParent(); + try { + $worksheet = $this->parent->getParent(); + } catch (Throwable $e) { + $worksheet = null; + } + + if ($worksheet === null) { + throw new Exception('Worksheet no longer exists'); + } + + return $worksheet; } /** @@ -541,19 +545,33 @@ public function getMergeRange() /** * Get cell style. - * - * @return Style */ - public function getStyle() + public function getStyle(): Style { return $this->getWorksheet()->getStyle($this->getCoordinate()); } + /** + * Get cell style. + */ + public function getAppliedStyle(): Style + { + if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) { + return $this->getStyle(); + } + $range = $this->getWorksheet()->getConditionalRange($this->getCoordinate()); + if ($range === null) { + return $this->getStyle(); + } + + $matcher = new CellStyleAssessor($this, $range); + + return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate())); + } + /** * Re-bind parent. * - * @param Worksheet $parent - * * @return Cell */ public function rebindParent(Worksheet $parent) @@ -566,13 +584,13 @@ public function rebindParent(Worksheet $parent) /** * Is cell in a specific range? * - * @param string $pRange Cell range (e.g. A1:A1) + * @param string $range Cell range (e.g. A1:A1) * * @return bool */ - public function isInRange($pRange) + public function isInRange($range) { - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); // Translate properties $myColumn = Coordinate::columnIndexFromString($this->getColumn()); @@ -620,10 +638,8 @@ public static function getValueBinder() /** * Set value binder to use. - * - * @param IValueBinder $binder */ - public static function setValueBinder(IValueBinder $binder) + public static function setValueBinder(IValueBinder $binder): void { self::$valueBinder = $binder; } @@ -656,13 +672,13 @@ public function getXfIndex() /** * Set index to cellXf. * - * @param int $pValue + * @param int $indexValue * * @return Cell */ - public function setXfIndex($pValue) + public function setXfIndex($indexValue) { - $this->xfIndex = $pValue; + $this->xfIndex = $indexValue; return $this->updateInCollection(); } @@ -670,13 +686,13 @@ public function setXfIndex($pValue) /** * Set the formula attributes. * - * @param mixed $pAttributes + * @param mixed $attributes * * @return $this */ - public function setFormulaAttributes($pAttributes) + public function setFormulaAttributes($attributes) { - $this->formulaAttributes = $pAttributes; + $this->formulaAttributes = $attributes; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellAddress.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellAddress.php new file mode 100644 index 00000000..d587dcd1 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellAddress.php @@ -0,0 +1,174 @@ +cellAddress = str_replace('$', '', $cellAddress); + [$this->columnName, $rowId] = Coordinate::coordinateFromString($cellAddress); + $this->rowId = (int) $rowId; + $this->columnId = Coordinate::columnIndexFromString($this->columnName); + $this->worksheet = $worksheet; + } + + /** + * @param mixed $columnId + * @param mixed $rowId + */ + private static function validateColumnAndRow($columnId, $rowId): void + { + $array = [$columnId, $rowId]; + array_walk( + $array, + function ($value): void { + if (!is_numeric($value) || $value <= 0) { + throw new Exception('Row and Column Ids must be positive integer values'); + } + } + ); + } + + /** + * @param mixed $columnId + * @param mixed $rowId + */ + public static function fromColumnAndRow($columnId, $rowId, ?Worksheet $worksheet = null): self + { + self::validateColumnAndRow($columnId, $rowId); + + /** @phpstan-ignore-next-line */ + return new static(Coordinate::stringFromColumnIndex($columnId) . ((string) $rowId), $worksheet); + } + + public static function fromColumnRowArray(array $array, ?Worksheet $worksheet = null): self + { + [$columnId, $rowId] = $array; + + return static::fromColumnAndRow($columnId, $rowId, $worksheet); + } + + /** + * @param mixed $cellAddress + */ + public static function fromCellAddress($cellAddress, ?Worksheet $worksheet = null): self + { + /** @phpstan-ignore-next-line */ + return new static($cellAddress, $worksheet); + } + + /** + * The returned address string will contain the worksheet name as well, if available, + * (ie. if a Worksheet was provided to the constructor). + * e.g. "'Mark''s Worksheet'!C5". + */ + public function fullCellAddress(): string + { + if ($this->worksheet !== null) { + $title = str_replace("'", "''", $this->worksheet->getTitle()); + + return "'{$title}'!{$this->cellAddress}"; + } + + return $this->cellAddress; + } + + public function worksheet(): ?Worksheet + { + return $this->worksheet; + } + + /** + * The returned address string will contain just the column/row address, + * (even if a Worksheet was provided to the constructor). + * e.g. "C5". + */ + public function cellAddress(): string + { + return $this->cellAddress; + } + + public function rowId(): int + { + return $this->rowId; + } + + public function columnId(): int + { + return $this->columnId; + } + + public function columnName(): string + { + return $this->columnName; + } + + public function nextRow(int $offset = 1): self + { + $newRowId = $this->rowId + $offset; + if ($newRowId < 1) { + $newRowId = 1; + } + + return static::fromColumnAndRow($this->columnId, $newRowId); + } + + public function previousRow(int $offset = 1): self + { + return $this->nextRow(0 - $offset); + } + + public function nextColumn(int $offset = 1): self + { + $newColumnId = $this->columnId + $offset; + if ($newColumnId < 1) { + $newColumnId = 1; + } + + return static::fromColumnAndRow($newColumnId, $this->rowId); + } + + public function previousColumn(int $offset = 1): self + { + return $this->nextColumn(0 - $offset); + } + + /** + * The returned address string will contain the worksheet name as well, if available, + * (ie. if a Worksheet was provided to the constructor). + * e.g. "'Mark''s Worksheet'!C5". + */ + public function __toString() + { + return $this->fullCellAddress(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellRange.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellRange.php new file mode 100644 index 00000000..908a0d07 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/CellRange.php @@ -0,0 +1,136 @@ +validateFromTo($from, $to); + } + + private function validateFromTo(CellAddress $from, CellAddress $to): void + { + // Identify actual top-left and bottom-right values (in case we've been given top-right and bottom-left) + $firstColumn = min($from->columnId(), $to->columnId()); + $firstRow = min($from->rowId(), $to->rowId()); + $lastColumn = max($from->columnId(), $to->columnId()); + $lastRow = max($from->rowId(), $to->rowId()); + + $fromWorksheet = $from->worksheet(); + $toWorksheet = $to->worksheet(); + $this->validateWorksheets($fromWorksheet, $toWorksheet); + + $this->from = $this->cellAddressWrapper($firstColumn, $firstRow, $fromWorksheet); + $this->to = $this->cellAddressWrapper($lastColumn, $lastRow, $toWorksheet); + } + + private function validateWorksheets(?Worksheet $fromWorksheet, ?Worksheet $toWorksheet): void + { + if ($fromWorksheet !== null && $toWorksheet !== null) { + // We could simply compare worksheets rather than worksheet titles; but at some point we may introduce + // support for 3d ranges; and at that point we drop this check and let the validation fall through + // to the check for same workbook; but unless we check on titles, this test will also detect if the + // worksheets are in different spreadsheets, and the next check will never execute or throw its + // own exception. + if ($fromWorksheet->getTitle() !== $toWorksheet->getTitle()) { + throw new Exception('3d Cell Ranges are not supported'); + } elseif ($fromWorksheet->getParent() !== $toWorksheet->getParent()) { + throw new Exception('Worksheets must be in the same spreadsheet'); + } + } + } + + private function cellAddressWrapper(int $column, int $row, ?Worksheet $worksheet = null): CellAddress + { + $cellAddress = Coordinate::stringFromColumnIndex($column) . (string) $row; + + return new class ($cellAddress, $worksheet) extends CellAddress { + public function nextRow(int $offset = 1): CellAddress + { + /** @var CellAddress $result */ + $result = parent::nextRow($offset); + $this->rowId = $result->rowId; + $this->cellAddress = $result->cellAddress; + + return $this; + } + + public function previousRow(int $offset = 1): CellAddress + { + /** @var CellAddress $result */ + $result = parent::previousRow($offset); + $this->rowId = $result->rowId; + $this->cellAddress = $result->cellAddress; + + return $this; + } + + public function nextColumn(int $offset = 1): CellAddress + { + /** @var CellAddress $result */ + $result = parent::nextColumn($offset); + $this->columnId = $result->columnId; + $this->columnName = $result->columnName; + $this->cellAddress = $result->cellAddress; + + return $this; + } + + public function previousColumn(int $offset = 1): CellAddress + { + /** @var CellAddress $result */ + $result = parent::previousColumn($offset); + $this->columnId = $result->columnId; + $this->columnName = $result->columnName; + $this->cellAddress = $result->cellAddress; + + return $this; + } + }; + } + + public function from(): CellAddress + { + // Re-order from/to in case the cell addresses have been modified + $this->validateFromTo($this->from, $this->to); + + return $this->from; + } + + public function to(): CellAddress + { + // Re-order from/to in case the cell addresses have been modified + $this->validateFromTo($this->from, $this->to); + + return $this->to; + } + + public function __toString(): string + { + // Re-order from/to in case the cell addresses have been modified + $this->validateFromTo($this->from, $this->to); + + if ($this->from->cellAddress() === $this->to->cellAddress()) { + return "{$this->from->fullCellAddress()}"; + } + + $fromAddress = $this->from->fullCellAddress(); + $toAddress = $this->to->cellAddress(); + + return "{$fromAddress}:{$toAddress}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/ColumnRange.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/ColumnRange.php new file mode 100644 index 00000000..1e521a13 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/ColumnRange.php @@ -0,0 +1,125 @@ +validateFromTo( + Coordinate::columnIndexFromString($from), + Coordinate::columnIndexFromString($to ?? $from) + ); + $this->worksheet = $worksheet; + } + + public static function fromColumnIndexes(int $from, int $to, ?Worksheet $worksheet = null): self + { + return new self(Coordinate::stringFromColumnIndex($from), Coordinate::stringFromColumnIndex($to), $worksheet); + } + + /** + * @param array $array + */ + public static function fromArray(array $array, ?Worksheet $worksheet = null): self + { + array_walk( + $array, + function (&$column): void { + $column = is_numeric($column) ? Coordinate::stringFromColumnIndex((int) $column) : $column; + } + ); + /** @var string $from */ + /** @var string $to */ + [$from, $to] = $array; + + return new self($from, $to, $worksheet); + } + + private function validateFromTo(int $from, int $to): void + { + // Identify actual top and bottom values (in case we've been given bottom and top) + $this->from = min($from, $to); + $this->to = max($from, $to); + } + + public function columnCount(): int + { + return $this->to - $this->from + 1; + } + + public function shiftDown(int $offset = 1): self + { + $newFrom = $this->from + $offset; + $newFrom = ($newFrom < 1) ? 1 : $newFrom; + + $newTo = $this->to + $offset; + $newTo = ($newTo < 1) ? 1 : $newTo; + + return self::fromColumnIndexes($newFrom, $newTo, $this->worksheet); + } + + public function shiftUp(int $offset = 1): self + { + return $this->shiftDown(0 - $offset); + } + + public function from(): string + { + return Coordinate::stringFromColumnIndex($this->from); + } + + public function to(): string + { + return Coordinate::stringFromColumnIndex($this->to); + } + + public function fromIndex(): int + { + return $this->from; + } + + public function toIndex(): int + { + return $this->to; + } + + public function toCellRange(): CellRange + { + return new CellRange( + CellAddress::fromColumnAndRow($this->from, 1, $this->worksheet), + CellAddress::fromColumnAndRow($this->to, AddressRange::MAX_ROW) + ); + } + + public function __toString(): string + { + $from = $this->from(); + $to = $this->to(); + + if ($this->worksheet !== null) { + $title = str_replace("'", "''", $this->worksheet->getTitle()); + + return "'{$title}'!{$from}:{$to}"; + } + + return "{$from}:{$to}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php index cc0543f6..ea53919c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php @@ -13,6 +13,8 @@ */ abstract class Coordinate { + public const A1_COORDINATE_REGEX = '/^(?\$?)(?[A-Z]{1,3})(?\$?)(?\d{1,7})$/i'; + /** * Default range variable constant. * @@ -23,92 +25,104 @@ abstract class Coordinate /** * Coordinate from string. * - * @param string $pCoordinateString eg: 'A1' - * - * @throws Exception + * @param string $cellAddress eg: 'A1' * - * @return string[] Array containing column and row (indexes 0 and 1) + * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1) */ - public static function coordinateFromString($pCoordinateString) + public static function coordinateFromString($cellAddress) { - if (preg_match('/^([$]?[A-Z]{1,3})([$]?\\d{1,7})$/', $pCoordinateString, $matches)) { - return [$matches[1], $matches[2]]; - } elseif (self::coordinateIsRange($pCoordinateString)) { + if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) { + return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']]; + } elseif (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); - } elseif ($pCoordinateString == '') { + } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string'); } - throw new Exception('Invalid cell coordinate ' . $pCoordinateString); + throw new Exception('Invalid cell coordinate ' . $cellAddress); } /** - * Checks if a coordinate represents a range of cells. + * Get indexes from a string coordinates. * - * @param string $coord eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2' + * @param string $coordinates eg: 'A1', '$B$12' + * + * @return array{0: int, 1: int} Array containing column index and row index (indexes 0 and 1) + */ + public static function indexesFromString(string $coordinates): array + { + [$col, $row] = self::coordinateFromString($coordinates); + + return [ + self::columnIndexFromString(ltrim($col, '$')), + (int) ltrim($row, '$'), + ]; + } + + /** + * Checks if a Cell Address represents a range of cells. + * + * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2' * * @return bool Whether the coordinate represents a range of cells */ - public static function coordinateIsRange($coord) + public static function coordinateIsRange($cellAddress) { - return (strpos($coord, ':') !== false) || (strpos($coord, ',') !== false); + return (strpos($cellAddress, ':') !== false) || (strpos($cellAddress, ',') !== false); } /** * Make string row, column or cell coordinate absolute. * - * @param string $pCoordinateString e.g. 'A' or '1' or 'A1' + * @param string $cellAddress e.g. 'A' or '1' or 'A1' * Note that this value can be a row or column reference as well as a cell reference * - * @throws Exception - * * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' */ - public static function absoluteReference($pCoordinateString) + public static function absoluteReference($cellAddress) { - if (self::coordinateIsRange($pCoordinateString)) { + if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the reference - [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); + [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate - if (ctype_digit($pCoordinateString)) { - return $worksheet . '$' . $pCoordinateString; - } elseif (ctype_alpha($pCoordinateString)) { - return $worksheet . '$' . strtoupper($pCoordinateString); + $cellAddress = "$cellAddress"; + if (ctype_digit($cellAddress)) { + return $worksheet . '$' . $cellAddress; + } elseif (ctype_alpha($cellAddress)) { + return $worksheet . '$' . strtoupper($cellAddress); } - return $worksheet . self::absoluteCoordinate($pCoordinateString); + return $worksheet . self::absoluteCoordinate($cellAddress); } /** * Make string coordinate absolute. * - * @param string $pCoordinateString e.g. 'A1' - * - * @throws Exception + * @param string $cellAddress e.g. 'A1' * * @return string Absolute coordinate e.g. '$A$1' */ - public static function absoluteCoordinate($pCoordinateString) + public static function absoluteCoordinate($cellAddress) { - if (self::coordinateIsRange($pCoordinateString)) { + if (self::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells'); } // Split out any worksheet name from the coordinate - [$worksheet, $pCoordinateString] = Worksheet::extractSheetTitle($pCoordinateString, true); + [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); if ($worksheet > '') { $worksheet .= '!'; } // Create absolute coordinate - [$column, $row] = self::coordinateFromString($pCoordinateString); + [$column, $row] = self::coordinateFromString($cellAddress); $column = ltrim($column, '$'); $row = ltrim($row, '$'); @@ -118,22 +132,23 @@ public static function absoluteCoordinate($pCoordinateString) /** * Split range into coordinate strings. * - * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' + * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' * * @return array Array containing one or more arrays containing one or two coordinate strings * e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']] * or ['B4'] */ - public static function splitRange($pRange) + public static function splitRange($range) { // Ensure $pRange is a valid range - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } - $exploded = explode(',', $pRange); + $exploded = explode(',', $range); $counter = count($exploded); for ($i = 0; $i < $counter; ++$i) { + // @phpstan-ignore-next-line $exploded[$i] = explode(':', $exploded[$i]); } @@ -143,51 +158,49 @@ public static function splitRange($pRange) /** * Build range from coordinate strings. * - * @param array $pRange Array containg one or more arrays containing one or two coordinate strings - * - * @throws Exception + * @param array $range Array containing one or more arrays containing one or two coordinate strings * * @return string String representation of $pRange */ - public static function buildRange(array $pRange) + public static function buildRange(array $range) { // Verify range - if (empty($pRange) || !is_array($pRange[0])) { + if (empty($range) || !is_array($range[0])) { throw new Exception('Range does not contain any information'); } // Build range - $counter = count($pRange); + $counter = count($range); for ($i = 0; $i < $counter; ++$i) { - $pRange[$i] = implode(':', $pRange[$i]); + $range[$i] = implode(':', $range[$i]); } - return implode(',', $pRange); + return implode(',', $range); } /** * Calculate range boundaries. * - * @param string $pRange Cell range (e.g. A1:A1) + * @param string $range Cell range (e.g. A1:A1) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays (Column Number, Row Number) */ - public static function rangeBoundaries($pRange) + public static function rangeBoundaries($range) { // Ensure $pRange is a valid range - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = strtoupper($range); // Extract range - if (strpos($pRange, ':') === false) { - $rangeA = $rangeB = $pRange; + if (strpos($range, ':') === false) { + $rangeA = $rangeB = $range; } else { - [$rangeA, $rangeB] = explode(':', $pRange); + [$rangeA, $rangeB] = explode(':', $range); } // Calculate range outer borders @@ -204,14 +217,14 @@ public static function rangeBoundaries($pRange) /** * Calculate range dimension. * - * @param string $pRange Cell range (e.g. A1:A1) + * @param string $range Cell range (e.g. A1:A1) * * @return array Range dimension (width, height) */ - public static function rangeDimension($pRange) + public static function rangeDimension($range) { // Calculate range outer borders - [$rangeStart, $rangeEnd] = self::rangeBoundaries($pRange); + [$rangeStart, $rangeEnd] = self::rangeBoundaries($range); return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)]; } @@ -219,26 +232,26 @@ public static function rangeDimension($pRange) /** * Calculate range boundaries. * - * @param string $pRange Cell range (e.g. A1:A1) + * @param string $range Cell range (e.g. A1:A1) * * @return array Range coordinates [Start Cell, End Cell] * where Start Cell and End Cell are arrays [Column ID, Row Number] */ - public static function getRangeBoundaries($pRange) + public static function getRangeBoundaries($range) { // Ensure $pRange is a valid range - if (empty($pRange)) { - $pRange = self::DEFAULT_RANGE; + if (empty($range)) { + $range = self::DEFAULT_RANGE; } // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = strtoupper($range); // Extract range - if (strpos($pRange, ':') === false) { - $rangeA = $rangeB = $pRange; + if (strpos($range, ':') === false) { + $rangeA = $rangeB = $range; } else { - [$rangeA, $rangeB] = explode(':', $pRange); + [$rangeA, $rangeB] = explode(':', $range); } return [self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)]; @@ -247,19 +260,19 @@ public static function getRangeBoundaries($pRange) /** * Column index from string. * - * @param string $pString eg 'A' + * @param string $columnAddress eg 'A' * * @return int Column index (A = 1) */ - public static function columnIndexFromString($pString) + public static function columnIndexFromString($columnAddress) { // Using a lookup cache adds a slight memory overhead, but boosts speed // caching using a static within the method is faster than a class static, // though it's additional memory overhead static $indexCache = []; - if (isset($indexCache[$pString])) { - return $indexCache[$pString]; + if (isset($indexCache[$columnAddress])) { + return $indexCache[$columnAddress]; } // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant @@ -271,25 +284,25 @@ public static function columnIndexFromString($pString) '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, ]; - // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString + // We also use the language construct isset() rather than the more costly strlen() function to match the length of $columnAddress // for improved performance - if (isset($pString[0])) { - if (!isset($pString[1])) { - $indexCache[$pString] = $columnLookup[$pString]; + if (isset($columnAddress[0])) { + if (!isset($columnAddress[1])) { + $indexCache[$columnAddress] = $columnLookup[$columnAddress]; - return $indexCache[$pString]; - } elseif (!isset($pString[2])) { - $indexCache[$pString] = $columnLookup[$pString[0]] * 26 + $columnLookup[$pString[1]]; + return $indexCache[$columnAddress]; + } elseif (!isset($columnAddress[2])) { + $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26 + $columnLookup[$columnAddress[1]]; - return $indexCache[$pString]; - } elseif (!isset($pString[3])) { - $indexCache[$pString] = $columnLookup[$pString[0]] * 676 + $columnLookup[$pString[1]] * 26 + $columnLookup[$pString[2]]; + return $indexCache[$columnAddress]; + } elseif (!isset($columnAddress[3])) { + $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676 + $columnLookup[$columnAddress[1]] * 26 + $columnLookup[$columnAddress[2]]; - return $indexCache[$pString]; + return $indexCache[$columnAddress]; } } - throw new Exception('Column string index can not be ' . ((isset($pString[0])) ? 'longer than 3 characters' : 'empty')); + throw new Exception('Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty')); } /** @@ -320,32 +333,61 @@ public static function stringFromColumnIndex($columnIndex) /** * Extract all cell references in range, which may be comprised of multiple cell ranges. * - * @param string $pRange Range (e.g. A1 or A1:C10 or A1:E10 A20:E25) + * @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3' * * @return array Array containing single cell references */ - public static function extractAllCellReferencesInRange($pRange) + public static function extractAllCellReferencesInRange($cellRange): array { - $returnValue = []; + [$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange); + + $cells = []; + foreach ($ranges as $range) { + $cells[] = self::getReferencesForCellBlock($range); + } + + $cells = self::processRangeSetOperators($operators, $cells); - // Explode spaces - $cellBlocks = self::getCellBlocksFromRangeString($pRange); - foreach ($cellBlocks as $cellBlock) { - $returnValue = array_merge($returnValue, self::getReferencesForCellBlock($cellBlock)); + if (empty($cells)) { + return []; } + $cellList = array_merge(...$cells); + $cellList = self::sortCellReferenceArray($cellList); + + return $cellList; + } + + private static function processRangeSetOperators(array $operators, array $cells): array + { + $operatorCount = count($operators); + for ($offset = 0; $offset < $operatorCount; ++$offset) { + $operator = $operators[$offset]; + if ($operator !== ' ') { + continue; + } + + $cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]); + unset($operators[$offset], $cells[$offset + 1]); + $operators = array_values($operators); + $cells = array_values($cells); + --$offset; + --$operatorCount; + } + + return $cells; + } + + private static function sortCellReferenceArray(array $cellList): array + { // Sort the result by column and row $sortKeys = []; - foreach (array_unique($returnValue) as $coord) { - $column = ''; - $row = 0; - + foreach ($cellList as $coord) { sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord; } ksort($sortKeys); - // Return value return array_values($sortKeys); } @@ -416,16 +458,16 @@ private static function getReferencesForCellBlock($cellBlock) * * [ 'A1:A3' => 'x', 'A4' => 'y' ] * - * @param array $pCoordCollection associative array mapping coordinates to values + * @param array $coordinateCollection associative array mapping coordinates to values * * @return array associative array mapping coordinate ranges to valuea */ - public static function mergeRangesInCollection(array $pCoordCollection) + public static function mergeRangesInCollection(array $coordinateCollection) { $hashedValues = []; $mergedCoordCollection = []; - foreach ($pCoordCollection as $coord => $value) { + foreach ($coordinateCollection as $coord => $value) { if (self::coordinateIsRange($coord)) { $mergedCoordCollection[$coord] = $value; @@ -490,15 +532,25 @@ public static function mergeRangesInCollection(array $pCoordCollection) } /** - * Get the individual cell blocks from a range string, splitting by space and removing any $ characters. + * Get the individual cell blocks from a range string, removing any $ characters. + * then splitting by operators and returning an array with ranges and operators. * - * @param string $pRange + * @param string $rangeString * - * @return string[] + * @return array[] */ - private static function getCellBlocksFromRangeString($pRange) + private static function getCellBlocksFromRangeString($rangeString) { - return explode(' ', str_replace('$', '', strtoupper($pRange))); + $rangeString = str_replace('$', '', strtoupper($rangeString)); + + // split range sets on intersection (space) or union (,) operators + $tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE); + /** @phpstan-ignore-next-line */ + $split = array_chunk($tokens, 2); + $ranges = array_column($split, 0); + $operators = array_column($split, 1); + + return [$ranges, $operators]; } /** @@ -511,7 +563,7 @@ private static function getCellBlocksFromRangeString($pRange) * @param int $currentRow * @param int $endRow */ - private static function validateRange($cellBlock, $startColumnIndex, $endColumnIndex, $currentRow, $endRow) + private static function validateRange($cellBlock, $startColumnIndex, $endColumnIndex, $currentRow, $endRow): void { if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) { throw new Exception('Invalid range: "' . $cellBlock . '"'); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php index ba035791..0f7efe2a 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataType.php @@ -16,6 +16,7 @@ class DataType const TYPE_NULL = 'null'; const TYPE_INLINE = 'inlineStr'; const TYPE_ERROR = 'e'; + const TYPE_ISO_DATE = 'd'; /** * List of error codes. @@ -45,41 +46,41 @@ public static function getErrorCodes() /** * Check a string that it satisfies Excel requirements. * - * @param null|RichText|string $pValue Value to sanitize to an Excel string + * @param null|RichText|string $textValue Value to sanitize to an Excel string * * @return null|RichText|string Sanitized value */ - public static function checkString($pValue) + public static function checkString($textValue) { - if ($pValue instanceof RichText) { + if ($textValue instanceof RichText) { // TODO: Sanitize Rich-Text string (max. character count is 32,767) - return $pValue; + return $textValue; } // string must never be longer than 32,767 characters, truncate if necessary - $pValue = StringHelper::substring($pValue, 0, 32767); + $textValue = StringHelper::substring($textValue, 0, 32767); // we require that newline is represented as "\n" in core, not as "\r\n" or "\r" - $pValue = str_replace(["\r\n", "\r"], "\n", $pValue); + $textValue = str_replace(["\r\n", "\r"], "\n", $textValue); - return $pValue; + return $textValue; } /** * Check a value that it is a valid error code. * - * @param mixed $pValue Value to sanitize to an Excel error code + * @param mixed $value Value to sanitize to an Excel error code * * @return string Sanitized value */ - public static function checkErrorCode($pValue) + public static function checkErrorCode($value) { - $pValue = (string) $pValue; + $value = (string) $value; - if (!isset(self::$errorCodes[$pValue])) { - $pValue = '#NULL!'; + if (!isset(self::$errorCodes[$value])) { + $value = '#NULL!'; } - return $pValue; + return $value; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php index dfeb024c..7ee53eae 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidation.php @@ -140,13 +140,13 @@ public function getFormula1() /** * Set Formula 1. * - * @param string $value + * @param string $formula * * @return $this */ - public function setFormula1($value) + public function setFormula1($formula) { - $this->formula1 = $value; + $this->formula1 = $formula; return $this; } @@ -164,13 +164,13 @@ public function getFormula2() /** * Set Formula 2. * - * @param string $value + * @param string $formula * * @return $this */ - public function setFormula2($value) + public function setFormula2($formula) { - $this->formula2 = $value; + $this->formula2 = $formula; return $this; } @@ -188,13 +188,13 @@ public function getType() /** * Set Type. * - * @param string $value + * @param string $type * * @return $this */ - public function setType($value) + public function setType($type) { - $this->type = $value; + $this->type = $type; return $this; } @@ -212,13 +212,13 @@ public function getErrorStyle() /** * Set Error style. * - * @param string $value see self::STYLE_* + * @param string $errorStyle see self::STYLE_* * * @return $this */ - public function setErrorStyle($value) + public function setErrorStyle($errorStyle) { - $this->errorStyle = $value; + $this->errorStyle = $errorStyle; return $this; } @@ -236,13 +236,13 @@ public function getOperator() /** * Set Operator. * - * @param string $value + * @param string $operator * * @return $this */ - public function setOperator($value) + public function setOperator($operator) { - $this->operator = $value; + $this->operator = $operator; return $this; } @@ -260,13 +260,13 @@ public function getAllowBlank() /** * Set Allow Blank. * - * @param bool $value + * @param bool $allowBlank * * @return $this */ - public function setAllowBlank($value) + public function setAllowBlank($allowBlank) { - $this->allowBlank = $value; + $this->allowBlank = $allowBlank; return $this; } @@ -284,13 +284,13 @@ public function getShowDropDown() /** * Set Show DropDown. * - * @param bool $value + * @param bool $showDropDown * * @return $this */ - public function setShowDropDown($value) + public function setShowDropDown($showDropDown) { - $this->showDropDown = $value; + $this->showDropDown = $showDropDown; return $this; } @@ -308,13 +308,13 @@ public function getShowInputMessage() /** * Set Show InputMessage. * - * @param bool $value + * @param bool $showInputMessage * * @return $this */ - public function setShowInputMessage($value) + public function setShowInputMessage($showInputMessage) { - $this->showInputMessage = $value; + $this->showInputMessage = $showInputMessage; return $this; } @@ -332,13 +332,13 @@ public function getShowErrorMessage() /** * Set Show ErrorMessage. * - * @param bool $value + * @param bool $showErrorMessage * * @return $this */ - public function setShowErrorMessage($value) + public function setShowErrorMessage($showErrorMessage) { - $this->showErrorMessage = $value; + $this->showErrorMessage = $showErrorMessage; return $this; } @@ -356,13 +356,13 @@ public function getErrorTitle() /** * Set Error title. * - * @param string $value + * @param string $errorTitle * * @return $this */ - public function setErrorTitle($value) + public function setErrorTitle($errorTitle) { - $this->errorTitle = $value; + $this->errorTitle = $errorTitle; return $this; } @@ -380,13 +380,13 @@ public function getError() /** * Set Error. * - * @param string $value + * @param string $error * * @return $this */ - public function setError($value) + public function setError($error) { - $this->error = $value; + $this->error = $error; return $this; } @@ -404,13 +404,13 @@ public function getPromptTitle() /** * Set Prompt title. * - * @param string $value + * @param string $promptTitle * * @return $this */ - public function setPromptTitle($value) + public function setPromptTitle($promptTitle) { - $this->promptTitle = $value; + $this->promptTitle = $promptTitle; return $this; } @@ -428,13 +428,13 @@ public function getPrompt() /** * Set Prompt. * - * @param string $value + * @param string $prompt * * @return $this */ - public function setPrompt($value) + public function setPrompt($prompt) { - $this->prompt = $value; + $this->prompt = $prompt; return $this; } @@ -460,6 +460,7 @@ public function getHashCode() $this->error . $this->promptTitle . $this->prompt . + $this->sqref . __CLASS__ ); } @@ -478,4 +479,19 @@ public function __clone() } } } + + /** @var ?string */ + private $sqref; + + public function getSqref(): ?string + { + return $this->sqref; + } + + public function setSqref(?string $str): self + { + $this->sqref = $str; + + return $this; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php index 430d81b9..0e395a7f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DataValidator.php @@ -3,7 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Cell; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Exception; /** @@ -64,8 +64,11 @@ private function isValueInList(Cell $cell) try { $result = $calculation->calculateFormula($matchFormula, $cell->getCoordinate(), $cell); + while (is_array($result)) { + $result = array_pop($result); + } - return $result !== Functions::NA(); + return $result !== ExcelError::NA(); } catch (Exception $ex) { return false; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php index cd05cf8b..4f2cdf78 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/DefaultValueBinder.php @@ -14,8 +14,6 @@ class DefaultValueBinder implements IValueBinder * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell * - * @throws \PhpOffice\PhpSpreadsheet\Exception - * * @return bool */ public function bindValue(Cell $cell, $value) @@ -28,6 +26,7 @@ public function bindValue(Cell $cell, $value) if ($value instanceof DateTimeInterface) { $value = $value->format('Y-m-d H:i:s'); } elseif (!($value instanceof RichText)) { + // Attempt to cast any unexpected objects to string $value = (string) $value; } } @@ -42,37 +41,39 @@ public function bindValue(Cell $cell, $value) /** * DataType for value. * - * @param mixed $pValue + * @param mixed $value * * @return string */ - public static function dataTypeForValue($pValue) + public static function dataTypeForValue($value) { // Match the value against a few data types - if ($pValue === null) { + if ($value === null) { return DataType::TYPE_NULL; - } elseif (is_float($pValue) || is_int($pValue)) { + } elseif (is_float($value) || is_int($value)) { return DataType::TYPE_NUMERIC; - } elseif (is_bool($pValue)) { + } elseif (is_bool($value)) { return DataType::TYPE_BOOL; - } elseif ($pValue === '') { + } elseif ($value === '') { return DataType::TYPE_STRING; - } elseif ($pValue instanceof RichText) { + } elseif ($value instanceof RichText) { return DataType::TYPE_INLINE; - } elseif (is_string($pValue) && $pValue[0] === '=' && strlen($pValue) > 1) { + } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=') { return DataType::TYPE_FORMULA; - } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) { - $tValue = ltrim($pValue, '+-'); - if (is_string($pValue) && $tValue[0] === '0' && strlen($tValue) > 1 && $tValue[1] !== '.') { + } elseif (preg_match('/^[\+\-]?(\d+\\.?\d*|\d*\\.?\d+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $value)) { + $tValue = ltrim($value, '+-'); + if (is_string($value) && strlen($tValue) > 1 && $tValue[0] === '0' && $tValue[1] !== '.') { + return DataType::TYPE_STRING; + } elseif ((strpos($value, '.') === false) && ($value > PHP_INT_MAX)) { return DataType::TYPE_STRING; - } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) { + } elseif (!is_numeric($value)) { return DataType::TYPE_STRING; } return DataType::TYPE_NUMERIC; - } elseif (is_string($pValue)) { + } elseif (is_string($value)) { $errorCodes = DataType::getErrorCodes(); - if (isset($errorCodes[$pValue])) { + if (isset($errorCodes[$value])) { return DataType::TYPE_ERROR; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php index 003d5101..ffdcbacd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Hyperlink.php @@ -21,14 +21,14 @@ class Hyperlink /** * Create a new Hyperlink. * - * @param string $pUrl Url to link the cell to - * @param string $pTooltip Tooltip to display on the hyperlink + * @param string $url Url to link the cell to + * @param string $tooltip Tooltip to display on the hyperlink */ - public function __construct($pUrl = '', $pTooltip = '') + public function __construct($url = '', $tooltip = '') { // Initialise member variables - $this->url = $pUrl; - $this->tooltip = $pTooltip; + $this->url = $url; + $this->tooltip = $tooltip; } /** @@ -44,13 +44,13 @@ public function getUrl() /** * Set URL. * - * @param string $value + * @param string $url * * @return $this */ - public function setUrl($value) + public function setUrl($url) { - $this->url = $value; + $this->url = $url; return $this; } @@ -68,13 +68,13 @@ public function getTooltip() /** * Set tooltip. * - * @param string $value + * @param string $tooltip * * @return $this */ - public function setTooltip($value) + public function setTooltip($tooltip) { - $this->tooltip = $value; + $this->tooltip = $tooltip; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/RowRange.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/RowRange.php new file mode 100644 index 00000000..38e6c141 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/RowRange.php @@ -0,0 +1,93 @@ +validateFromTo($from, $to ?? $from); + $this->worksheet = $worksheet; + } + + public static function fromArray(array $array, ?Worksheet $worksheet = null): self + { + [$from, $to] = $array; + + return new self($from, $to, $worksheet); + } + + private function validateFromTo(int $from, int $to): void + { + // Identify actual top and bottom values (in case we've been given bottom and top) + $this->from = min($from, $to); + $this->to = max($from, $to); + } + + public function from(): int + { + return $this->from; + } + + public function to(): int + { + return $this->to; + } + + public function rowCount(): int + { + return $this->to - $this->from + 1; + } + + public function shiftRight(int $offset = 1): self + { + $newFrom = $this->from + $offset; + $newFrom = ($newFrom < 1) ? 1 : $newFrom; + + $newTo = $this->to + $offset; + $newTo = ($newTo < 1) ? 1 : $newTo; + + return new self($newFrom, $newTo, $this->worksheet); + } + + public function shiftLeft(int $offset = 1): self + { + return $this->shiftRight(0 - $offset); + } + + public function toCellRange(): CellRange + { + return new CellRange( + CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString('A'), $this->from, $this->worksheet), + CellAddress::fromColumnAndRow(Coordinate::columnIndexFromString(AddressRange::MAX_COLUMN), $this->to) + ); + } + + public function __toString(): string + { + if ($this->worksheet !== null) { + $title = str_replace("'", "''", $this->worksheet->getTitle()); + + return "'{$title}'!{$this->from}:{$this->to}"; + } + + return "{$this->from}:{$this->to}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php index 0552677f..d525faff 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/StringValueBinder.php @@ -2,30 +2,123 @@ namespace PhpOffice\PhpSpreadsheet\Cell; +use DateTimeInterface; +use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class StringValueBinder implements IValueBinder { + /** + * @var bool + */ + protected $convertNull = true; + + /** + * @var bool + */ + protected $convertBoolean = true; + + /** + * @var bool + */ + protected $convertNumeric = true; + + /** + * @var bool + */ + protected $convertFormula = true; + + public function setNullConversion(bool $suppressConversion = false): self + { + $this->convertNull = $suppressConversion; + + return $this; + } + + public function setBooleanConversion(bool $suppressConversion = false): self + { + $this->convertBoolean = $suppressConversion; + + return $this; + } + + public function getBooleanConversion(): bool + { + return $this->convertBoolean; + } + + public function setNumericConversion(bool $suppressConversion = false): self + { + $this->convertNumeric = $suppressConversion; + + return $this; + } + + public function setFormulaConversion(bool $suppressConversion = false): self + { + $this->convertFormula = $suppressConversion; + + return $this; + } + + public function setConversionForAllValueTypes(bool $suppressConversion = false): self + { + $this->convertNull = $suppressConversion; + $this->convertBoolean = $suppressConversion; + $this->convertNumeric = $suppressConversion; + $this->convertFormula = $suppressConversion; + + return $this; + } + /** * Bind value to a cell. * * @param Cell $cell Cell to bind value to * @param mixed $value Value to bind in cell - * - * @throws \PhpOffice\PhpSpreadsheet\Exception - * - * @return bool */ public function bindValue(Cell $cell, $value) { + if (is_object($value)) { + return $this->bindObjectValue($cell, $value); + } + // sanitize UTF-8 strings if (is_string($value)) { $value = StringHelper::sanitizeUTF8($value); } + if ($value === null && $this->convertNull === false) { + $cell->setValueExplicit($value, DataType::TYPE_NULL); + } elseif (is_bool($value) && $this->convertBoolean === false) { + $cell->setValueExplicit($value, DataType::TYPE_BOOL); + } elseif ((is_int($value) || is_float($value)) && $this->convertNumeric === false) { + $cell->setValueExplicit($value, DataType::TYPE_NUMERIC); + } elseif (is_string($value) && strlen($value) > 1 && $value[0] === '=' && $this->convertFormula === false) { + $cell->setValueExplicit($value, DataType::TYPE_FORMULA); + } else { + if (is_string($value) && strlen($value) > 1 && $value[0] === '=') { + $cell->getStyle()->setQuotePrefix(true); + } + $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); + } + + return true; + } + + protected function bindObjectValue(Cell $cell, object $value): bool + { + // Handle any objects that might be injected + if ($value instanceof DateTimeInterface) { + $value = $value->format('Y-m-d H:i:s'); + } elseif ($value instanceof RichText) { + $cell->setValueExplicit($value, DataType::TYPE_INLINE); + + return true; + } + $cell->setValueExplicit((string) $value, DataType::TYPE_STRING); - // Done! return true; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/CellReferenceHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/CellReferenceHelper.php new file mode 100644 index 00000000..0f079d69 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/CellReferenceHelper.php @@ -0,0 +1,119 @@ +beforeCellAddress = str_replace('$', '', $beforeCellAddress); + $this->numberOfColumns = $numberOfColumns; + $this->numberOfRows = $numberOfRows; + + // Get coordinate of $beforeCellAddress + [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress); + $this->beforeColumn = (int) Coordinate::columnIndexFromString($beforeColumn); + $this->beforeRow = (int) $beforeRow; + } + + public function beforeCellAddress(): string + { + return $this->beforeCellAddress; + } + + public function refreshRequired(string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): bool + { + return $this->beforeCellAddress !== $beforeCellAddress || + $this->numberOfColumns !== $numberOfColumns || + $this->numberOfRows !== $numberOfRows; + } + + public function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false): string + { + if (Coordinate::coordinateIsRange($cellReference)) { + throw new Exception('Only single cell references may be passed to this method.'); + } + + // Get coordinate of $cellReference + [$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference); + $newColumnIndex = (int) Coordinate::columnIndexFromString(str_replace('$', '', $newColumn)); + $newRowIndex = (int) str_replace('$', '', $newRow); + + $absoluteColumn = $newColumn[0] === '$' ? '$' : ''; + $absoluteRow = $newRow[0] === '$' ? '$' : ''; + // Verify which parts should be updated + if ($includeAbsoluteReferences === false) { + $updateColumn = (($absoluteColumn !== '$') && $newColumnIndex >= $this->beforeColumn); + $updateRow = (($absoluteRow !== '$') && $newRowIndex >= $this->beforeRow); + } else { + $updateColumn = ($newColumnIndex >= $this->beforeColumn); + $updateRow = ($newRowIndex >= $this->beforeRow); + } + + // Create new column reference + if ($updateColumn) { + $newColumn = ($includeAbsoluteReferences === false) + ? Coordinate::stringFromColumnIndex($newColumnIndex + $this->numberOfColumns) + : $absoluteColumn . Coordinate::stringFromColumnIndex($newColumnIndex + $this->numberOfColumns); + } + + // Create new row reference + if ($updateRow) { + $newRow = ($includeAbsoluteReferences === false) + ? $newRowIndex + $this->numberOfRows + : $absoluteRow . (string) ($newRowIndex + $this->numberOfRows); + } + + // Return new reference + return "{$newColumn}{$newRow}"; + } + + public function cellAddressInDeleteRange(string $cellAddress): bool + { + [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); + $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); + // Is cell within the range of rows/columns if we're deleting + if ( + $this->numberOfRows < 0 && + ($cellRow >= ($this->beforeRow + $this->numberOfRows)) && + ($cellRow < $this->beforeRow) + ) { + return true; + } elseif ( + $this->numberOfColumns < 0 && + ($cellColumnIndex >= ($this->beforeColumn + $this->numberOfColumns)) && + ($cellColumnIndex < $this->beforeColumn) + ) { + return true; + } + + return false; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php index 66242e34..eeed326d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Axis.php @@ -13,7 +13,7 @@ class Axis extends Properties /** * Axis Number. * - * @var array of mixed + * @var mixed[] */ private $axisNumber = [ 'format' => self::FORMAT_CODE_GENERAL, @@ -23,7 +23,7 @@ class Axis extends Properties /** * Axis Options. * - * @var array of mixed + * @var mixed[] */ private $axisOptions = [ 'minimum' => null, @@ -41,7 +41,7 @@ class Axis extends Properties /** * Fill Properties. * - * @var array of mixed + * @var mixed[] */ private $fillProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, @@ -52,7 +52,7 @@ class Axis extends Properties /** * Line Properties. * - * @var array of mixed + * @var mixed[] */ private $lineProperties = [ 'type' => self::EXCEL_COLOR_TYPE_ARGB, @@ -63,7 +63,7 @@ class Axis extends Properties /** * Line Style Properties. * - * @var array of mixed + * @var mixed[] */ private $lineStyleProperties = [ 'width' => '9525', @@ -86,7 +86,7 @@ class Axis extends Properties /** * Shadow Properties. * - * @var array of mixed + * @var mixed[] */ private $shadowProperties = [ 'presets' => self::SHADOW_PRESETS_NOSHADOW, @@ -111,7 +111,7 @@ class Axis extends Properties /** * Glow Properties. * - * @var array of mixed + * @var mixed[] */ private $glowProperties = [ 'size' => null, @@ -125,7 +125,7 @@ class Axis extends Properties /** * Soft Edge Properties. * - * @var array of mixed + * @var mixed[] */ private $softEdges = [ 'size' => null, @@ -135,10 +135,8 @@ class Axis extends Properties * Get Series Data Type. * * @param mixed $format_code - * - * @return string */ - public function setAxisNumberProperties($format_code) + public function setAxisNumberProperties($format_code): void { $this->axisNumber['format'] = (string) $format_code; $this->axisNumber['source_linked'] = 0; @@ -167,30 +165,30 @@ public function getAxisNumberSourceLinked() /** * Set Axis Options Properties. * - * @param string $axis_labels - * @param string $horizontal_crosses_value - * @param string $horizontal_crosses - * @param string $axis_orientation - * @param string $major_tmt - * @param string $minor_tmt + * @param string $axisLabels + * @param string $horizontalCrossesValue + * @param string $horizontalCrosses + * @param string $axisOrientation + * @param string $majorTmt + * @param string $minorTmt * @param string $minimum * @param string $maximum - * @param string $major_unit - * @param string $minor_unit + * @param string $majorUnit + * @param string $minorUnit */ - public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null) + public function setAxisOptionsProperties($axisLabels, $horizontalCrossesValue = null, $horizontalCrosses = null, $axisOrientation = null, $majorTmt = null, $minorTmt = null, $minimum = null, $maximum = null, $majorUnit = null, $minorUnit = null): void { - $this->axisOptions['axis_labels'] = (string) $axis_labels; - ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; - ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null; - ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null; - ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null; - ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; - ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + $this->axisOptions['axis_labels'] = (string) $axisLabels; + ($horizontalCrossesValue !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontalCrossesValue : null; + ($horizontalCrosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontalCrosses : null; + ($axisOrientation !== null) ? $this->axisOptions['orientation'] = (string) $axisOrientation : null; + ($majorTmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $majorTmt : null; + ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null; + ($minorTmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minorTmt : null; ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null; ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null; - ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null; - ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null; + ($majorUnit !== null) ? $this->axisOptions['major_unit'] = (string) $majorUnit : null; + ($minorUnit !== null) ? $this->axisOptions['minor_unit'] = (string) $minorUnit : null; } /** @@ -210,7 +208,7 @@ public function getAxisOptionsProperty($property) * * @param string $orientation */ - public function setAxisOrientation($orientation) + public function setAxisOrientation($orientation): void { $this->axisOptions['orientation'] = (string) $orientation; } @@ -220,11 +218,11 @@ public function setAxisOrientation($orientation) * * @param string $color * @param int $alpha - * @param string $type + * @param string $AlphaType */ - public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) + public function setFillParameters($color, $alpha = 0, $AlphaType = self::EXCEL_COLOR_TYPE_ARGB): void { - $this->fillProperties = $this->setColorProperties($color, $alpha, $type); + $this->fillProperties = $this->setColorProperties($color, $alpha, $AlphaType); } /** @@ -232,11 +230,11 @@ public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_ * * @param string $color * @param int $alpha - * @param string $type + * @param string $alphaType */ - public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) + public function setLineParameters($color, $alpha = 0, $alphaType = self::EXCEL_COLOR_TYPE_ARGB): void { - $this->lineProperties = $this->setColorProperties($color, $alpha, $type); + $this->lineProperties = $this->setColorProperties($color, $alpha, $alphaType); } /** @@ -266,27 +264,27 @@ public function getLineProperty($property) /** * Set Line Style Properties. * - * @param float $line_width - * @param string $compound_type - * @param string $dash_type - * @param string $cap_type - * @param string $join_type - * @param string $head_arrow_type - * @param string $head_arrow_size - * @param string $end_arrow_type - * @param string $end_arrow_size - */ - public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) + * @param float $lineWidth + * @param string $compoundType + * @param string $dashType + * @param string $capType + * @param string $joinType + * @param string $headArrowType + * @param string $headArrowSize + * @param string $endArrowType + * @param string $endArrowSize + */ + public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void { - ($line_width !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null; - ($compound_type !== null) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null; - ($dash_type !== null) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null; - ($cap_type !== null) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null; - ($join_type !== null) ? $this->lineStyleProperties['join'] = (string) $join_type : null; - ($head_arrow_type !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null; - ($head_arrow_size !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null; - ($end_arrow_type !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null; - ($end_arrow_size !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null; + ($lineWidth !== null) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null; + ($compoundType !== null) ? $this->lineStyleProperties['compound'] = (string) $compoundType : null; + ($dashType !== null) ? $this->lineStyleProperties['dash'] = (string) $dashType : null; + ($capType !== null) ? $this->lineStyleProperties['cap'] = (string) $capType : null; + ($joinType !== null) ? $this->lineStyleProperties['join'] = (string) $joinType : null; + ($headArrowType !== null) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $headArrowType : null; + ($headArrowSize !== null) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $headArrowSize : null; + ($endArrowType !== null) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $endArrowType : null; + ($endArrowSize !== null) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $endArrowSize : null; } /** @@ -328,38 +326,38 @@ public function getLineStyleArrowLength($arrow) /** * Set Shadow Properties. * - * @param int $sh_presets - * @param string $sh_color_value - * @param string $sh_color_type - * @param string $sh_color_alpha - * @param float $sh_blur - * @param int $sh_angle - * @param float $sh_distance + * @param int $shadowPresets + * @param string $colorValue + * @param string $colorType + * @param string $colorAlpha + * @param float $blur + * @param int $angle + * @param float $distance */ - public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) + public function setShadowProperties($shadowPresets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void { - $this->setShadowPresetsProperties((int) $sh_presets) + $this->setShadowPresetsProperties((int) $shadowPresets) ->setShadowColor( - $sh_color_value === null ? $this->shadowProperties['color']['value'] : $sh_color_value, - $sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $sh_color_alpha, - $sh_color_type === null ? $this->shadowProperties['color']['type'] : $sh_color_type + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha ?? (int) $this->shadowProperties['color']['alpha'], + $colorType ?? $this->shadowProperties['color']['type'] ) - ->setShadowBlur($sh_blur) - ->setShadowAngle($sh_angle) - ->setShadowDistance($sh_distance); + ->setShadowBlur($blur) + ->setShadowAngle($angle) + ->setShadowDistance($distance); } /** * Set Shadow Color. * - * @param int $shadow_presets + * @param int $presets * * @return $this */ - private function setShadowPresetsProperties($shadow_presets) + private function setShadowPresetsProperties($presets) { - $this->shadowProperties['presets'] = $shadow_presets; - $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + $this->shadowProperties['presets'] = $presets; + $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } @@ -367,22 +365,21 @@ private function setShadowPresetsProperties($shadow_presets) /** * Set Shadow Properties from Mapped Values. * - * @param array $properties_map - * @param mixed &$reference + * @param mixed $reference * * @return $this */ - private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null) { $base_reference = $reference; - foreach ($properties_map as $property_key => $property_val) { + foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { $reference = &$this->shadowProperties[$property_key]; } else { $reference = &$reference[$property_key]; } - $this->setShadowProperiesMapValues($property_val, $reference); + $this->setShadowPropertiesMapValues($property_val, $reference); } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; @@ -400,13 +397,13 @@ private function setShadowProperiesMapValues(array $properties_map, &$reference * * @param string $color * @param int $alpha - * @param string $type + * @param string $alphaType * * @return $this */ - private function setShadowColor($color, $alpha, $type) + private function setShadowColor($color, $alpha, $alphaType) { - $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $type); + $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $alphaType); return $this; } @@ -475,17 +472,17 @@ public function getShadowProperty($elements) * Set Glow Properties. * * @param float $size - * @param string $color_value - * @param int $color_alpha - * @param string $color_type + * @param string $colorValue + * @param int $colorAlpha + * @param string $colorType */ - public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) + public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void { $this->setGlowSize($size) ->setGlowColor( - $color_value === null ? $this->glowProperties['color']['value'] : $color_value, - $color_alpha === null ? (int) $this->glowProperties['color']['alpha'] : $color_alpha, - $color_type === null ? $this->glowProperties['color']['type'] : $color_type + $colorValue ?? $this->glowProperties['color']['value'], + $colorAlpha ?? (int) $this->glowProperties['color']['alpha'], + $colorType ?? $this->glowProperties['color']['type'] ); } @@ -522,13 +519,13 @@ private function setGlowSize($size) * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @return $this */ - private function setGlowColor($color, $alpha, $type) + private function setGlowColor($color, $alpha, $colorType) { - $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $type); + $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $colorType); return $this; } @@ -538,7 +535,7 @@ private function setGlowColor($color, $alpha, $type) * * @param float $size */ - public function setSoftEdges($size) + public function setSoftEdges($size): void { if ($size !== null) { $softEdges['size'] = (string) $this->getExcelPointsWidth($size); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php index 59c9ed5d..bed89464 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Chart.php @@ -68,7 +68,7 @@ class Chart * * @var string */ - private $displayBlanksAs = '0'; + private $displayBlanksAs = DataSeries::EMPTY_AS_GAP; /** * Chart Asix Y as. @@ -144,19 +144,10 @@ class Chart * Create a new Chart. * * @param mixed $name - * @param null|Title $title - * @param null|Legend $legend - * @param null|PlotArea $plotArea * @param mixed $plotVisibleOnly - * @param mixed $displayBlanksAs - * @param null|Title $xAxisLabel - * @param null|Title $yAxisLabel - * @param null|Axis $xAxis - * @param null|Axis $yAxis - * @param null|GridLines $majorGridlines - * @param null|GridLines $minorGridlines + * @param string $displayBlanksAs */ - public function __construct($name, Title $title = null, Legend $legend = null, PlotArea $plotArea = null, $plotVisibleOnly = true, $displayBlanksAs = 'gap', Title $xAxisLabel = null, Title $yAxisLabel = null, Axis $xAxis = null, Axis $yAxis = null, GridLines $majorGridlines = null, GridLines $minorGridlines = null) + public function __construct($name, ?Title $title = null, ?Legend $legend = null, ?PlotArea $plotArea = null, $plotVisibleOnly = true, $displayBlanksAs = DataSeries::EMPTY_AS_GAP, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null) { $this->name = $name; $this->title = $title; @@ -195,13 +186,11 @@ public function getWorksheet() /** * Set Worksheet. * - * @param Worksheet $pValue - * * @return $this */ - public function setWorksheet(Worksheet $pValue = null) + public function setWorksheet(?Worksheet $worksheet = null) { - $this->worksheet = $pValue; + $this->worksheet = $worksheet; return $this; } @@ -219,8 +208,6 @@ public function getTitle() /** * Set Title. * - * @param Title $title - * * @return $this */ public function setTitle(Title $title) @@ -243,8 +230,6 @@ public function getLegend() /** * Set Legend. * - * @param Legend $legend - * * @return $this */ public function setLegend(Legend $legend) @@ -267,8 +252,6 @@ public function getXAxisLabel() /** * Set X-Axis Label. * - * @param Title $label - * * @return $this */ public function setXAxisLabel(Title $label) @@ -291,8 +274,6 @@ public function getYAxisLabel() /** * Set Y-Axis Label. * - * @param Title $label - * * @return $this */ public function setYAxisLabel(Title $label) @@ -441,7 +422,7 @@ public function setTopLeftPosition($cell, $xOffset = null, $yOffset = null) /** * Get the top left position of the chart. * - * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + * @return array{cell: string, xOffset: int, yOffset: int} an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell */ public function getTopLeftPosition() { @@ -645,7 +626,7 @@ public function getBottomRightYOffset() return $this->bottomRightYOffset; } - public function refresh() + public function refresh(): void { if ($this->worksheet !== null) { $this->plotArea->refresh($this->worksheet); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php index c20efabe..067d30e5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeries.php @@ -40,6 +40,10 @@ class DataSeries const STYLE_MARKER = 'marker'; const STYLE_FILLED = 'filled'; + const EMPTY_AS_GAP = 'gap'; + const EMPTY_AS_ZERO = 'zero'; + const EMPTY_AS_SPAN = 'span'; + /** * Series Plot Type. * @@ -71,21 +75,21 @@ class DataSeries /** * Order of plots in Series. * - * @var array of integer + * @var int[] */ private $plotOrder = []; /** * Plot Label. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotLabel = []; /** * Plot Category. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotCategory = []; @@ -99,7 +103,7 @@ class DataSeries /** * Plot Values. * - * @var array of DataSeriesValues + * @var DataSeriesValues[] */ private $plotValues = []; @@ -227,7 +231,7 @@ public function getPlotOrder() /** * Get Plot Labels. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotLabels() { @@ -239,7 +243,7 @@ public function getPlotLabels() * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotLabelByIndex($index) { @@ -256,7 +260,7 @@ public function getPlotLabelByIndex($index) /** * Get Plot Categories. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotCategories() { @@ -268,7 +272,7 @@ public function getPlotCategories() * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotCategoryByIndex($index) { @@ -309,7 +313,7 @@ public function setPlotStyle($plotStyle) /** * Get Plot Values. * - * @return array of DataSeriesValues + * @return DataSeriesValues[] */ public function getPlotValues() { @@ -321,7 +325,7 @@ public function getPlotValues() * * @param mixed $index * - * @return DataSeriesValues + * @return DataSeriesValues|false */ public function getPlotValuesByIndex($index) { @@ -369,7 +373,7 @@ public function setSmoothLine($smoothLine) return $this; } - public function refresh(Worksheet $worksheet) + public function refresh(Worksheet $worksheet): void { foreach ($this->plotValues as $plotValues) { if ($plotValues !== null) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php index ec40cb84..88063336 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/DataSeriesValues.php @@ -55,7 +55,7 @@ class DataSeriesValues /** * Data Values. * - * @var array of mixed + * @var mixed[] */ private $dataValues = []; @@ -115,8 +115,6 @@ public function getDataType() * DataSeriesValues::DATASERIES_TYPE_NUMBER * Normally used for chart data values * - * @throws Exception - * * @return $this */ public function setDataType($dataType) @@ -247,8 +245,6 @@ public function setFillColor($color) * * @param string $color value for color * - * @throws \Exception thrown if color is invalid - * * @return bool true if validation was successful */ private function validateColor($color) @@ -317,7 +313,7 @@ public function multiLevelCount() /** * Get Series Data Values. * - * @return array of mixed + * @return mixed[] */ public function getDataValues() { @@ -356,7 +352,7 @@ public function setDataValues($dataValues) return $this; } - public function refresh(Worksheet $worksheet, $flatten = true) + public function refresh(Worksheet $worksheet, $flatten = true): void { if ($this->dataSource !== null) { $calcEngine = Calculation::getInstance($worksheet->getParent()); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php index b07fcae5..84af3ada 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/GridLines.php @@ -105,73 +105,73 @@ private function activateObject() * * @param string $value * @param int $alpha - * @param string $type + * @param string $colorType */ - public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD) + public function setLineColorProperties($value, $alpha = 0, $colorType = self::EXCEL_COLOR_TYPE_STANDARD): void { $this->activateObject() ->lineProperties['color'] = $this->setColorProperties( $value, $alpha, - $type + $colorType ); } /** * Set Line Color Properties. * - * @param float $line_width - * @param string $compound_type - * @param string $dash_type - * @param string $cap_type - * @param string $join_type - * @param string $head_arrow_type - * @param string $head_arrow_size - * @param string $end_arrow_type - * @param string $end_arrow_size + * @param float $lineWidth + * @param string $compoundType + * @param string $dashType + * @param string $capType + * @param string $joinType + * @param string $headArrowType + * @param string $headArrowSize + * @param string $endArrowType + * @param string $endArrowSize */ - public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) + public function setLineStyleProperties($lineWidth = null, $compoundType = null, $dashType = null, $capType = null, $joinType = null, $headArrowType = null, $headArrowSize = null, $endArrowType = null, $endArrowSize = null): void { $this->activateObject(); - ($line_width !== null) - ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) + ($lineWidth !== null) + ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $lineWidth) : null; - ($compound_type !== null) - ? $this->lineProperties['style']['compound'] = (string) $compound_type + ($compoundType !== null) + ? $this->lineProperties['style']['compound'] = (string) $compoundType : null; - ($dash_type !== null) - ? $this->lineProperties['style']['dash'] = (string) $dash_type + ($dashType !== null) + ? $this->lineProperties['style']['dash'] = (string) $dashType : null; - ($cap_type !== null) - ? $this->lineProperties['style']['cap'] = (string) $cap_type + ($capType !== null) + ? $this->lineProperties['style']['cap'] = (string) $capType : null; - ($join_type !== null) - ? $this->lineProperties['style']['join'] = (string) $join_type + ($joinType !== null) + ? $this->lineProperties['style']['join'] = (string) $joinType : null; - ($head_arrow_type !== null) - ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type + ($headArrowType !== null) + ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $headArrowType : null; - ($head_arrow_size !== null) - ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size + ($headArrowSize !== null) + ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $headArrowSize : null; - ($end_arrow_type !== null) - ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type + ($endArrowType !== null) + ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $endArrowType : null; - ($end_arrow_size !== null) - ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size + ($endArrowSize !== null) + ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $endArrowSize : null; } /** * Get Line Color Property. * - * @param string $parameter + * @param string $propertyName * * @return string */ - public function getLineColorProperty($parameter) + public function getLineColorProperty($propertyName) { - return $this->lineProperties['color'][$parameter]; + return $this->lineProperties['color'][$propertyName]; } /** @@ -190,28 +190,28 @@ public function getLineStyleProperty($elements) * Set Glow Properties. * * @param float $size - * @param string $color_value - * @param int $color_alpha - * @param string $color_type + * @param string $colorValue + * @param int $colorAlpha + * @param string $colorType */ - public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) + public function setGlowProperties($size, $colorValue = null, $colorAlpha = null, $colorType = null): void { $this ->activateObject() ->setGlowSize($size) - ->setGlowColor($color_value, $color_alpha, $color_type); + ->setGlowColor($colorValue, $colorAlpha, $colorType); } /** * Get Glow Color Property. * - * @param string $property + * @param string $propertyName * * @return string */ - public function getGlowColor($property) + public function getGlowColor($propertyName) { - return $this->glowProperties['color'][$property]; + return $this->glowProperties['color'][$propertyName]; } /** @@ -243,11 +243,11 @@ private function setGlowSize($size) * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @return $this */ - private function setGlowColor($color, $alpha, $type) + private function setGlowColor($color, $alpha, $colorType) { if ($color !== null) { $this->glowProperties['color']['value'] = (string) $color; @@ -255,8 +255,8 @@ private function setGlowColor($color, $alpha, $type) if ($alpha !== null) { $this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } - if ($type !== null) { - $this->glowProperties['color']['type'] = (string) $type; + if ($colorType !== null) { + $this->glowProperties['color']['type'] = (string) $colorType; } return $this; @@ -265,52 +265,52 @@ private function setGlowColor($color, $alpha, $type) /** * Get Line Style Arrow Parameters. * - * @param string $arrow_selector - * @param string $property_selector + * @param string $arrowSelector + * @param string $propertySelector * * @return string */ - public function getLineStyleArrowParameters($arrow_selector, $property_selector) + public function getLineStyleArrowParameters($arrowSelector, $propertySelector) { - return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector); + return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrowSelector]['size'], $propertySelector); } /** * Set Shadow Properties. * - * @param int $sh_presets - * @param string $sh_color_value - * @param string $sh_color_type - * @param int $sh_color_alpha - * @param string $sh_blur - * @param int $sh_angle - * @param float $sh_distance + * @param int $presets + * @param string $colorValue + * @param string $colorType + * @param string $colorAlpha + * @param string $blur + * @param int $angle + * @param float $distance */ - public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) + public function setShadowProperties($presets, $colorValue = null, $colorType = null, $colorAlpha = null, $blur = null, $angle = null, $distance = null): void { $this->activateObject() - ->setShadowPresetsProperties((int) $sh_presets) + ->setShadowPresetsProperties((int) $presets) ->setShadowColor( - $sh_color_value === null ? $this->shadowProperties['color']['value'] : $sh_color_value, - $sh_color_alpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha), - $sh_color_type === null ? $this->shadowProperties['color']['type'] : $sh_color_type + $colorValue ?? $this->shadowProperties['color']['value'], + $colorAlpha === null ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($colorAlpha), + $colorType ?? $this->shadowProperties['color']['type'] ) - ->setShadowBlur($sh_blur) - ->setShadowAngle($sh_angle) - ->setShadowDistance($sh_distance); + ->setShadowBlur((float) $blur) + ->setShadowAngle($angle) + ->setShadowDistance($distance); } /** * Set Shadow Presets Properties. * - * @param int $shadow_presets + * @param int $presets * * @return $this */ - private function setShadowPresetsProperties($shadow_presets) + private function setShadowPresetsProperties($presets) { - $this->shadowProperties['presets'] = $shadow_presets; - $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + $this->shadowProperties['presets'] = $presets; + $this->setShadowPropertiesMapValues($this->getShadowPresetsMap($presets)); return $this; } @@ -318,22 +318,21 @@ private function setShadowPresetsProperties($shadow_presets) /** * Set Shadow Properties Values. * - * @param array $properties_map - * @param mixed &$reference + * @param mixed $reference * * @return $this */ - private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + private function setShadowPropertiesMapValues(array $propertiesMap, &$reference = null) { $base_reference = $reference; - foreach ($properties_map as $property_key => $property_val) { + foreach ($propertiesMap as $property_key => $property_val) { if (is_array($property_val)) { if ($reference === null) { $reference = &$this->shadowProperties[$property_key]; } else { $reference = &$reference[$property_key]; } - $this->setShadowProperiesMapValues($property_val, $reference); + $this->setShadowPropertiesMapValues($property_val, $reference); } else { if ($base_reference === null) { $this->shadowProperties[$property_key] = $property_val; @@ -351,11 +350,11 @@ private function setShadowProperiesMapValues(array $properties_map, &$reference * * @param string $color * @param int $alpha - * @param string $type + * @param string $colorType * * @return $this */ - private function setShadowColor($color, $alpha, $type) + private function setShadowColor($color, $alpha, $colorType) { if ($color !== null) { $this->shadowProperties['color']['value'] = (string) $color; @@ -363,8 +362,8 @@ private function setShadowColor($color, $alpha, $type) if ($alpha !== null) { $this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); } - if ($type !== null) { - $this->shadowProperties['color']['type'] = (string) $type; + if ($colorType !== null) { + $this->shadowProperties['color']['type'] = (string) $colorType; } return $this; @@ -435,7 +434,7 @@ public function getShadowProperty($elements) * * @param float $size */ - public function setSoftEdgesSize($size) + public function setSoftEdgesSize($size): void { if ($size !== null) { $this->activateObject(); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php index 3e989c6d..cea96557 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Layout.php @@ -110,8 +110,6 @@ class Layout /** * Create a new Layout. - * - * @param array $layout */ public function __construct(array $layout = []) { @@ -151,13 +149,13 @@ public function getLayoutTarget() /** * Set Layout Target. * - * @param string $value + * @param string $target * * @return $this */ - public function setLayoutTarget($value) + public function setLayoutTarget($target) { - $this->layoutTarget = $value; + $this->layoutTarget = $target; return $this; } @@ -175,13 +173,13 @@ public function getXMode() /** * Set X-Mode. * - * @param string $value + * @param string $mode * * @return $this */ - public function setXMode($value) + public function setXMode($mode) { - $this->xMode = (string) $value; + $this->xMode = (string) $mode; return $this; } @@ -199,13 +197,13 @@ public function getYMode() /** * Set Y-Mode. * - * @param string $value + * @param string $mode * * @return $this */ - public function setYMode($value) + public function setYMode($mode) { - $this->yMode = (string) $value; + $this->yMode = (string) $mode; return $this; } @@ -223,13 +221,13 @@ public function getXPosition() /** * Set X-Position. * - * @param float $value + * @param float $position * * @return $this */ - public function setXPosition($value) + public function setXPosition($position) { - $this->xPos = (float) $value; + $this->xPos = (float) $position; return $this; } @@ -247,13 +245,13 @@ public function getYPosition() /** * Set Y-Position. * - * @param float $value + * @param float $position * * @return $this */ - public function setYPosition($value) + public function setYPosition($position) { - $this->yPos = (float) $value; + $this->yPos = (float) $position; return $this; } @@ -271,13 +269,13 @@ public function getWidth() /** * Set Width. * - * @param float $value + * @param float $width * * @return $this */ - public function setWidth($value) + public function setWidth($width) { - $this->width = $value; + $this->width = $width; return $this; } @@ -295,13 +293,13 @@ public function getHeight() /** * Set Height. * - * @param float $value + * @param float $height * * @return $this */ - public function setHeight($value) + public function setHeight($height) { - $this->height = $value; + $this->height = $height; return $this; } @@ -320,13 +318,13 @@ public function getShowLegendKey() * Set show legend key * Specifies that legend keys should be shown in data labels. * - * @param bool $value Show legend key + * @param bool $showLegendKey Show legend key * * @return $this */ - public function setShowLegendKey($value) + public function setShowLegendKey($showLegendKey) { - $this->showLegendKey = $value; + $this->showLegendKey = $showLegendKey; return $this; } @@ -345,13 +343,13 @@ public function getShowVal() * Set show val * Specifies that the value should be shown in data labels. * - * @param bool $value Show val + * @param bool $showDataLabelValues Show val * * @return $this */ - public function setShowVal($value) + public function setShowVal($showDataLabelValues) { - $this->showVal = $value; + $this->showVal = $showDataLabelValues; return $this; } @@ -370,13 +368,13 @@ public function getShowCatName() * Set show cat name * Specifies that the category name should be shown in data labels. * - * @param bool $value Show cat name + * @param bool $showCategoryName Show cat name * * @return $this */ - public function setShowCatName($value) + public function setShowCatName($showCategoryName) { - $this->showCatName = $value; + $this->showCatName = $showCategoryName; return $this; } @@ -395,13 +393,13 @@ public function getShowSerName() * Set show ser name * Specifies that the series name should be shown in data labels. * - * @param bool $value Show series name + * @param bool $showSeriesName Show series name * * @return $this */ - public function setShowSerName($value) + public function setShowSerName($showSeriesName) { - $this->showSerName = $value; + $this->showSerName = $showSeriesName; return $this; } @@ -420,13 +418,13 @@ public function getShowPercent() * Set show percentage * Specifies that the percentage should be shown in data labels. * - * @param bool $value Show percentage + * @param bool $showPercentage Show percentage * * @return $this */ - public function setShowPercent($value) + public function setShowPercent($showPercentage) { - $this->showPercent = $value; + $this->showPercent = $showPercentage; return $this; } @@ -445,13 +443,13 @@ public function getShowBubbleSize() * Set show bubble size * Specifies that the bubble size should be shown in data labels. * - * @param bool $value Show bubble size + * @param bool $showBubbleSize Show bubble size * * @return $this */ - public function setShowBubbleSize($value) + public function setShowBubbleSize($showBubbleSize) { - $this->showBubbleSize = $value; + $this->showBubbleSize = $showBubbleSize; return $this; } @@ -470,13 +468,13 @@ public function getShowLeaderLines() * Set show leader lines * Specifies that leader lines should be shown in data labels. * - * @param bool $value Show leader lines + * @param bool $showLeaderLines Show leader lines * * @return $this */ - public function setShowLeaderLines($value) + public function setShowLeaderLines($showLeaderLines) { - $this->showLeaderLines = $value; + $this->showLeaderLines = $showLeaderLines; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php index d0776265..2f003cd8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Legend.php @@ -52,10 +52,9 @@ class Legend * Create a new Legend. * * @param string $position - * @param null|Layout $layout * @param bool $overlay */ - public function __construct($position = self::POSITION_RIGHT, Layout $layout = null, $overlay = false) + public function __construct($position = self::POSITION_RIGHT, ?Layout $layout = null, $overlay = false) { $this->setPosition($position); $this->layout = $layout; @@ -132,18 +131,10 @@ public function getOverlay() * Set allow overlay of other elements? * * @param bool $overlay - * - * @return bool */ - public function setOverlay($overlay) + public function setOverlay($overlay): void { - if (!is_bool($overlay)) { - return false; - } - $this->overlay = $overlay; - - return true; } /** diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php index 9da4aa32..ecb7b6c9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/PlotArea.php @@ -23,10 +23,9 @@ class PlotArea /** * Create a new PlotArea. * - * @param null|Layout $layout * @param DataSeries[] $plotSeries */ - public function __construct(Layout $layout = null, array $plotSeries = []) + public function __construct(?Layout $layout = null, array $plotSeries = []) { $this->layout = $layout; $this->plotSeries = $plotSeries; @@ -44,10 +43,8 @@ public function getLayout() /** * Get Number of Plot Groups. - * - * @return array of DataSeries */ - public function getPlotGroupCount() + public function getPlotGroupCount(): int { return count($this->plotSeries); } @@ -70,7 +67,7 @@ public function getPlotSeriesCount() /** * Get Plot Series. * - * @return array of DataSeries + * @return DataSeries[] */ public function getPlotGroup() { @@ -103,7 +100,7 @@ public function setPlotSeries(array $plotSeries) return $this; } - public function refresh(Worksheet $worksheet) + public function refresh(Worksheet $worksheet): void { foreach ($this->plotSeries as $plotSeries) { $plotSeries->refresh($worksheet); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php index 98095f0d..ef22fb52 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Properties.php @@ -135,16 +135,16 @@ protected function getTrueAlpha($alpha) return (string) 100 - $alpha . '000'; } - protected function setColorProperties($color, $alpha, $type) + protected function setColorProperties($color, $alpha, $colorType) { return [ - 'type' => (string) $type, + 'type' => (string) $colorType, 'value' => (string) $color, 'alpha' => (string) $this->getTrueAlpha($alpha), ]; } - protected function getLineStyleArrowSize($array_selector, $array_kay_selector) + protected function getLineStyleArrowSize($arraySelector, $arrayKaySelector) { $sizes = [ 1 => ['w' => 'sm', 'len' => 'sm'], @@ -158,10 +158,10 @@ protected function getLineStyleArrowSize($array_selector, $array_kay_selector) 9 => ['w' => 'lg', 'len' => 'lg'], ]; - return $sizes[$array_selector][$array_kay_selector]; + return $sizes[$arraySelector][$arrayKaySelector]; } - protected function getShadowPresetsMap($shadow_presets_option) + protected function getShadowPresetsMap($presetsOption) { $presets_options = [ //OUTER @@ -350,7 +350,7 @@ protected function getShadowPresetsMap($shadow_presets_option) ], ]; - return $presets_options[$shadow_presets_option]; + return $presets_options[$presetsOption]; } protected function getArrayElementsValue($properties, $elements) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php index c6fcfbfc..3032f6ba 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/IRenderer.php @@ -8,8 +8,6 @@ interface IRenderer { /** * IRenderer constructor. - * - * @param \PhpOffice\PhpSpreadsheet\Chart\Chart $chart */ public function __construct(Chart $chart); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php index 9dcab049..0ab70870 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/JpGraph.php @@ -2,10 +2,24 @@ namespace PhpOffice\PhpSpreadsheet\Chart\Renderer; +use AccBarPlot; +use AccLinePlot; +use BarPlot; +use ContourPlot; +use Graph; +use GroupBarPlot; +use LinePlot; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; - -require_once __DIR__ . '/Polyfill.php'; +use PieGraph; +use PiePlot; +use PiePlot3D; +use PiePlotC; +use RadarGraph; +use RadarPlot; +use ScatterPlot; +use Spline; +use StockPlot; class JpGraph implements IRenderer { @@ -33,8 +47,6 @@ class JpGraph implements IRenderer /** * Create a new jpgraph. - * - * @param Chart $chart */ public function __construct(Chart $chart) { @@ -43,7 +55,7 @@ public function __construct(Chart $chart) $this->chart = $chart; } - private static function init() + private static function init(): void { static $loaded = false; if ($loaded) { @@ -179,7 +191,7 @@ private function getCaption($captionElement) return $caption; } - private function renderTitle() + private function renderTitle(): void { $title = $this->getCaption($this->chart->getTitle()); if ($title !== null) { @@ -187,7 +199,7 @@ private function renderTitle() } } - private function renderLegend() + private function renderLegend(): void { $legend = $this->chart->getLegend(); if ($legend !== null) { @@ -205,9 +217,11 @@ private function renderLegend() break; case 't': $this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top + break; case 'b': $this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom + break; default: $this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right @@ -220,9 +234,9 @@ private function renderLegend() } } - private function renderCartesianPlotArea($type = 'textlin') + private function renderCartesianPlotArea($type = 'textlin'): void { - $this->graph = new \Graph(self::$width, self::$height); + $this->graph = new Graph(self::$width, self::$height); $this->graph->SetScale($type); $this->renderTitle(); @@ -257,22 +271,22 @@ private function renderCartesianPlotArea($type = 'textlin') } } - private function renderPiePlotArea() + private function renderPiePlotArea(): void { - $this->graph = new \PieGraph(self::$width, self::$height); + $this->graph = new PieGraph(self::$width, self::$height); $this->renderTitle(); } - private function renderRadarPlotArea() + private function renderRadarPlotArea(): void { - $this->graph = new \RadarGraph(self::$width, self::$height); + $this->graph = new RadarGraph(self::$width, self::$height); $this->graph->SetScale('lin'); $this->renderTitle(); } - private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') + private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d'): void { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); @@ -287,6 +301,8 @@ private function renderPlotLine($groupID, $filled = false, $combination = false, $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } else { + $sumValues = []; } // Loop through each data series in turn @@ -308,7 +324,7 @@ private function renderPlotLine($groupID, $filled = false, $combination = false, ++$testCurrentIndex; } - $seriesPlot = new \LinePlot($dataValues); + $seriesPlot = new LinePlot($dataValues); if ($combination) { $seriesPlot->SetBarCenter(); } @@ -330,12 +346,12 @@ private function renderPlotLine($groupID, $filled = false, $combination = false, if ($grouping == 'standard') { $groupPlot = $seriesPlots; } else { - $groupPlot = new \AccLinePlot($seriesPlots); + $groupPlot = new AccLinePlot($seriesPlots); } $this->graph->Add($groupPlot); } - private function renderPlotBar($groupID, $dimensions = '2d') + private function renderPlotBar($groupID, $dimensions = '2d'): void { $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); // Rotate for bar rather than column chart @@ -362,6 +378,8 @@ private function renderPlotBar($groupID, $dimensions = '2d') $seriesPlots = []; if ($grouping == 'percentStacked') { $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } else { + $sumValues = []; } // Loop through each data series in turn @@ -385,7 +403,7 @@ private function renderPlotBar($groupID, $dimensions = '2d') if ($rotation == 'bar') { $dataValues = array_reverse($dataValues); } - $seriesPlot = new \BarPlot($dataValues); + $seriesPlot = new BarPlot($dataValues); $seriesPlot->SetColor('black'); $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); if ($dimensions == '3d') { @@ -406,11 +424,11 @@ private function renderPlotBar($groupID, $dimensions = '2d') } if ($grouping == 'clustered') { - $groupPlot = new \GroupBarPlot($seriesPlots); + $groupPlot = new GroupBarPlot($seriesPlots); } elseif ($grouping == 'standard') { - $groupPlot = new \GroupBarPlot($seriesPlots); + $groupPlot = new GroupBarPlot($seriesPlots); } else { - $groupPlot = new \AccBarPlot($seriesPlots); + $groupPlot = new AccBarPlot($seriesPlots); if ($dimensions == '3d') { $groupPlot->SetShadow(); } @@ -419,7 +437,7 @@ private function renderPlotBar($groupID, $dimensions = '2d') $this->graph->Add($groupPlot); } - private function renderPlotScatter($groupID, $bubble) + private function renderPlotScatter($groupID, $bubble): void { $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); @@ -436,14 +454,14 @@ private function renderPlotScatter($groupID, $bubble) $dataValuesY[$k] = $k; } - $seriesPlot = new \ScatterPlot($dataValuesX, $dataValuesY); + $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); if ($scatterStyle == 'lineMarker') { $seriesPlot->SetLinkPoints(); $seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]); } elseif ($scatterStyle == 'smoothMarker') { - $spline = new \Spline($dataValuesY, $dataValuesX); + $spline = new Spline($dataValuesY, $dataValuesX); [$splineDataY, $splineDataX] = $spline->Get(count($dataValuesX) * self::$width / 20); - $lplot = new \LinePlot($splineDataX, $splineDataY); + $lplot = new LinePlot($splineDataX, $splineDataY); $lplot->SetColor(self::$colourSet[self::$plotColour]); $this->graph->Add($lplot); @@ -464,7 +482,7 @@ private function renderPlotScatter($groupID, $bubble) } } - private function renderPlotRadar($groupID) + private function renderPlotRadar($groupID): void { $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); @@ -488,7 +506,7 @@ private function renderPlotRadar($groupID) $this->graph->SetTitles(array_reverse($dataValues)); - $seriesPlot = new \RadarPlot(array_reverse($dataValuesX)); + $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); @@ -502,7 +520,7 @@ private function renderPlotRadar($groupID) } } - private function renderPlotContour($groupID) + private function renderPlotContour($groupID): void { $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); @@ -517,12 +535,12 @@ private function renderPlotContour($groupID) $dataValues[$i] = $dataValuesX; } - $seriesPlot = new \ContourPlot($dataValues); + $seriesPlot = new ContourPlot($dataValues); $this->graph->Add($seriesPlot); } - private function renderPlotStock($groupID) + private function renderPlotStock($groupID): void { $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); @@ -556,13 +574,13 @@ private function renderPlotStock($groupID) $this->graph->xaxis->SetTickLabels($datasetLabels); } - $seriesPlot = new \StockPlot($dataValuesPlot); + $seriesPlot = new StockPlot($dataValuesPlot); $seriesPlot->SetWidth(20); $this->graph->Add($seriesPlot); } - private function renderAreaChart($groupCount, $dimensions = '2d') + private function renderAreaChart($groupCount, $dimensions = '2d'): void { $this->renderCartesianPlotArea(); @@ -571,7 +589,7 @@ private function renderAreaChart($groupCount, $dimensions = '2d') } } - private function renderLineChart($groupCount, $dimensions = '2d') + private function renderLineChart($groupCount, $dimensions = '2d'): void { $this->renderCartesianPlotArea(); @@ -580,7 +598,7 @@ private function renderLineChart($groupCount, $dimensions = '2d') } } - private function renderBarChart($groupCount, $dimensions = '2d') + private function renderBarChart($groupCount, $dimensions = '2d'): void { $this->renderCartesianPlotArea(); @@ -589,7 +607,7 @@ private function renderBarChart($groupCount, $dimensions = '2d') } } - private function renderScatterChart($groupCount) + private function renderScatterChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); @@ -598,7 +616,7 @@ private function renderScatterChart($groupCount) } } - private function renderBubbleChart($groupCount) + private function renderBubbleChart($groupCount): void { $this->renderCartesianPlotArea('linlin'); @@ -607,7 +625,7 @@ private function renderBubbleChart($groupCount) } } - private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false) + private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false): void { $this->renderPiePlotArea(); @@ -643,12 +661,12 @@ private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = fal } if ($dimensions == '3d') { - $seriesPlot = new \PiePlot3D($dataValues); + $seriesPlot = new PiePlot3D($dataValues); } else { if ($doughnut) { - $seriesPlot = new \PiePlotC($dataValues); + $seriesPlot = new PiePlotC($dataValues); } else { - $seriesPlot = new \PiePlot($dataValues); + $seriesPlot = new PiePlot($dataValues); } } @@ -679,7 +697,7 @@ private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = fal } } - private function renderRadarChart($groupCount) + private function renderRadarChart($groupCount): void { $this->renderRadarPlotArea(); @@ -688,7 +706,7 @@ private function renderRadarChart($groupCount) } } - private function renderStockChart($groupCount) + private function renderStockChart($groupCount): void { $this->renderCartesianPlotArea('intint'); @@ -697,7 +715,7 @@ private function renderStockChart($groupCount) } } - private function renderContourChart($groupCount, $dimensions) + private function renderContourChart($groupCount, $dimensions): void { $this->renderCartesianPlotArea('intint'); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/Polyfill.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/Polyfill.php deleted file mode 100644 index 7fa38394..00000000 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Chart/Renderer/Polyfill.php +++ /dev/null @@ -1,9 +0,0 @@ -caption = $caption; $this->layout = $layout; @@ -33,17 +34,40 @@ public function __construct($caption = null, Layout $layout = null) /** * Get caption. * - * @return string + * @return array|RichText|string */ public function getCaption() { return $this->caption; } + public function getCaptionText(): string + { + $caption = $this->caption; + if (is_string($caption)) { + return $caption; + } + if ($caption instanceof RichText) { + return $caption->getPlainText(); + } + $retVal = ''; + foreach ($caption as $textx) { + /** @var RichText|string */ + $text = $textx; + if ($text instanceof RichText) { + $retVal .= $text->getPlainText(); + } else { + $retVal .= $text; + } + } + + return $retVal; + } + /** * Set caption. * - * @param string $caption + * @param array|RichText|string $caption * * @return $this */ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php index 84c3d300..d49f5457 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Cells.php @@ -2,37 +2,38 @@ namespace PhpOffice\PhpSpreadsheet\Collection; +use Generator; use PhpOffice\PhpSpreadsheet\Cell\Cell; -use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use Psr\SimpleCache\CacheInterface; class Cells { /** - * @var \Psr\SimpleCache\CacheInterface + * @var CacheInterface */ private $cache; /** * Parent worksheet. * - * @var Worksheet + * @var null|Worksheet */ private $parent; /** * The currently active Cell. * - * @var Cell + * @var null|Cell */ private $currentCell; /** * Coordinate of the currently active Cell. * - * @var string + * @var null|string */ private $currentCoordinate; @@ -61,7 +62,6 @@ class Cells * Initialise this new cell collection. * * @param Worksheet $parent The worksheet for this cell collection - * @param CacheInterface $cache */ public function __construct(Worksheet $parent, CacheInterface $cache) { @@ -76,7 +76,7 @@ public function __construct(Worksheet $parent, CacheInterface $cache) /** * Return the parent worksheet for this cell collection. * - * @return Worksheet + * @return null|Worksheet */ public function getParent() { @@ -86,18 +86,18 @@ public function getParent() /** * Whether the collection holds a cell for the given coordinate. * - * @param string $pCoord Coordinate of the cell to check + * @param string $cellCoordinate Coordinate of the cell to check * * @return bool */ - public function has($pCoord) + public function has($cellCoordinate) { - if ($pCoord === $this->currentCoordinate) { + if ($cellCoordinate === $this->currentCoordinate) { return true; } // Check if the requested entry exists in the index - return isset($this->index[$pCoord]); + return isset($this->index[$cellCoordinate]); } /** @@ -105,8 +105,6 @@ public function has($pCoord) * * @param Cell $cell Cell to update * - * @throws PhpSpreadsheetException - * * @return Cell */ public function update(Cell $cell) @@ -117,21 +115,21 @@ public function update(Cell $cell) /** * Delete a cell in cache identified by coordinate. * - * @param string $pCoord Coordinate of the cell to delete + * @param string $cellCoordinate Coordinate of the cell to delete */ - public function delete($pCoord) + public function delete($cellCoordinate): void { - if ($pCoord === $this->currentCoordinate && $this->currentCell !== null) { + if ($cellCoordinate === $this->currentCoordinate && $this->currentCell !== null) { $this->currentCell->detach(); $this->currentCoordinate = null; $this->currentCell = null; $this->currentCellIsDirty = false; } - unset($this->index[$pCoord]); + unset($this->index[$cellCoordinate]); // Delete the entry from cache - $this->cache->delete($this->cachePrefix . $pCoord); + $this->cache->delete($this->cachePrefix . $cellCoordinate); } /** @@ -153,8 +151,6 @@ public function getSortedCoordinates() { $sortKeys = []; foreach ($this->getCoordinates() as $coord) { - $column = ''; - $row = 0; sscanf($coord, '%[A-Z]%d', $column, $row); $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; } @@ -174,8 +170,6 @@ public function getHighestRowAndColumn() $col = ['A' => '1A']; $row = [1]; foreach ($this->getCoordinates() as $coord) { - $c = ''; - $r = 0; sscanf($coord, '%[A-Z]%d', $c, $r); $row[$r] = $r; $col[$c] = strlen($c) . $c; @@ -183,7 +177,7 @@ public function getHighestRowAndColumn() // Determine highest column and row $highestRow = max($row); - $highestColumn = substr(max($col), 1); + $highestColumn = substr((string) @max($col), 1); return [ 'row' => $highestRow, @@ -194,7 +188,7 @@ public function getHighestRowAndColumn() /** * Return the cell coordinate of the currently active cell object. * - * @return string + * @return null|string */ public function getCurrentCoordinate() { @@ -208,10 +202,7 @@ public function getCurrentCoordinate() */ public function getCurrentColumn() { - $column = ''; - $row = 0; - - sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row); + sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return $column; } @@ -223,10 +214,7 @@ public function getCurrentColumn() */ public function getCurrentRow() { - $column = ''; - $row = 0; - - sscanf($this->currentCoordinate, '%[A-Z]%d', $column, $row); + sscanf($this->currentCoordinate ?? '', '%[A-Z]%d', $column, $row); return (int) $row; } @@ -234,7 +222,7 @@ public function getCurrentRow() /** * Get highest worksheet column. * - * @param string $row Return the highest column for the specified row, + * @param null|int|string $row Return the highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name @@ -242,30 +230,25 @@ public function getCurrentRow() public function getHighestColumn($row = null) { if ($row === null) { - $colRow = $this->getHighestRowAndColumn(); - - return $colRow['column']; + return $this->getHighestRowAndColumn()['column']; } - $columnList = [1]; + $maxColumn = '1A'; foreach ($this->getCoordinates() as $coord) { - $c = ''; - $r = 0; - sscanf($coord, '%[A-Z]%d', $c, $r); if ($r != $row) { continue; } - $columnList[] = Coordinate::columnIndexFromString($c); + $maxColumn = max($maxColumn, strlen($c) . $c); } - return Coordinate::stringFromColumnIndex(max($columnList)); + return substr($maxColumn, 1); } /** * Get highest worksheet row. * - * @param string $column Return the highest row for the specified column, + * @param null|string $column Return the highest row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number @@ -273,24 +256,19 @@ public function getHighestColumn($row = null) public function getHighestRow($column = null) { if ($column === null) { - $colRow = $this->getHighestRowAndColumn(); - - return $colRow['row']; + return $this->getHighestRowAndColumn()['row']; } - $rowList = [0]; + $maxRow = 1; foreach ($this->getCoordinates() as $coord) { - $c = ''; - $r = 0; - sscanf($coord, '%[A-Z]%d', $c, $r); if ($c != $column) { continue; } - $rowList[] = $r; + $maxRow = max($maxRow, $r); } - return max($rowList); + return $maxRow; } /** @@ -300,23 +278,23 @@ public function getHighestRow($column = null) */ private function getUniqueID() { - return uniqid('phpspreadsheet.', true) . '.'; + return Settings::getCache() instanceof Memory + ? random_bytes(7) . ':' + : uniqid('phpspreadsheet.', true) . '.'; } /** * Clone the cell collection. * - * @param Worksheet $parent The new worksheet that we're copying to - * * @return self */ - public function cloneCellCollection(Worksheet $parent) + public function cloneCellCollection(Worksheet $worksheet) { $this->storeCurrentCell(); $newCollection = clone $this; - $newCollection->parent = $parent; - if (($newCollection->currentCell !== null) && (is_object($newCollection->currentCell))) { + $newCollection->parent = $worksheet; + if (is_object($newCollection->currentCell)) { $newCollection->currentCell->attach($this); } @@ -329,16 +307,14 @@ public function cloneCellCollection(Worksheet $parent) // Change prefix $newCollection->cachePrefix = $newCollection->getUniqueID(); foreach ($oldValues as $oldKey => $value) { - $newValues[str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey)] = clone $value; + /** @var string $newKey */ + $newKey = str_replace($oldCachePrefix, $newCollection->cachePrefix, $oldKey); + $newValues[$newKey] = clone $value; } // Store new values $stored = $newCollection->cache->setMultiple($newValues); - if (!$stored) { - $newCollection->__destruct(); - - throw new PhpSpreadsheetException('Failed to copy cells in cache'); - } + $this->destructIfNeeded($stored, $newCollection, 'Failed to copy cells in cache'); return $newCollection; } @@ -348,12 +324,9 @@ public function cloneCellCollection(Worksheet $parent) * * @param string $row Row number to remove */ - public function removeRow($row) + public function removeRow($row): void { foreach ($this->getCoordinates() as $coord) { - $c = ''; - $r = 0; - sscanf($coord, '%[A-Z]%d', $c, $r); if ($r == $row) { $this->delete($coord); @@ -366,12 +339,9 @@ public function removeRow($row) * * @param string $column Column ID to remove */ - public function removeColumn($column) + public function removeColumn($column): void { foreach ($this->getCoordinates() as $coord) { - $c = ''; - $r = 0; - sscanf($coord, '%[A-Z]%d', $c, $r); if ($c == $column) { $this->delete($coord); @@ -382,20 +352,14 @@ public function removeColumn($column) /** * Store cell data in cache for the current cell object if it's "dirty", * and the 'nullify' the current cell object. - * - * @throws PhpSpreadsheetException */ - private function storeCurrentCell() + private function storeCurrentCell(): void { - if ($this->currentCellIsDirty && !empty($this->currentCoordinate)) { + if ($this->currentCellIsDirty && isset($this->currentCoordinate, $this->currentCell)) { $this->currentCell->detach(); $stored = $this->cache->set($this->cachePrefix . $this->currentCoordinate, $this->currentCell); - if (!$stored) { - $this->__destruct(); - - throw new PhpSpreadsheetException("Failed to store cell {$this->currentCoordinate} in cache"); - } + $this->destructIfNeeded($stored, $this, "Failed to store cell {$this->currentCoordinate} in cache"); $this->currentCellIsDirty = false; } @@ -403,24 +367,31 @@ private function storeCurrentCell() $this->currentCell = null; } + private function destructIfNeeded(bool $stored, self $cells, string $message): void + { + if (!$stored) { + $cells->__destruct(); + + throw new PhpSpreadsheetException($message); + } + } + /** * Add or update a cell identified by its coordinate into the collection. * - * @param string $pCoord Coordinate of the cell to update + * @param string $cellCoordinate Coordinate of the cell to update * @param Cell $cell Cell to update * - * @throws PhpSpreadsheetException - * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell + * @return Cell */ - public function add($pCoord, Cell $cell) + public function add($cellCoordinate, Cell $cell) { - if ($pCoord !== $this->currentCoordinate) { + if ($cellCoordinate !== $this->currentCoordinate) { $this->storeCurrentCell(); } - $this->index[$pCoord] = true; + $this->index[$cellCoordinate] = true; - $this->currentCoordinate = $pCoord; + $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; $this->currentCellIsDirty = true; @@ -430,32 +401,30 @@ public function add($pCoord, Cell $cell) /** * Get cell at a specific coordinate. * - * @param string $pCoord Coordinate of the cell - * - * @throws PhpSpreadsheetException + * @param string $cellCoordinate Coordinate of the cell * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell Cell that was found, or null if not found + * @return null|Cell Cell that was found, or null if not found */ - public function get($pCoord) + public function get($cellCoordinate) { - if ($pCoord === $this->currentCoordinate) { + if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell; } $this->storeCurrentCell(); // Return null if requested entry doesn't exist in collection - if (!$this->has($pCoord)) { + if (!$this->has($cellCoordinate)) { return null; } // Check if the entry that has been requested actually exists - $cell = $this->cache->get($this->cachePrefix . $pCoord); + $cell = $this->cache->get($this->cachePrefix . $cellCoordinate); if ($cell === null) { - throw new PhpSpreadsheetException("Cell entry {$pCoord} no longer exists in cache. This probably means that the cache was cleared by someone else."); + throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else."); } // Set current entry to the requested entry - $this->currentCoordinate = $pCoord; + $this->currentCoordinate = $cellCoordinate; $this->currentCell = $cell; // Re-attach this as the cell's parent $this->currentCell->attach($this); @@ -467,7 +436,7 @@ public function get($pCoord) /** * Clear the cell collection and disconnect from our parent. */ - public function unsetWorksheetCells() + public function unsetWorksheetCells(): void { if ($this->currentCell !== null) { $this->currentCell->detach(); @@ -495,7 +464,7 @@ public function __destruct() /** * Returns all known cache keys. * - * @return \Generator|string[] + * @return Generator|string[] */ private function getAllCacheKeys() { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php index 7f34c231..26f18dfc 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php @@ -10,12 +10,12 @@ abstract class CellsFactory /** * Initialise the cache storage. * - * @param Worksheet $parent Enable cell caching for this worksheet + * @param Worksheet $worksheet Enable cell caching for this worksheet * * @return Cells * */ - public static function getInstance(Worksheet $parent) + public static function getInstance(Worksheet $worksheet) { - return new Cells($parent, Settings::getCache()); + return new Cells($worksheet, Settings::getCache()); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php index a32551b0..2690ab7d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Collection; +use DateInterval; use Psr\SimpleCache\CacheInterface; /** @@ -14,6 +15,9 @@ class Memory implements CacheInterface { private $cache = []; + /** + * @return bool + */ public function clear() { $this->cache = []; @@ -21,6 +25,11 @@ public function clear() return true; } + /** + * @param string $key + * + * @return bool + */ public function delete($key) { unset($this->cache[$key]); @@ -28,6 +37,11 @@ public function delete($key) return true; } + /** + * @param iterable $keys + * + * @return bool + */ public function deleteMultiple($keys) { foreach ($keys as $key) { @@ -37,6 +51,12 @@ public function deleteMultiple($keys) return true; } + /** + * @param string $key + * @param mixed $default + * + * @return mixed + */ public function get($key, $default = null) { if ($this->has($key)) { @@ -46,6 +66,12 @@ public function get($key, $default = null) return $default; } + /** + * @param iterable $keys + * @param mixed $default + * + * @return iterable + */ public function getMultiple($keys, $default = null) { $results = []; @@ -56,11 +82,23 @@ public function getMultiple($keys, $default = null) return $results; } + /** + * @param string $key + * + * @return bool + */ public function has($key) { return array_key_exists($key, $this->cache); } + /** + * @param string $key + * @param mixed $value + * @param null|DateInterval|int $ttl + * + * @return bool + */ public function set($key, $value, $ttl = null) { $this->cache[$key] = $value; @@ -68,6 +106,12 @@ public function set($key, $value, $ttl = null) return true; } + /** + * @param iterable $values + * @param null|DateInterval|int $ttl + * + * @return bool + */ public function setMultiple($values, $ttl = null) { foreach ($values as $key => $value) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php index 8041ddaf..abadc7df 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php @@ -2,7 +2,13 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Helper\Size; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; +use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Color; +use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; class Comment implements IComparable { @@ -58,7 +64,7 @@ class Comment implements IComparable /** * Comment fill color. * - * @var Style\Color + * @var Color */ private $fillColor; @@ -69,6 +75,13 @@ class Comment implements IComparable */ private $alignment; + /** + * Background image in comment. + * + * @var Drawing + */ + private $backgroundImage; + /** * Create a new Comment. */ @@ -77,28 +90,23 @@ public function __construct() // Initialise variables $this->author = 'Author'; $this->text = new RichText(); - $this->fillColor = new Style\Color('FFFFFFE1'); - $this->alignment = Style\Alignment::HORIZONTAL_GENERAL; + $this->fillColor = new Color('FFFFFFE1'); + $this->alignment = Alignment::HORIZONTAL_GENERAL; + $this->backgroundImage = new Drawing(); } /** * Get Author. - * - * @return string */ - public function getAuthor() + public function getAuthor(): string { return $this->author; } /** * Set Author. - * - * @param string $author - * - * @return $this */ - public function setAuthor($author) + public function setAuthor(string $author): self { $this->author = $author; @@ -107,166 +115,146 @@ public function setAuthor($author) /** * Get Rich text comment. - * - * @return RichText */ - public function getText() + public function getText(): RichText { return $this->text; } /** * Set Rich text comment. - * - * @param RichText $pValue - * - * @return $this */ - public function setText(RichText $pValue) + public function setText(RichText $text): self { - $this->text = $pValue; + $this->text = $text; return $this; } /** * Get comment width (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getWidth() + public function getWidth(): string { return $this->width; } /** - * Set comment width (CSS style, i.e. XXpx or YYpt). - * - * @param string $width - * - * @return $this + * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - public function setWidth($width) + public function setWidth(string $width): self { - $this->width = $width; + $width = new Size($width); + if ($width->valid()) { + $this->width = (string) $width; + } return $this; } /** * Get comment height (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getHeight() + public function getHeight(): string { return $this->height; } /** - * Set comment height (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - public function setHeight($value) + public function setHeight(string $height): self { - $this->height = $value; + $height = new Size($height); + if ($height->valid()) { + $this->height = (string) $height; + } return $this; } /** * Get left margin (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getMarginLeft() + public function getMarginLeft(): string { return $this->marginLeft; } /** - * Set left margin (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - public function setMarginLeft($value) + public function setMarginLeft(string $margin): self { - $this->marginLeft = $value; + $margin = new Size($margin); + if ($margin->valid()) { + $this->marginLeft = (string) $margin; + } return $this; } /** * Get top margin (CSS style, i.e. XXpx or YYpt). - * - * @return string */ - public function getMarginTop() + public function getMarginTop(): string { return $this->marginTop; } /** - * Set top margin (CSS style, i.e. XXpx or YYpt). - * - * @param string $value - * - * @return $this + * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ - public function setMarginTop($value) + public function setMarginTop(string $margin): self { - $this->marginTop = $value; + $margin = new Size($margin); + if ($margin->valid()) { + $this->marginTop = (string) $margin; + } return $this; } /** * Is the comment visible by default? - * - * @return bool */ - public function getVisible() + public function getVisible(): bool { return $this->visible; } /** * Set comment default visibility. - * - * @param bool $value - * - * @return $this */ - public function setVisible($value) + public function setVisible(bool $visibility): self + { + $this->visible = $visibility; + + return $this; + } + + /** + * Set fill color. + */ + public function setFillColor(Color $color): self { - $this->visible = $value; + $this->fillColor = $color; return $this; } /** * Get fill color. - * - * @return Style\Color */ - public function getFillColor() + public function getFillColor(): Color { return $this->fillColor; } /** * Set Alignment. - * - * @param string $alignment see Style\Alignment::HORIZONTAL_* - * - * @return $this */ - public function setAlignment($alignment) + public function setAlignment(string $alignment): self { $this->alignment = $alignment; @@ -275,20 +263,16 @@ public function setAlignment($alignment) /** * Get Alignment. - * - * @return string */ - public function getAlignment() + public function getAlignment(): string { return $this->alignment; } /** * Get hash code. - * - * @return string Hash code */ - public function getHashCode() + public function getHashCode(): string { return md5( $this->author . @@ -300,6 +284,7 @@ public function getHashCode() ($this->visible ? 1 : 0) . $this->fillColor->getHashCode() . $this->alignment . + ($this->hasBackgroundImage() ? $this->backgroundImage->getHashCode() : '') . __CLASS__ ); } @@ -321,11 +306,57 @@ public function __clone() /** * Convert to string. - * - * @return string */ - public function __toString() + public function __toString(): string { return $this->text->getPlainText(); } + + /** + * Check is background image exists. + */ + public function hasBackgroundImage(): bool + { + $path = $this->backgroundImage->getPath(); + + if (empty($path)) { + return false; + } + + return getimagesize($path) !== false; + } + + /** + * Returns background image. + */ + public function getBackgroundImage(): Drawing + { + return $this->backgroundImage; + } + + /** + * Sets background image. + */ + public function setBackgroundImage(Drawing $objDrawing): self + { + if (!array_key_exists($objDrawing->getType(), Drawing::IMAGE_TYPES_CONVERTION_MAP)) { + throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + } + $this->backgroundImage = $objDrawing; + + return $this; + } + + /** + * Sets size of comment as size of background image. + */ + public function setSizeAsBackgroundImage(): self + { + if ($this->hasBackgroundImage()) { + $this->setWidth(SharedDrawing::pixelsToPoints($this->backgroundImage->getWidth()) . 'pt'); + $this->setHeight(SharedDrawing::pixelsToPoints($this->backgroundImage->getHeight()) . 'pt'); + } + + return $this; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php new file mode 100644 index 00000000..3b874b43 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php @@ -0,0 +1,272 @@ +worksheet). + * + * @var bool + */ + protected $localOnly; + + /** + * Scope. + * + * @var Worksheet + */ + protected $scope; + + /** + * Whether this is a named range or a named formula. + * + * @var bool + */ + protected $isFormula; + + /** + * Create a new Defined Name. + */ + public function __construct( + string $name, + ?Worksheet $worksheet = null, + ?string $value = null, + bool $localOnly = false, + ?Worksheet $scope = null + ) { + if ($worksheet === null) { + $worksheet = $scope; + } + + // Set local members + $this->name = $name; + $this->worksheet = $worksheet; + $this->value = (string) $value; + $this->localOnly = $localOnly; + // If local only, then the scope will be set to worksheet unless a scope is explicitly set + $this->scope = ($localOnly === true) ? (($scope === null) ? $worksheet : $scope) : null; + // If the range string contains characters that aren't associated with the range definition (A-Z,1-9 + // for cell references, and $, or the range operators (colon comma or space), quotes and ! for + // worksheet names + // then this is treated as a named formula, and not a named range + $this->isFormula = self::testIfFormula($this->value); + } + + /** + * Create a new defined name, either a range or a formula. + */ + public static function createInstance( + string $name, + ?Worksheet $worksheet = null, + ?string $value = null, + bool $localOnly = false, + ?Worksheet $scope = null + ): self { + $value = (string) $value; + $isFormula = self::testIfFormula($value); + if ($isFormula) { + return new NamedFormula($name, $worksheet, $value, $localOnly, $scope); + } + + return new NamedRange($name, $worksheet, $value, $localOnly, $scope); + } + + public static function testIfFormula(string $value): bool + { + if (substr($value, 0, 1) === '=') { + $value = substr($value, 1); + } + + if (is_numeric($value)) { + return true; + } + + $segMatcher = false; + foreach (explode("'", $value) as $subVal) { + // Only test in alternate array entries (the non-quoted blocks) + if ( + ($segMatcher = !$segMatcher) && + (preg_match('/' . self::REGEXP_IDENTIFY_FORMULA . '/miu', $subVal)) + ) { + return true; + } + } + + return false; + } + + /** + * Get name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Set name. + */ + public function setName(string $name): self + { + if (!empty($name)) { + // Old title + $oldTitle = $this->name; + + // Re-attach + if ($this->worksheet !== null) { + $this->worksheet->getParent()->removeNamedRange($this->name, $this->worksheet); + } + $this->name = $name; + + if ($this->worksheet !== null) { + $this->worksheet->getParent()->addNamedRange($this); + } + + // New title + $newTitle = $this->name; + ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle); + } + + return $this; + } + + /** + * Get worksheet. + */ + public function getWorksheet(): ?Worksheet + { + return $this->worksheet; + } + + /** + * Set worksheet. + */ + public function setWorksheet(?Worksheet $worksheet): self + { + $this->worksheet = $worksheet; + + return $this; + } + + /** + * Get range or formula value. + */ + public function getValue(): string + { + return $this->value; + } + + /** + * Set range or formula value. + */ + public function setValue(string $value): self + { + $this->value = $value; + + return $this; + } + + /** + * Get localOnly. + */ + public function getLocalOnly(): bool + { + return $this->localOnly; + } + + /** + * Set localOnly. + */ + public function setLocalOnly(bool $localScope): self + { + $this->localOnly = $localScope; + $this->scope = $localScope ? $this->worksheet : null; + + return $this; + } + + /** + * Get scope. + */ + public function getScope(): ?Worksheet + { + return $this->scope; + } + + /** + * Set scope. + */ + public function setScope(?Worksheet $worksheet): self + { + $this->scope = $worksheet; + $this->localOnly = $worksheet !== null; + + return $this; + } + + /** + * Identify whether this is a named range or a named formula. + */ + public function isFormula(): bool + { + return $this->isFormula; + } + + /** + * Resolve a named range to a regular cell range or formula. + */ + public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self + { + if ($sheetName === '') { + $worksheet2 = $worksheet; + } else { + $worksheet2 = $worksheet->getParent()->getSheetByName($sheetName); + if ($worksheet2 === null) { + return null; + } + } + + return $worksheet->getParent()->getDefinedName($definedName, $worksheet2); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php index 58fd2ef6..2d461c59 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Properties.php @@ -2,15 +2,26 @@ namespace PhpOffice\PhpSpreadsheet\Document; +use DateTime; +use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; + class Properties { /** constants */ - const PROPERTY_TYPE_BOOLEAN = 'b'; - const PROPERTY_TYPE_INTEGER = 'i'; - const PROPERTY_TYPE_FLOAT = 'f'; - const PROPERTY_TYPE_DATE = 'd'; - const PROPERTY_TYPE_STRING = 's'; - const PROPERTY_TYPE_UNKNOWN = 'u'; + public const PROPERTY_TYPE_BOOLEAN = 'b'; + public const PROPERTY_TYPE_INTEGER = 'i'; + public const PROPERTY_TYPE_FLOAT = 'f'; + public const PROPERTY_TYPE_DATE = 'd'; + public const PROPERTY_TYPE_STRING = 's'; + public const PROPERTY_TYPE_UNKNOWN = 'u'; + + private const VALID_PROPERTY_TYPE_LIST = [ + self::PROPERTY_TYPE_BOOLEAN, + self::PROPERTY_TYPE_INTEGER, + self::PROPERTY_TYPE_FLOAT, + self::PROPERTY_TYPE_DATE, + self::PROPERTY_TYPE_STRING, + ]; /** * Creator. @@ -29,14 +40,14 @@ class Properties /** * Created. * - * @var int + * @var float|int */ private $created; /** * Modified. * - * @var int + * @var float|int */ private $modified; @@ -87,12 +98,12 @@ class Properties * * @var string */ - private $company = 'Microsoft Corporation'; + private $company = ''; /** * Custom Properties. * - * @var string + * @var array{value: mixed, type: string}[] */ private $customProperties = []; @@ -103,16 +114,14 @@ public function __construct() { // Initialise values $this->lastModifiedBy = $this->creator; - $this->created = time(); - $this->modified = time(); + $this->created = self::intOrFloatTimestamp(null); + $this->modified = $this->created; } /** * Get Creator. - * - * @return string */ - public function getCreator() + public function getCreator(): string { return $this->creator; } @@ -120,11 +129,9 @@ public function getCreator() /** * Set Creator. * - * @param string $creator - * * @return $this */ - public function setCreator($creator) + public function setCreator(string $creator): self { $this->creator = $creator; @@ -133,10 +140,8 @@ public function setCreator($creator) /** * Get Last Modified By. - * - * @return string */ - public function getLastModifiedBy() + public function getLastModifiedBy(): string { return $this->lastModifiedBy; } @@ -144,21 +149,42 @@ public function getLastModifiedBy() /** * Set Last Modified By. * - * @param string $pValue - * * @return $this */ - public function setLastModifiedBy($pValue) + public function setLastModifiedBy(string $modifiedBy): self { - $this->lastModifiedBy = $pValue; + $this->lastModifiedBy = $modifiedBy; return $this; } + /** + * @param null|float|int|string $timestamp + * + * @return float|int + */ + private static function intOrFloatTimestamp($timestamp) + { + if ($timestamp === null) { + $timestamp = (float) (new DateTime())->format('U'); + } elseif (is_string($timestamp)) { + if (is_numeric($timestamp)) { + $timestamp = (float) $timestamp; + } else { + $timestamp = preg_replace('/[.][0-9]*$/', '', $timestamp) ?? ''; + $timestamp = preg_replace('/^(\\d{4})- (\\d)/', '$1-0$2', $timestamp) ?? ''; + $timestamp = preg_replace('/^(\\d{4}-\\d{2})- (\\d)/', '$1-0$2', $timestamp) ?? ''; + $timestamp = (float) (new DateTime($timestamp))->format('U'); + } + } + + return IntOrFloat::evaluate($timestamp); + } + /** * Get Created. * - * @return int + * @return float|int */ public function getCreated() { @@ -168,23 +194,13 @@ public function getCreated() /** * Set Created. * - * @param int|string $time + * @param null|float|int|string $timestamp * * @return $this */ - public function setCreated($time) + public function setCreated($timestamp): self { - if ($time === null) { - $time = time(); - } elseif (is_string($time)) { - if (is_numeric($time)) { - $time = (int) $time; - } else { - $time = strtotime($time); - } - } - - $this->created = $time; + $this->created = self::intOrFloatTimestamp($timestamp); return $this; } @@ -192,7 +208,7 @@ public function setCreated($time) /** * Get Modified. * - * @return int + * @return float|int */ public function getModified() { @@ -202,33 +218,21 @@ public function getModified() /** * Set Modified. * - * @param int|string $time + * @param null|float|int|string $timestamp * * @return $this */ - public function setModified($time) + public function setModified($timestamp): self { - if ($time === null) { - $time = time(); - } elseif (is_string($time)) { - if (is_numeric($time)) { - $time = (int) $time; - } else { - $time = strtotime($time); - } - } - - $this->modified = $time; + $this->modified = self::intOrFloatTimestamp($timestamp); return $this; } /** * Get Title. - * - * @return string */ - public function getTitle() + public function getTitle(): string { return $this->title; } @@ -236,11 +240,9 @@ public function getTitle() /** * Set Title. * - * @param string $title - * * @return $this */ - public function setTitle($title) + public function setTitle(string $title): self { $this->title = $title; @@ -249,10 +251,8 @@ public function setTitle($title) /** * Get Description. - * - * @return string */ - public function getDescription() + public function getDescription(): string { return $this->description; } @@ -260,11 +260,9 @@ public function getDescription() /** * Set Description. * - * @param string $description - * * @return $this */ - public function setDescription($description) + public function setDescription(string $description): self { $this->description = $description; @@ -273,10 +271,8 @@ public function setDescription($description) /** * Get Subject. - * - * @return string */ - public function getSubject() + public function getSubject(): string { return $this->subject; } @@ -284,11 +280,9 @@ public function getSubject() /** * Set Subject. * - * @param string $subject - * * @return $this */ - public function setSubject($subject) + public function setSubject(string $subject): self { $this->subject = $subject; @@ -297,10 +291,8 @@ public function setSubject($subject) /** * Get Keywords. - * - * @return string */ - public function getKeywords() + public function getKeywords(): string { return $this->keywords; } @@ -308,11 +300,9 @@ public function getKeywords() /** * Set Keywords. * - * @param string $keywords - * * @return $this */ - public function setKeywords($keywords) + public function setKeywords(string $keywords): self { $this->keywords = $keywords; @@ -321,10 +311,8 @@ public function setKeywords($keywords) /** * Get Category. - * - * @return string */ - public function getCategory() + public function getCategory(): string { return $this->category; } @@ -332,11 +320,9 @@ public function getCategory() /** * Set Category. * - * @param string $category - * * @return $this */ - public function setCategory($category) + public function setCategory(string $category): self { $this->category = $category; @@ -345,10 +331,8 @@ public function setCategory($category) /** * Get Company. - * - * @return string */ - public function getCompany() + public function getCompany(): string { return $this->company; } @@ -356,11 +340,9 @@ public function getCompany() /** * Set Company. * - * @param string $company - * * @return $this */ - public function setCompany($company) + public function setCompany(string $company): self { $this->company = $company; @@ -369,10 +351,8 @@ public function setCompany($company) /** * Get Manager. - * - * @return string */ - public function getManager() + public function getManager(): string { return $this->manager; } @@ -380,11 +360,9 @@ public function getManager() /** * Set Manager. * - * @param string $manager - * * @return $this */ - public function setManager($manager) + public function setManager(string $manager): self { $this->manager = $manager; @@ -394,57 +372,66 @@ public function setManager($manager) /** * Get a List of Custom Property Names. * - * @return array of string + * @return string[] */ - public function getCustomProperties() + public function getCustomProperties(): array { return array_keys($this->customProperties); } /** * Check if a Custom Property is defined. - * - * @param string $propertyName - * - * @return bool */ - public function isCustomPropertySet($propertyName) + public function isCustomPropertySet(string $propertyName): bool { - return isset($this->customProperties[$propertyName]); + return array_key_exists($propertyName, $this->customProperties); } /** * Get a Custom Property Value. * - * @param string $propertyName - * * @return mixed */ - public function getCustomPropertyValue($propertyName) + public function getCustomPropertyValue(string $propertyName) { if (isset($this->customProperties[$propertyName])) { return $this->customProperties[$propertyName]['value']; } + + return null; } /** * Get a Custom Property Type. * - * @param string $propertyName - * - * @return string + * @return null|string */ - public function getCustomPropertyType($propertyName) + public function getCustomPropertyType(string $propertyName) { - if (isset($this->customProperties[$propertyName])) { - return $this->customProperties[$propertyName]['type']; + return $this->customProperties[$propertyName]['type'] ?? null; + } + + /** + * @param mixed $propertyValue + */ + private function identifyPropertyType($propertyValue): string + { + if (is_float($propertyValue)) { + return self::PROPERTY_TYPE_FLOAT; } + if (is_int($propertyValue)) { + return self::PROPERTY_TYPE_INTEGER; + } + if (is_bool($propertyValue)) { + return self::PROPERTY_TYPE_BOOLEAN; + } + + return self::PROPERTY_TYPE_STRING; } /** * Set a Custom Property. * - * @param string $propertyName * @param mixed $propertyValue * @param string $propertyType * 'i' : Integer @@ -455,175 +442,96 @@ public function getCustomPropertyType($propertyName) * * @return $this */ - public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null) - { - if (($propertyType === null) || (!in_array($propertyType, [self::PROPERTY_TYPE_INTEGER, - self::PROPERTY_TYPE_FLOAT, - self::PROPERTY_TYPE_STRING, - self::PROPERTY_TYPE_DATE, - self::PROPERTY_TYPE_BOOLEAN, ]))) { - if ($propertyValue === null) { - $propertyType = self::PROPERTY_TYPE_STRING; - } elseif (is_float($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_FLOAT; - } elseif (is_int($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_INTEGER; - } elseif (is_bool($propertyValue)) { - $propertyType = self::PROPERTY_TYPE_BOOLEAN; - } else { - $propertyType = self::PROPERTY_TYPE_STRING; - } + public function setCustomProperty(string $propertyName, $propertyValue = '', $propertyType = null): self + { + if (($propertyType === null) || (!in_array($propertyType, self::VALID_PROPERTY_TYPE_LIST))) { + $propertyType = $this->identifyPropertyType($propertyValue); } - $this->customProperties[$propertyName] = [ - 'value' => $propertyValue, - 'type' => $propertyType, - ]; + if (!is_object($propertyValue)) { + $this->customProperties[$propertyName] = [ + 'value' => self::convertProperty($propertyValue, $propertyType), + 'type' => $propertyType, + ]; + } return $this; } - /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. + private const PROPERTY_TYPE_ARRAY = [ + 'i' => self::PROPERTY_TYPE_INTEGER, // Integer + 'i1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Signed Integer + 'i2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Signed Integer + 'i4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Signed Integer + 'i8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Signed Integer + 'int' => self::PROPERTY_TYPE_INTEGER, // Integer + 'ui1' => self::PROPERTY_TYPE_INTEGER, // 1-Byte Unsigned Integer + 'ui2' => self::PROPERTY_TYPE_INTEGER, // 2-Byte Unsigned Integer + 'ui4' => self::PROPERTY_TYPE_INTEGER, // 4-Byte Unsigned Integer + 'ui8' => self::PROPERTY_TYPE_INTEGER, // 8-Byte Unsigned Integer + 'uint' => self::PROPERTY_TYPE_INTEGER, // Unsigned Integer + 'f' => self::PROPERTY_TYPE_FLOAT, // Real Number + 'r4' => self::PROPERTY_TYPE_FLOAT, // 4-Byte Real Number + 'r8' => self::PROPERTY_TYPE_FLOAT, // 8-Byte Real Number + 'decimal' => self::PROPERTY_TYPE_FLOAT, // Decimal + 's' => self::PROPERTY_TYPE_STRING, // String + 'empty' => self::PROPERTY_TYPE_STRING, // Empty + 'null' => self::PROPERTY_TYPE_STRING, // Null + 'lpstr' => self::PROPERTY_TYPE_STRING, // LPSTR + 'lpwstr' => self::PROPERTY_TYPE_STRING, // LPWSTR + 'bstr' => self::PROPERTY_TYPE_STRING, // Basic String + 'd' => self::PROPERTY_TYPE_DATE, // Date and Time + 'date' => self::PROPERTY_TYPE_DATE, // Date and Time + 'filetime' => self::PROPERTY_TYPE_DATE, // File Time + 'b' => self::PROPERTY_TYPE_BOOLEAN, // Boolean + 'bool' => self::PROPERTY_TYPE_BOOLEAN, // Boolean + ]; + + private const SPECIAL_TYPES = [ + 'empty' => '', + 'null' => null, + ]; + + /** + * Convert property to form desired by Excel. + * + * @param mixed $propertyValue + * + * @return mixed */ - public function __clone() + public static function convertProperty($propertyValue, string $propertyType) { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } + return self::SPECIAL_TYPES[$propertyType] ?? self::convertProperty2($propertyValue, $propertyType); } - public static function convertProperty($propertyValue, $propertyType) + /** + * Convert property to form desired by Excel. + * + * @param mixed $propertyValue + * + * @return mixed + */ + private static function convertProperty2($propertyValue, string $type) { + $propertyType = self::convertPropertyType($type); switch ($propertyType) { - case 'empty': // Empty - return ''; - - break; - case 'null': // Null - return null; - - break; - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer - return (int) $propertyValue; - - break; - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer - return abs((int) $propertyValue); - - break; - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal - return (float) $propertyValue; + case self::PROPERTY_TYPE_INTEGER: + $intValue = (int) $propertyValue; - break; - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - return $propertyValue; - - break; - case 'date': // Date and Time - case 'filetime': // File Time - return strtotime($propertyValue); - - break; - case 'bool': // Boolean - return $propertyValue == 'true'; - - break; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data + return ($type[0] === 'u') ? abs($intValue) : $intValue; + case self::PROPERTY_TYPE_FLOAT: + return (float) $propertyValue; + case self::PROPERTY_TYPE_DATE: + return self::intOrFloatTimestamp($propertyValue); + case self::PROPERTY_TYPE_BOOLEAN: + return is_bool($propertyValue) ? $propertyValue : ($propertyValue === 'true'); + default: // includes string return $propertyValue; - - break; } - - return $propertyValue; } - public static function convertPropertyType($propertyType) + public static function convertPropertyType(string $propertyType): string { - switch ($propertyType) { - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer - return self::PROPERTY_TYPE_INTEGER; - - break; - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal - return self::PROPERTY_TYPE_FLOAT; - - break; - case 'empty': // Empty - case 'null': // Null - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - return self::PROPERTY_TYPE_STRING; - - break; - case 'date': // Date and Time - case 'filetime': // File Time - return self::PROPERTY_TYPE_DATE; - - break; - case 'bool': // Boolean - return self::PROPERTY_TYPE_BOOLEAN; - - break; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return self::PROPERTY_TYPE_UNKNOWN; - - break; - } - - return self::PROPERTY_TYPE_UNKNOWN; + return self::PROPERTY_TYPE_ARRAY[$propertyType] ?? self::PROPERTY_TYPE_UNKNOWN; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php index cef3db8c..279aed43 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Document/Security.php @@ -50,94 +50,57 @@ public function __construct() /** * Is some sort of document security enabled? - * - * @return bool */ - public function isSecurityEnabled() + public function isSecurityEnabled(): bool { return $this->lockRevision || $this->lockStructure || $this->lockWindows; } - /** - * Get LockRevision. - * - * @return bool - */ - public function getLockRevision() + public function getLockRevision(): bool { return $this->lockRevision; } - /** - * Set LockRevision. - * - * @param bool $pValue - * - * @return $this - */ - public function setLockRevision($pValue) + public function setLockRevision(?bool $locked): self { - $this->lockRevision = $pValue; + if ($locked !== null) { + $this->lockRevision = $locked; + } return $this; } - /** - * Get LockStructure. - * - * @return bool - */ - public function getLockStructure() + public function getLockStructure(): bool { return $this->lockStructure; } - /** - * Set LockStructure. - * - * @param bool $pValue - * - * @return $this - */ - public function setLockStructure($pValue) + public function setLockStructure(?bool $locked): self { - $this->lockStructure = $pValue; + if ($locked !== null) { + $this->lockStructure = $locked; + } return $this; } - /** - * Get LockWindows. - * - * @return bool - */ - public function getLockWindows() + public function getLockWindows(): bool { return $this->lockWindows; } - /** - * Set LockWindows. - * - * @param bool $pValue - * - * @return $this - */ - public function setLockWindows($pValue) + public function setLockWindows(?bool $locked): self { - $this->lockWindows = $pValue; + if ($locked !== null) { + $this->lockWindows = $locked; + } return $this; } - /** - * Get RevisionsPassword (hashed). - * - * @return string - */ - public function getRevisionsPassword() + public function getRevisionsPassword(): string { return $this->revisionsPassword; } @@ -145,27 +108,24 @@ public function getRevisionsPassword() /** * Set RevisionsPassword. * - * @param string $pValue - * @param bool $pAlreadyHashed If the password has already been hashed, set this to true + * @param string $password + * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ - public function setRevisionsPassword($pValue, $pAlreadyHashed = false) + public function setRevisionsPassword(?string $password, bool $alreadyHashed = false) { - if (!$pAlreadyHashed) { - $pValue = PasswordHasher::hashPassword($pValue); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); + } + $this->revisionsPassword = $password; } - $this->revisionsPassword = $pValue; return $this; } - /** - * Get WorkbookPassword (hashed). - * - * @return string - */ - public function getWorkbookPassword() + public function getWorkbookPassword(): string { return $this->workbookPassword; } @@ -173,33 +133,20 @@ public function getWorkbookPassword() /** * Set WorkbookPassword. * - * @param string $pValue - * @param bool $pAlreadyHashed If the password has already been hashed, set this to true + * @param string $password + * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ - public function setWorkbookPassword($pValue, $pAlreadyHashed = false) + public function setWorkbookPassword(?string $password, bool $alreadyHashed = false) { - if (!$pAlreadyHashed) { - $pValue = PasswordHasher::hashPassword($pValue); + if ($password !== null) { + if (!$alreadyHashed) { + $password = PasswordHasher::hashPassword($password); + } + $this->workbookPassword = $password; } - $this->workbookPassword = $pValue; return $this; } - - /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. - */ - public function __clone() - { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } - } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php deleted file mode 100644 index de6f313f..00000000 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DocumentGenerator.php +++ /dev/null @@ -1,111 +0,0 @@ - $category) { - $result .= "\n"; - $result .= "## {$categoryConstant}\n"; - $result .= "\n"; - $lengths = [20, 42]; - $result .= self::tableRow($lengths, ['Excel Function', 'PhpSpreadsheet Function']) . "\n"; - $result .= self::tableRow($lengths, null) . "\n"; - foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) { - if ($category === $functionInfo['category']) { - $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']); - $result .= self::tableRow($lengths, [$excelFunction, $phpFunction]) . "\n"; - } - } - } - - return $result; - } - - /** - * @throws ReflectionException - * - * @return array - */ - private static function getCategories(): array - { - return (new ReflectionClass(Category::class))->getConstants(); - } - - private static function tableRow(array $lengths, array $values = null): string - { - $result = ''; - foreach (array_map(null, $lengths, $values ?? []) as $i => [$length, $value]) { - $pad = $value === null ? '-' : ' '; - if ($i > 0) { - $result .= '|' . $pad; - } - $result .= str_pad($value ?? '', $length, $pad); - } - - return rtrim($result, ' '); - } - - private static function getPhpSpreadsheetFunctionText($functionCall): string - { - if (is_string($functionCall)) { - return $functionCall; - } - if ($functionCall === [Functions::class, 'DUMMY']) { - return '**Not yet Implemented**'; - } - if (is_array($functionCall)) { - return "\\{$functionCall[0]}::{$functionCall[1]}"; - } - - throw new UnexpectedValueException( - '$functionCall is of type ' . gettype($functionCall) . '. string or array expected' - ); - } - - /** - * @param array[] $phpSpreadsheetFunctions - * - * @throws ReflectionException - * - * @return string - */ - public static function generateFunctionListByName(array $phpSpreadsheetFunctions): string - { - $categoryConstants = array_flip(self::getCategories()); - $result = "# Function list by name\n"; - $lastAlphabet = null; - foreach ($phpSpreadsheetFunctions as $excelFunction => $functionInfo) { - $lengths = [20, 31, 42]; - if ($lastAlphabet !== $excelFunction[0]) { - $lastAlphabet = $excelFunction[0]; - $result .= "\n"; - $result .= "## {$lastAlphabet}\n"; - $result .= "\n"; - $result .= self::tableRow($lengths, ['Excel Function', 'Category', 'PhpSpreadsheet Function']) . "\n"; - $result .= self::tableRow($lengths, null) . "\n"; - } - $category = $categoryConstants[$functionInfo['category']]; - $phpFunction = self::getPhpSpreadsheetFunctionText($functionInfo['functionCall']); - $result .= self::tableRow($lengths, [$excelFunction, $category, $phpFunction]) . "\n"; - } - - return $result; - } -} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php index 4e8f0a5c..59209eed 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php @@ -2,52 +2,51 @@ namespace PhpOffice\PhpSpreadsheet; +/** + * @template T of IComparable + */ class HashTable { /** * HashTable elements. * - * @var IComparable[] + * @var array */ protected $items = []; /** * HashTable key map. * - * @var string[] + * @var array */ protected $keyMap = []; /** - * Create a new \PhpOffice\PhpSpreadsheet\HashTable. + * Create a new HashTable. * - * @param IComparable[] $pSource Optional source array to create HashTable from - * - * @throws Exception + * @param T[] $source Optional source array to create HashTable from */ - public function __construct($pSource = null) + public function __construct($source = null) { - if ($pSource !== null) { + if ($source !== null) { // Create HashTable - $this->addFromSource($pSource); + $this->addFromSource($source); } } /** * Add HashTable items from source. * - * @param IComparable[] $pSource Source array to create HashTable from - * - * @throws Exception + * @param T[] $source Source array to create HashTable from */ - public function addFromSource(array $pSource = null) + public function addFromSource(?array $source = null): void { // Check if an array was passed - if ($pSource == null) { + if ($source === null) { return; } - foreach ($pSource as $item) { + foreach ($source as $item) { $this->add($item); } } @@ -55,13 +54,13 @@ public function addFromSource(array $pSource = null) /** * Add HashTable item. * - * @param IComparable $pSource Item to add + * @param T $source Item to add */ - public function add(IComparable $pSource) + public function add(IComparable $source): void { - $hash = $pSource->getHashCode(); + $hash = $source->getHashCode(); if (!isset($this->items[$hash])) { - $this->items[$hash] = $pSource; + $this->items[$hash] = $source; $this->keyMap[count($this->items) - 1] = $hash; } } @@ -69,11 +68,11 @@ public function add(IComparable $pSource) /** * Remove HashTable item. * - * @param IComparable $pSource Item to remove + * @param T $source Item to remove */ - public function remove(IComparable $pSource) + public function remove(IComparable $source): void { - $hash = $pSource->getHashCode(); + $hash = $source->getHashCode(); if (isset($this->items[$hash])) { unset($this->items[$hash]); @@ -94,7 +93,7 @@ public function remove(IComparable $pSource) /** * Clear HashTable. */ - public function clear() + public function clear(): void { $this->items = []; $this->keyMap = []; @@ -113,26 +112,22 @@ public function count() /** * Get index for hash code. * - * @param string $pHashCode - * - * @return int Index + * @return false|int Index */ - public function getIndexForHashCode($pHashCode) + public function getIndexForHashCode(string $hashCode) { - return array_search($pHashCode, $this->keyMap); + return array_search($hashCode, $this->keyMap, true); } /** * Get by index. * - * @param int $pIndex - * - * @return IComparable + * @return null|T */ - public function getByIndex($pIndex) + public function getByIndex(int $index) { - if (isset($this->keyMap[$pIndex])) { - return $this->getByHashCode($this->keyMap[$pIndex]); + if (isset($this->keyMap[$index])) { + return $this->getByHashCode($this->keyMap[$index]); } return null; @@ -141,14 +136,12 @@ public function getByIndex($pIndex) /** * Get by hashcode. * - * @param string $pHashCode - * - * @return IComparable + * @return null|T */ - public function getByHashCode($pHashCode) + public function getByHashCode(string $hashCode) { - if (isset($this->items[$pHashCode])) { - return $this->items[$pHashCode]; + if (isset($this->items[$hashCode])) { + return $this->items[$hashCode]; } return null; @@ -157,7 +150,7 @@ public function getByHashCode($pHashCode) /** * HashTable to array. * - * @return IComparable[] + * @return T[] */ public function toArray() { @@ -171,8 +164,15 @@ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; + // each member of this class is an array + if (is_array($value)) { + $array1 = $value; + foreach ($array1 as $key1 => $value1) { + if (is_object($value1)) { + $array1[$key1] = clone $value1; + } + } + $this->$key = $array1; } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php new file mode 100644 index 00000000..4e3e6680 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Dimension.php @@ -0,0 +1,103 @@ + 96.0 / 2.54, + self::UOM_MILLIMETERS => 96.0 / 25.4, + self::UOM_INCHES => 96.0, + self::UOM_PIXELS => 1.0, + self::UOM_POINTS => 96.0 / 72, + self::UOM_PICA => 96.0 * 12 / 72, + ]; + + /** + * Based on a standard column width of 8.54 units in MS Excel. + */ + const RELATIVE_UNITS = [ + 'em' => 10.0 / 8.54, + 'ex' => 10.0 / 8.54, + 'ch' => 10.0 / 8.54, + 'rem' => 10.0 / 8.54, + 'vw' => 8.54, + 'vh' => 8.54, + 'vmin' => 8.54, + 'vmax' => 8.54, + '%' => 8.54 / 100, + ]; + + /** + * @var float|int If this is a width, then size is measured in pixels (if is set) + * or in Excel's default column width units if $unit is null. + * If this is a height, then size is measured in pixels () + * or in points () if $unit is null. + */ + protected $size; + + /** + * @var null|string + */ + protected $unit; + + public function __construct(string $dimension) + { + [$size, $unit] = sscanf($dimension, '%[1234567890.]%s'); + $unit = strtolower(trim($unit ?? '')); + + // If a UoM is specified, then convert the size to pixels for internal storage + if (isset(self::ABSOLUTE_UNITS[$unit])) { + $size *= self::ABSOLUTE_UNITS[$unit]; + $this->unit = self::UOM_PIXELS; + } elseif (isset(self::RELATIVE_UNITS[$unit])) { + $size *= self::RELATIVE_UNITS[$unit]; + $size = round($size, 4); + } + + $this->size = $size; + } + + public function width(): float + { + return (float) ($this->unit === null) + ? $this->size + : round(Drawing::pixelsToCellDimension((int) $this->size, new Font(false)), 4); + } + + public function height(): float + { + return (float) ($this->unit === null) + ? $this->size + : $this->toUnit(self::UOM_POINTS); + } + + public function toUnit(string $unitOfMeasure): float + { + $unitOfMeasure = strtolower($unitOfMeasure); + if (!array_key_exists($unitOfMeasure, self::ABSOLUTE_UNITS)) { + throw new Exception("{$unitOfMeasure} is not a vaid unit of measure"); + } + + $size = $this->size; + if ($this->unit === null) { + $size = Drawing::cellDimensionToPixels($size, new Font(false)); + } + + return $size / self::ABSOLUTE_UNITS[$unitOfMeasure]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php index eaf73028..4737379a 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Html.php @@ -593,7 +593,7 @@ class Html */ protected $richTextObject; - protected function initialise() + protected function initialise(): void { $this->face = $this->size = $this->color = null; $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; @@ -619,6 +619,7 @@ public function toRichTextObject($html) // Load the HTML file into the DOM object // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup $prefix = ''; + /** @scrutinizer ignore-unhandled */ @$dom->loadHTML($prefix . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // Discard excess white space $dom->preserveWhiteSpace = false; @@ -632,7 +633,7 @@ public function toRichTextObject($html) return $this->richTextObject; } - protected function cleanWhitespace() + protected function cleanWhitespace(): void { foreach ($this->richTextObject->getRichTextElements() as $key => $element) { $text = $element->getText(); @@ -646,7 +647,7 @@ protected function cleanWhitespace() } } - protected function buildTextRun() + protected function buildTextRun(): void { $text = $this->stringData; if (trim($text) === '') { @@ -684,22 +685,22 @@ protected function buildTextRun() $this->stringData = ''; } - protected function rgbToColour($rgb) + protected function rgbToColour(string $rgbValue): string { - preg_match_all('/\d+/', $rgb, $values); + preg_match_all('/\d+/', $rgbValue, $values); foreach ($values[0] as &$value) { $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); } - return implode($values[0]); + return implode('', $values[0]); } - protected function colourNameLookup($rgb) + public static function colourNameLookup(string $colorName): string { - return self::$colourMap[$rgb]; + return self::$colourMap[$colorName] ?? ''; } - protected function startFontTag($tag) + protected function startFontTag($tag): void { foreach ($tag->attributes as $attribute) { $attributeName = strtolower($attribute->name); @@ -711,7 +712,7 @@ protected function startFontTag($tag) } elseif (strpos(trim($attributeValue), '#') === 0) { $this->$attributeName = ltrim($attributeValue, '#'); } else { - $this->$attributeName = $this->colourNameLookup($attributeValue); + $this->$attributeName = static::colourNameLookup($attributeValue); } } else { $this->$attributeName = $attributeValue; @@ -719,103 +720,102 @@ protected function startFontTag($tag) } } - protected function endFontTag() + protected function endFontTag(): void { $this->face = $this->size = $this->color = null; } - protected function startBoldTag() + protected function startBoldTag(): void { $this->bold = true; } - protected function endBoldTag() + protected function endBoldTag(): void { $this->bold = false; } - protected function startItalicTag() + protected function startItalicTag(): void { $this->italic = true; } - protected function endItalicTag() + protected function endItalicTag(): void { $this->italic = false; } - protected function startUnderlineTag() + protected function startUnderlineTag(): void { $this->underline = true; } - protected function endUnderlineTag() + protected function endUnderlineTag(): void { $this->underline = false; } - protected function startSubscriptTag() + protected function startSubscriptTag(): void { $this->subscript = true; } - protected function endSubscriptTag() + protected function endSubscriptTag(): void { $this->subscript = false; } - protected function startSuperscriptTag() + protected function startSuperscriptTag(): void { $this->superscript = true; } - protected function endSuperscriptTag() + protected function endSuperscriptTag(): void { $this->superscript = false; } - protected function startStrikethruTag() + protected function startStrikethruTag(): void { $this->strikethrough = true; } - protected function endStrikethruTag() + protected function endStrikethruTag(): void { $this->strikethrough = false; } - protected function breakTag() + protected function breakTag(): void { $this->stringData .= "\n"; } - protected function parseTextNode(DOMText $textNode) + protected function parseTextNode(DOMText $textNode): void { $domText = preg_replace( '/\s+/u', ' ', - str_replace(["\r", "\n"], ' ', $textNode->nodeValue) + str_replace(["\r", "\n"], ' ', $textNode->nodeValue ?: '') ); $this->stringData .= $domText; $this->buildTextRun(); } /** - * @param DOMElement $element * @param string $callbackTag - * @param array $callbacks */ - protected function handleCallback(DOMElement $element, $callbackTag, array $callbacks) + protected function handleCallback(DOMElement $element, $callbackTag, array $callbacks): void { if (isset($callbacks[$callbackTag])) { $elementHandler = $callbacks[$callbackTag]; if (method_exists($this, $elementHandler)) { + /** @phpstan-ignore-next-line */ call_user_func([$this, $elementHandler], $element); } } } - protected function parseElementNode(DOMElement $element) + protected function parseElementNode(DOMElement $element): void { $callbackTag = strtolower($element->nodeName); $this->stack[] = $callbackTag; @@ -828,7 +828,7 @@ protected function parseElementNode(DOMElement $element) $this->handleCallback($element, $callbackTag, $this->endTagCallbacks); } - protected function parseElements(DOMNode $element) + protected function parseElements(DOMNode $element): void { foreach ($element->childNodes as $child) { if ($child instanceof DOMText) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Migrator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Migrator.php deleted file mode 100644 index 26d5fcea..00000000 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Migrator.php +++ /dev/null @@ -1,333 +0,0 @@ -from = array_keys($this->getMapping()); - $this->to = array_values($this->getMapping()); - } - - /** - * Return the ordered mapping from old PHPExcel class names to new PhpSpreadsheet one. - * - * @return string[] - */ - public function getMapping() - { - // Order matters here, we should have the deepest namespaces first (the most "unique" strings) - $classes = [ - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE\Blip::class, - 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer\SpContainer::class, - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE::class, - 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer::class, - 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer::class, - 'PHPExcel_Shared_OLE_PPS_File' => \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\File::class, - 'PHPExcel_Shared_OLE_PPS_Root' => \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS\Root::class, - 'PHPExcel_Worksheet_AutoFilter_Column_Rule' => \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::class, - 'PHPExcel_Writer_OpenDocument_Cell_Comment' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment::class, - 'PHPExcel_Calculation_Token_Stack' => \PhpOffice\PhpSpreadsheet\Calculation\Token\Stack::class, - 'PHPExcel_Chart_Renderer_jpgraph' => \PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class, - 'PHPExcel_Reader_Excel5_Escher' => \PhpOffice\PhpSpreadsheet\Reader\Xls\Escher::class, - 'PHPExcel_Reader_Excel5_MD5' => \PhpOffice\PhpSpreadsheet\Reader\Xls\MD5::class, - 'PHPExcel_Reader_Excel5_RC4' => \PhpOffice\PhpSpreadsheet\Reader\Xls\RC4::class, - 'PHPExcel_Reader_Excel2007_Chart' => \PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart::class, - 'PHPExcel_Reader_Excel2007_Theme' => \PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme::class, - 'PHPExcel_Shared_Escher_DgContainer' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer::class, - 'PHPExcel_Shared_Escher_DggContainer' => \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer::class, - 'CholeskyDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\CholeskyDecomposition::class, - 'EigenvalueDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\EigenvalueDecomposition::class, - 'PHPExcel_Shared_JAMA_LUDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\LUDecomposition::class, - 'PHPExcel_Shared_JAMA_Matrix' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\Matrix::class, - 'QRDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\QRDecomposition::class, - 'PHPExcel_Shared_JAMA_QRDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\QRDecomposition::class, - 'SingularValueDecomposition' => \PhpOffice\PhpSpreadsheet\Shared\JAMA\SingularValueDecomposition::class, - 'PHPExcel_Shared_OLE_ChainedBlockStream' => \PhpOffice\PhpSpreadsheet\Shared\OLE\ChainedBlockStream::class, - 'PHPExcel_Shared_OLE_PPS' => \PhpOffice\PhpSpreadsheet\Shared\OLE\PPS::class, - 'PHPExcel_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\BestFit::class, - 'PHPExcel_Exponential_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\ExponentialBestFit::class, - 'PHPExcel_Linear_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\LinearBestFit::class, - 'PHPExcel_Logarithmic_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\LogarithmicBestFit::class, - 'polynomialBestFit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\PolynomialBestFit::class, - 'PHPExcel_Polynomial_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\PolynomialBestFit::class, - 'powerBestFit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\PowerBestFit::class, - 'PHPExcel_Power_Best_Fit' => \PhpOffice\PhpSpreadsheet\Shared\Trend\PowerBestFit::class, - 'trendClass' => \PhpOffice\PhpSpreadsheet\Shared\Trend\Trend::class, - 'PHPExcel_Worksheet_AutoFilter_Column' => \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::class, - 'PHPExcel_Worksheet_Drawing_Shadow' => \PhpOffice\PhpSpreadsheet\Worksheet\Drawing\Shadow::class, - 'PHPExcel_Writer_OpenDocument_Content' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Content::class, - 'PHPExcel_Writer_OpenDocument_Meta' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Meta::class, - 'PHPExcel_Writer_OpenDocument_MetaInf' => \PhpOffice\PhpSpreadsheet\Writer\Ods\MetaInf::class, - 'PHPExcel_Writer_OpenDocument_Mimetype' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Mimetype::class, - 'PHPExcel_Writer_OpenDocument_Settings' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Settings::class, - 'PHPExcel_Writer_OpenDocument_Styles' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Styles::class, - 'PHPExcel_Writer_OpenDocument_Thumbnails' => \PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails::class, - 'PHPExcel_Writer_OpenDocument_WriterPart' => \PhpOffice\PhpSpreadsheet\Writer\Ods\WriterPart::class, - 'PHPExcel_Writer_PDF_Core' => \PhpOffice\PhpSpreadsheet\Writer\Pdf::class, - 'PHPExcel_Writer_PDF_DomPDF' => \PhpOffice\PhpSpreadsheet\Writer\Pdf\Dompdf::class, - 'PHPExcel_Writer_PDF_mPDF' => \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class, - 'PHPExcel_Writer_PDF_tcPDF' => \PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf::class, - 'PHPExcel_Writer_Excel5_BIFFwriter' => \PhpOffice\PhpSpreadsheet\Writer\Xls\BIFFwriter::class, - 'PHPExcel_Writer_Excel5_Escher' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Escher::class, - 'PHPExcel_Writer_Excel5_Font' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Font::class, - 'PHPExcel_Writer_Excel5_Parser' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser::class, - 'PHPExcel_Writer_Excel5_Workbook' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::class, - 'PHPExcel_Writer_Excel5_Worksheet' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet::class, - 'PHPExcel_Writer_Excel5_Xf' => \PhpOffice\PhpSpreadsheet\Writer\Xls\Xf::class, - 'PHPExcel_Writer_Excel2007_Chart' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart::class, - 'PHPExcel_Writer_Excel2007_Comments' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments::class, - 'PHPExcel_Writer_Excel2007_ContentTypes' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes::class, - 'PHPExcel_Writer_Excel2007_DocProps' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps::class, - 'PHPExcel_Writer_Excel2007_Drawing' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing::class, - 'PHPExcel_Writer_Excel2007_Rels' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::class, - 'PHPExcel_Writer_Excel2007_RelsRibbon' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon::class, - 'PHPExcel_Writer_Excel2007_RelsVBA' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA::class, - 'PHPExcel_Writer_Excel2007_StringTable' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable::class, - 'PHPExcel_Writer_Excel2007_Style' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style::class, - 'PHPExcel_Writer_Excel2007_Theme' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme::class, - 'PHPExcel_Writer_Excel2007_Workbook' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook::class, - 'PHPExcel_Writer_Excel2007_Worksheet' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::class, - 'PHPExcel_Writer_Excel2007_WriterPart' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart::class, - 'PHPExcel_CachedObjectStorage_CacheBase' => \PhpOffice\PhpSpreadsheet\Collection\Cells::class, - 'PHPExcel_CalcEngine_CyclicReferenceStack' => \PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack::class, - 'PHPExcel_CalcEngine_Logger' => \PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger::class, - 'PHPExcel_Calculation_Functions' => \PhpOffice\PhpSpreadsheet\Calculation\Functions::class, - 'PHPExcel_Calculation_Function' => \PhpOffice\PhpSpreadsheet\Calculation\Category::class, - 'PHPExcel_Calculation_Database' => \PhpOffice\PhpSpreadsheet\Calculation\Database::class, - 'PHPExcel_Calculation_DateTime' => \PhpOffice\PhpSpreadsheet\Calculation\DateTime::class, - 'PHPExcel_Calculation_Engineering' => \PhpOffice\PhpSpreadsheet\Calculation\Engineering::class, - 'PHPExcel_Calculation_Exception' => \PhpOffice\PhpSpreadsheet\Calculation\Exception::class, - 'PHPExcel_Calculation_ExceptionHandler' => \PhpOffice\PhpSpreadsheet\Calculation\ExceptionHandler::class, - 'PHPExcel_Calculation_Financial' => \PhpOffice\PhpSpreadsheet\Calculation\Financial::class, - 'PHPExcel_Calculation_FormulaParser' => \PhpOffice\PhpSpreadsheet\Calculation\FormulaParser::class, - 'PHPExcel_Calculation_FormulaToken' => \PhpOffice\PhpSpreadsheet\Calculation\FormulaToken::class, - 'PHPExcel_Calculation_Logical' => \PhpOffice\PhpSpreadsheet\Calculation\Logical::class, - 'PHPExcel_Calculation_LookupRef' => \PhpOffice\PhpSpreadsheet\Calculation\LookupRef::class, - 'PHPExcel_Calculation_MathTrig' => \PhpOffice\PhpSpreadsheet\Calculation\MathTrig::class, - 'PHPExcel_Calculation_Statistical' => \PhpOffice\PhpSpreadsheet\Calculation\Statistical::class, - 'PHPExcel_Calculation_TextData' => \PhpOffice\PhpSpreadsheet\Calculation\TextData::class, - 'PHPExcel_Cell_AdvancedValueBinder' => \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder::class, - 'PHPExcel_Cell_DataType' => \PhpOffice\PhpSpreadsheet\Cell\DataType::class, - 'PHPExcel_Cell_DataValidation' => \PhpOffice\PhpSpreadsheet\Cell\DataValidation::class, - 'PHPExcel_Cell_DefaultValueBinder' => \PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder::class, - 'PHPExcel_Cell_Hyperlink' => \PhpOffice\PhpSpreadsheet\Cell\Hyperlink::class, - 'PHPExcel_Cell_IValueBinder' => \PhpOffice\PhpSpreadsheet\Cell\IValueBinder::class, - 'PHPExcel_Chart_Axis' => \PhpOffice\PhpSpreadsheet\Chart\Axis::class, - 'PHPExcel_Chart_DataSeries' => \PhpOffice\PhpSpreadsheet\Chart\DataSeries::class, - 'PHPExcel_Chart_DataSeriesValues' => \PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues::class, - 'PHPExcel_Chart_Exception' => \PhpOffice\PhpSpreadsheet\Chart\Exception::class, - 'PHPExcel_Chart_GridLines' => \PhpOffice\PhpSpreadsheet\Chart\GridLines::class, - 'PHPExcel_Chart_Layout' => \PhpOffice\PhpSpreadsheet\Chart\Layout::class, - 'PHPExcel_Chart_Legend' => \PhpOffice\PhpSpreadsheet\Chart\Legend::class, - 'PHPExcel_Chart_PlotArea' => \PhpOffice\PhpSpreadsheet\Chart\PlotArea::class, - 'PHPExcel_Properties' => \PhpOffice\PhpSpreadsheet\Chart\Properties::class, - 'PHPExcel_Chart_Title' => \PhpOffice\PhpSpreadsheet\Chart\Title::class, - 'PHPExcel_DocumentProperties' => \PhpOffice\PhpSpreadsheet\Document\Properties::class, - 'PHPExcel_DocumentSecurity' => \PhpOffice\PhpSpreadsheet\Document\Security::class, - 'PHPExcel_Helper_HTML' => \PhpOffice\PhpSpreadsheet\Helper\Html::class, - 'PHPExcel_Reader_Abstract' => \PhpOffice\PhpSpreadsheet\Reader\BaseReader::class, - 'PHPExcel_Reader_CSV' => \PhpOffice\PhpSpreadsheet\Reader\Csv::class, - 'PHPExcel_Reader_DefaultReadFilter' => \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter::class, - 'PHPExcel_Reader_Excel2003XML' => \PhpOffice\PhpSpreadsheet\Reader\Xml::class, - 'PHPExcel_Reader_Exception' => \PhpOffice\PhpSpreadsheet\Reader\Exception::class, - 'PHPExcel_Reader_Gnumeric' => \PhpOffice\PhpSpreadsheet\Reader\Gnumeric::class, - 'PHPExcel_Reader_HTML' => \PhpOffice\PhpSpreadsheet\Reader\Html::class, - 'PHPExcel_Reader_IReadFilter' => \PhpOffice\PhpSpreadsheet\Reader\IReadFilter::class, - 'PHPExcel_Reader_IReader' => \PhpOffice\PhpSpreadsheet\Reader\IReader::class, - 'PHPExcel_Reader_OOCalc' => \PhpOffice\PhpSpreadsheet\Reader\Ods::class, - 'PHPExcel_Reader_SYLK' => \PhpOffice\PhpSpreadsheet\Reader\Slk::class, - 'PHPExcel_Reader_Excel5' => \PhpOffice\PhpSpreadsheet\Reader\Xls::class, - 'PHPExcel_Reader_Excel2007' => \PhpOffice\PhpSpreadsheet\Reader\Xlsx::class, - 'PHPExcel_RichText_ITextElement' => \PhpOffice\PhpSpreadsheet\RichText\ITextElement::class, - 'PHPExcel_RichText_Run' => \PhpOffice\PhpSpreadsheet\RichText\Run::class, - 'PHPExcel_RichText_TextElement' => \PhpOffice\PhpSpreadsheet\RichText\TextElement::class, - 'PHPExcel_Shared_CodePage' => \PhpOffice\PhpSpreadsheet\Shared\CodePage::class, - 'PHPExcel_Shared_Date' => \PhpOffice\PhpSpreadsheet\Shared\Date::class, - 'PHPExcel_Shared_Drawing' => \PhpOffice\PhpSpreadsheet\Shared\Drawing::class, - 'PHPExcel_Shared_Escher' => \PhpOffice\PhpSpreadsheet\Shared\Escher::class, - 'PHPExcel_Shared_File' => \PhpOffice\PhpSpreadsheet\Shared\File::class, - 'PHPExcel_Shared_Font' => \PhpOffice\PhpSpreadsheet\Shared\Font::class, - 'PHPExcel_Shared_OLE' => \PhpOffice\PhpSpreadsheet\Shared\OLE::class, - 'PHPExcel_Shared_OLERead' => \PhpOffice\PhpSpreadsheet\Shared\OLERead::class, - 'PHPExcel_Shared_PasswordHasher' => \PhpOffice\PhpSpreadsheet\Shared\PasswordHasher::class, - 'PHPExcel_Shared_String' => \PhpOffice\PhpSpreadsheet\Shared\StringHelper::class, - 'PHPExcel_Shared_TimeZone' => \PhpOffice\PhpSpreadsheet\Shared\TimeZone::class, - 'PHPExcel_Shared_XMLWriter' => \PhpOffice\PhpSpreadsheet\Shared\XMLWriter::class, - 'PHPExcel_Shared_Excel5' => \PhpOffice\PhpSpreadsheet\Shared\Xls::class, - 'PHPExcel_Style_Alignment' => \PhpOffice\PhpSpreadsheet\Style\Alignment::class, - 'PHPExcel_Style_Border' => \PhpOffice\PhpSpreadsheet\Style\Border::class, - 'PHPExcel_Style_Borders' => \PhpOffice\PhpSpreadsheet\Style\Borders::class, - 'PHPExcel_Style_Color' => \PhpOffice\PhpSpreadsheet\Style\Color::class, - 'PHPExcel_Style_Conditional' => \PhpOffice\PhpSpreadsheet\Style\Conditional::class, - 'PHPExcel_Style_Fill' => \PhpOffice\PhpSpreadsheet\Style\Fill::class, - 'PHPExcel_Style_Font' => \PhpOffice\PhpSpreadsheet\Style\Font::class, - 'PHPExcel_Style_NumberFormat' => \PhpOffice\PhpSpreadsheet\Style\NumberFormat::class, - 'PHPExcel_Style_Protection' => \PhpOffice\PhpSpreadsheet\Style\Protection::class, - 'PHPExcel_Style_Supervisor' => \PhpOffice\PhpSpreadsheet\Style\Supervisor::class, - 'PHPExcel_Worksheet_AutoFilter' => \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter::class, - 'PHPExcel_Worksheet_BaseDrawing' => \PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing::class, - 'PHPExcel_Worksheet_CellIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\CellIterator::class, - 'PHPExcel_Worksheet_Column' => \PhpOffice\PhpSpreadsheet\Worksheet\Column::class, - 'PHPExcel_Worksheet_ColumnCellIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\ColumnCellIterator::class, - 'PHPExcel_Worksheet_ColumnDimension' => \PhpOffice\PhpSpreadsheet\Worksheet\ColumnDimension::class, - 'PHPExcel_Worksheet_ColumnIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\ColumnIterator::class, - 'PHPExcel_Worksheet_Drawing' => \PhpOffice\PhpSpreadsheet\Worksheet\Drawing::class, - 'PHPExcel_Worksheet_HeaderFooter' => \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::class, - 'PHPExcel_Worksheet_HeaderFooterDrawing' => \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing::class, - 'PHPExcel_WorksheetIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\Iterator::class, - 'PHPExcel_Worksheet_MemoryDrawing' => \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::class, - 'PHPExcel_Worksheet_PageMargins' => \PhpOffice\PhpSpreadsheet\Worksheet\PageMargins::class, - 'PHPExcel_Worksheet_PageSetup' => \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::class, - 'PHPExcel_Worksheet_Protection' => \PhpOffice\PhpSpreadsheet\Worksheet\Protection::class, - 'PHPExcel_Worksheet_Row' => \PhpOffice\PhpSpreadsheet\Worksheet\Row::class, - 'PHPExcel_Worksheet_RowCellIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\RowCellIterator::class, - 'PHPExcel_Worksheet_RowDimension' => \PhpOffice\PhpSpreadsheet\Worksheet\RowDimension::class, - 'PHPExcel_Worksheet_RowIterator' => \PhpOffice\PhpSpreadsheet\Worksheet\RowIterator::class, - 'PHPExcel_Worksheet_SheetView' => \PhpOffice\PhpSpreadsheet\Worksheet\SheetView::class, - 'PHPExcel_Writer_Abstract' => \PhpOffice\PhpSpreadsheet\Writer\BaseWriter::class, - 'PHPExcel_Writer_CSV' => \PhpOffice\PhpSpreadsheet\Writer\Csv::class, - 'PHPExcel_Writer_Exception' => \PhpOffice\PhpSpreadsheet\Writer\Exception::class, - 'PHPExcel_Writer_HTML' => \PhpOffice\PhpSpreadsheet\Writer\Html::class, - 'PHPExcel_Writer_IWriter' => \PhpOffice\PhpSpreadsheet\Writer\IWriter::class, - 'PHPExcel_Writer_OpenDocument' => \PhpOffice\PhpSpreadsheet\Writer\Ods::class, - 'PHPExcel_Writer_PDF' => \PhpOffice\PhpSpreadsheet\Writer\Pdf::class, - 'PHPExcel_Writer_Excel5' => \PhpOffice\PhpSpreadsheet\Writer\Xls::class, - 'PHPExcel_Writer_Excel2007' => \PhpOffice\PhpSpreadsheet\Writer\Xlsx::class, - 'PHPExcel_CachedObjectStorageFactory' => \PhpOffice\PhpSpreadsheet\Collection\CellsFactory::class, - 'PHPExcel_Calculation' => \PhpOffice\PhpSpreadsheet\Calculation\Calculation::class, - 'PHPExcel_Cell' => \PhpOffice\PhpSpreadsheet\Cell\Cell::class, - 'PHPExcel_Chart' => \PhpOffice\PhpSpreadsheet\Chart\Chart::class, - 'PHPExcel_Comment' => \PhpOffice\PhpSpreadsheet\Comment::class, - 'PHPExcel_Exception' => \PhpOffice\PhpSpreadsheet\Exception::class, - 'PHPExcel_HashTable' => \PhpOffice\PhpSpreadsheet\HashTable::class, - 'PHPExcel_IComparable' => \PhpOffice\PhpSpreadsheet\IComparable::class, - 'PHPExcel_IOFactory' => \PhpOffice\PhpSpreadsheet\IOFactory::class, - 'PHPExcel_NamedRange' => \PhpOffice\PhpSpreadsheet\NamedRange::class, - 'PHPExcel_ReferenceHelper' => \PhpOffice\PhpSpreadsheet\ReferenceHelper::class, - 'PHPExcel_RichText' => \PhpOffice\PhpSpreadsheet\RichText\RichText::class, - 'PHPExcel_Settings' => \PhpOffice\PhpSpreadsheet\Settings::class, - 'PHPExcel_Style' => \PhpOffice\PhpSpreadsheet\Style\Style::class, - 'PHPExcel_Worksheet' => \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::class, - ]; - - $methods = [ - 'MINUTEOFHOUR' => 'MINUTE', - 'SECONDOFMINUTE' => 'SECOND', - 'DAYOFWEEK' => 'WEEKDAY', - 'WEEKOFYEAR' => 'WEEKNUM', - 'ExcelToPHPObject' => 'excelToDateTimeObject', - 'ExcelToPHP' => 'excelToTimestamp', - 'FormattedPHPToExcel' => 'formattedPHPToExcel', - 'Cell::absoluteCoordinate' => 'Coordinate::absoluteCoordinate', - 'Cell::absoluteReference' => 'Coordinate::absoluteReference', - 'Cell::buildRange' => 'Coordinate::buildRange', - 'Cell::columnIndexFromString' => 'Coordinate::columnIndexFromString', - 'Cell::coordinateFromString' => 'Coordinate::coordinateFromString', - 'Cell::extractAllCellReferencesInRange' => 'Coordinate::extractAllCellReferencesInRange', - 'Cell::getRangeBoundaries' => 'Coordinate::getRangeBoundaries', - 'Cell::mergeRangesInCollection' => 'Coordinate::mergeRangesInCollection', - 'Cell::rangeBoundaries' => 'Coordinate::rangeBoundaries', - 'Cell::rangeDimension' => 'Coordinate::rangeDimension', - 'Cell::splitRange' => 'Coordinate::splitRange', - 'Cell::stringFromColumnIndex' => 'Coordinate::stringFromColumnIndex', - ]; - - // Keep '\' prefix for class names - $prefixedClasses = []; - foreach ($classes as $key => &$value) { - $value = str_replace('PhpOffice\\', '\\PhpOffice\\', $value); - $prefixedClasses['\\' . $key] = $value; - } - $mapping = $prefixedClasses + $classes + $methods; - - return $mapping; - } - - /** - * Search in all files in given directory. - * - * @param string $path - */ - private function recursiveReplace($path) - { - $patterns = [ - '/*.md', - '/*.txt', - '/*.TXT', - '/*.php', - '/*.phpt', - '/*.php3', - '/*.php4', - '/*.php5', - '/*.phtml', - ]; - - foreach ($patterns as $pattern) { - foreach (glob($path . $pattern) as $file) { - if (strpos($path, '/vendor/') !== false) { - echo $file . " skipped\n"; - - continue; - } - $original = file_get_contents($file); - $converted = $this->replace($original); - - if ($original !== $converted) { - echo $file . " converted\n"; - file_put_contents($file, $converted); - } - } - } - - // Do the recursion in subdirectory - foreach (glob($path . '/*', GLOB_ONLYDIR) as $subpath) { - if (strpos($subpath, $path . '/') === 0) { - $this->recursiveReplace($subpath); - } - } - } - - public function migrate() - { - $path = realpath(getcwd()); - echo 'This will search and replace recursively in ' . $path . PHP_EOL; - echo 'You MUST backup your files first, or you risk losing data.' . PHP_EOL; - echo 'Are you sure ? (y/n)'; - - $confirm = fread(STDIN, 1); - if ($confirm === 'y') { - $this->recursiveReplace($path); - } - } - - /** - * Migrate the given code from PHPExcel to PhpSpreadsheet. - * - * @param string $original - * - * @return string - */ - public function replace($original) - { - $converted = str_replace($this->from, $this->to, $original); - - // The string "PHPExcel" gets special treatment because of how common it might be. - // This regex requires a word boundary around the string, and it can't be - // preceded by $ or -> (goal is to filter out cases where a variable is named $PHPExcel or similar) - $converted = preg_replace('~(?)(\b|\\\\)PHPExcel\b~', '\\' . \PhpOffice\PhpSpreadsheet\Spreadsheet::class, $converted); - - return $converted; - } -} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php index e199c807..257a02a8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Sample.php @@ -5,12 +5,12 @@ use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\IWriter; -use PhpOffice\PhpSpreadsheet\Writer\Pdf; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RecursiveRegexIterator; use ReflectionClass; use RegexIterator; +use RuntimeException; /** * Helper class to be used in sample code. @@ -70,7 +70,7 @@ public function getPageHeading() /** * Returns an array of all known samples. * - * @return string[] [$name => $path] + * @return string[][] [$name => $path] */ public function getSamples() { @@ -106,11 +106,10 @@ public function getSamples() /** * Write documents. * - * @param Spreadsheet $spreadsheet * @param string $filename * @param string[] $writers */ - public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls']) + public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xlsx', 'Xls']): void { // Set active sheet index to the first sheet, so Excel opens this as the first sheet $spreadsheet->setActiveSheetIndex(0); @@ -119,11 +118,6 @@ public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xl foreach ($writers as $writerType) { $path = $this->getFilename($filename, mb_strtolower($writerType)); $writer = IOFactory::createWriter($spreadsheet, $writerType); - if ($writer instanceof Pdf) { - // PDF writer needs temporary directory - $tempDir = $this->getTemporaryFolder(); - $writer->setTempDir($tempDir); - } $callStartTime = microtime(true); $writer->save($path); $this->logWrite($writer, $path, $callStartTime); @@ -132,6 +126,11 @@ public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xl $this->logEndingNotes(); } + protected function isDirOrMkdir(string $folder): bool + { + return \is_dir($folder) || \mkdir($folder); + } + /** * Returns the temporary directory and make sure it exists. * @@ -140,10 +139,8 @@ public function write(Spreadsheet $spreadsheet, $filename, array $writers = ['Xl private function getTemporaryFolder() { $tempFolder = sys_get_temp_dir() . '/phpspreadsheet'; - if (!is_dir($tempFolder)) { - if (!mkdir($tempFolder) && !is_dir($tempFolder)) { - throw new \RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); - } + if (!$this->isDirOrMkdir($tempFolder)) { + throw new RuntimeException(sprintf('Directory "%s" was not created', $tempFolder)); } return $tempFolder; @@ -179,7 +176,7 @@ public function getTemporaryFilename($extension = 'xlsx') return $temporaryFilename . '.' . $extension; } - public function log($message) + public function log($message): void { $eol = $this->isCli() ? PHP_EOL : '
        '; echo date('H:i:s ') . $message . $eol; @@ -188,7 +185,7 @@ public function log($message) /** * Log ending notes. */ - public function logEndingNotes() + public function logEndingNotes(): void { // Do not show execution time for index $this->log('Peak memory usage: ' . (memory_get_peak_usage(true) / 1024 / 1024) . 'MB'); @@ -197,11 +194,10 @@ public function logEndingNotes() /** * Log a line about the write operation. * - * @param IWriter $writer * @param string $path * @param float $callStartTime */ - public function logWrite(IWriter $writer, $path, $callStartTime) + public function logWrite(IWriter $writer, $path, $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; @@ -219,7 +215,7 @@ public function logWrite(IWriter $writer, $path, $callStartTime) * @param string $path * @param float $callStartTime */ - public function logRead($format, $path, $callStartTime) + public function logRead($format, $path, $callStartTime): void { $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php new file mode 100644 index 00000000..12ba4ef7 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Helper/Size.php @@ -0,0 +1,52 @@ +\d*\.?\d+)(?Ppt|px|em)?$/i'; + + /** + * @var bool + */ + protected $valid; + + /** + * @var string + */ + protected $size = ''; + + /** + * @var string + */ + protected $unit = ''; + + public function __construct(string $size) + { + $this->valid = (bool) preg_match(self::REGEXP_SIZE_VALIDATION, $size, $matches); + if ($this->valid) { + $this->size = $matches['size']; + $this->unit = $matches['unit'] ?? 'pt'; + } + } + + public function valid(): bool + { + return $this->valid; + } + + public function size(): string + { + return $this->size; + } + + public function unit(): string + { + return $this->unit; + } + + public function __toString() + { + return $this->size . $this->unit; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php index 4266ea54..e437a220 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Reader\IReader; use PhpOffice\PhpSpreadsheet\Shared\File; +use PhpOffice\PhpSpreadsheet\Writer\IWriter; /** * Factory to create readers and writers easily. @@ -12,23 +14,39 @@ */ abstract class IOFactory { + public const READER_XLSX = 'Xlsx'; + public const READER_XLS = 'Xls'; + public const READER_XML = 'Xml'; + public const READER_ODS = 'Ods'; + public const READER_SYLK = 'Slk'; + public const READER_SLK = 'Slk'; + public const READER_GNUMERIC = 'Gnumeric'; + public const READER_HTML = 'Html'; + public const READER_CSV = 'Csv'; + + public const WRITER_XLSX = 'Xlsx'; + public const WRITER_XLS = 'Xls'; + public const WRITER_ODS = 'Ods'; + public const WRITER_CSV = 'Csv'; + public const WRITER_HTML = 'Html'; + private static $readers = [ - 'Xlsx' => Reader\Xlsx::class, - 'Xls' => Reader\Xls::class, - 'Xml' => Reader\Xml::class, - 'Ods' => Reader\Ods::class, - 'Slk' => Reader\Slk::class, - 'Gnumeric' => Reader\Gnumeric::class, - 'Html' => Reader\Html::class, - 'Csv' => Reader\Csv::class, + self::READER_XLSX => Reader\Xlsx::class, + self::READER_XLS => Reader\Xls::class, + self::READER_XML => Reader\Xml::class, + self::READER_ODS => Reader\Ods::class, + self::READER_SLK => Reader\Slk::class, + self::READER_GNUMERIC => Reader\Gnumeric::class, + self::READER_HTML => Reader\Html::class, + self::READER_CSV => Reader\Csv::class, ]; private static $writers = [ - 'Xls' => Writer\Xls::class, - 'Xlsx' => Writer\Xlsx::class, - 'Ods' => Writer\Ods::class, - 'Csv' => Writer\Csv::class, - 'Html' => Writer\Html::class, + self::WRITER_XLS => Writer\Xls::class, + self::WRITER_XLSX => Writer\Xlsx::class, + self::WRITER_ODS => Writer\Ods::class, + self::WRITER_CSV => Writer\Csv::class, + self::WRITER_HTML => Writer\Html::class, 'Tcpdf' => Writer\Pdf\Tcpdf::class, 'Dompdf' => Writer\Pdf\Dompdf::class, 'Mpdf' => Writer\Pdf\Mpdf::class, @@ -36,15 +54,8 @@ abstract class IOFactory /** * Create Writer\IWriter. - * - * @param Spreadsheet $spreadsheet - * @param string $writerType Example: Xlsx - * - * @throws Writer\Exception - * - * @return Writer\IWriter */ - public static function createWriter(Spreadsheet $spreadsheet, $writerType) + public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter { if (!isset(self::$writers[$writerType])) { throw new Writer\Exception("No writer found for type $writerType"); @@ -57,15 +68,9 @@ public static function createWriter(Spreadsheet $spreadsheet, $writerType) } /** - * Create Reader\IReader. - * - * @param string $readerType Example: Xlsx - * - * @throws Reader\Exception - * - * @return Reader\IReader + * Create IReader. */ - public static function createReader($readerType) + public static function createReader(string $readerType): IReader { if (!isset(self::$readers[$readerType])) { throw new Reader\Exception("No reader found for type $readerType"); @@ -80,31 +85,29 @@ public static function createReader($readerType) /** * Loads Spreadsheet from file using automatic Reader\IReader resolution. * - * @param string $pFilename The name of the spreadsheet file - * - * @throws Reader\Exception - * - * @return Spreadsheet + * @param string $filename The name of the spreadsheet file + * @param int $flags the optional second parameter flags may be used to identify specific elements + * that should be loaded, but which won't be loaded by default, using these values: + * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file + * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try + * all possible Readers until it finds a match; but this allows you to pass in a + * list of Readers so it will only try the subset that you specify here. + * Values in this list can be any of the constant values defined in the set + * IOFactory::READER_*. */ - public static function load($pFilename) + public static function load(string $filename, int $flags = 0, ?array $readers = null): Spreadsheet { - $reader = self::createReaderForFile($pFilename); + $reader = self::createReaderForFile($filename, $readers); - return $reader->load($pFilename); + return $reader->load($filename, $flags); } /** - * Identify file type using automatic Reader\IReader resolution. - * - * @param string $pFilename The name of the spreadsheet file to identify - * - * @throws Reader\Exception - * - * @return string + * Identify file type using automatic IReader resolution. */ - public static function identify($pFilename) + public static function identify(string $filename, ?array $readers = null): string { - $reader = self::createReaderForFile($pFilename); + $reader = self::createReaderForFile($filename, $readers); $className = get_class($reader); $classType = explode('\\', $className); unset($reader); @@ -113,35 +116,47 @@ public static function identify($pFilename) } /** - * Create Reader\IReader for file using automatic Reader\IReader resolution. - * - * @param string $filename The name of the spreadsheet file - * - * @throws Reader\Exception + * Create Reader\IReader for file using automatic IReader resolution. * - * @return Reader\IReader + * @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try + * all possible Readers until it finds a match; but this allows you to pass in a + * list of Readers so it will only try the subset that you specify here. + * Values in this list can be any of the constant values defined in the set + * IOFactory::READER_*. */ - public static function createReaderForFile($filename) + public static function createReaderForFile(string $filename, ?array $readers = null): IReader { File::assertFile($filename); + $testReaders = self::$readers; + if ($readers !== null) { + $readers = array_map('strtoupper', $readers); + $testReaders = array_filter( + self::$readers, + function (string $readerType) use ($readers) { + return in_array(strtoupper($readerType), $readers, true); + }, + ARRAY_FILTER_USE_KEY + ); + } + // First, lucky guess by inspecting file extension $guessedReader = self::getReaderTypeFromExtension($filename); - if ($guessedReader !== null) { + if (($guessedReader !== null) && array_key_exists($guessedReader, $testReaders)) { $reader = self::createReader($guessedReader); // Let's see if we are lucky - if (isset($reader) && $reader->canRead($filename)) { + if ($reader->canRead($filename)) { return $reader; } } // If we reach here then "lucky guess" didn't give any result - // Try walking through all the options in self::$autoResolveClasses - foreach (self::$readers as $type => $class) { + // Try walking through all the options in self::$readers (or the selected subset) + foreach ($testReaders as $readerType => $class) { // Ignore our original guess, we know that won't work - if ($type !== $guessedReader) { - $reader = self::createReader($type); + if ($readerType !== $guessedReader) { + $reader = self::createReader($readerType); if ($reader->canRead($filename)) { return $reader; } @@ -153,12 +168,8 @@ public static function createReaderForFile($filename) /** * Guess a reader type from the file extension, if any. - * - * @param string $filename - * - * @return null|string */ - private static function getReaderTypeFromExtension($filename) + private static function getReaderTypeFromExtension(string $filename): ?string { $pathinfo = pathinfo($filename); if (!isset($pathinfo['extension'])) { @@ -198,14 +209,11 @@ private static function getReaderTypeFromExtension($filename) /** * Register a writer with its type and class name. - * - * @param string $writerType - * @param string $writerClass */ - public static function registerWriter($writerType, $writerClass) + public static function registerWriter(string $writerType, string $writerClass): void { - if (!is_a($writerClass, Writer\IWriter::class, true)) { - throw new Writer\Exception('Registered writers must implement ' . Writer\IWriter::class); + if (!is_a($writerClass, IWriter::class, true)) { + throw new Writer\Exception('Registered writers must implement ' . IWriter::class); } self::$writers[$writerType] = $writerClass; @@ -213,14 +221,11 @@ public static function registerWriter($writerType, $writerClass) /** * Register a reader with its type and class name. - * - * @param string $readerType - * @param string $readerClass */ - public static function registerReader($readerType, $readerClass) + public static function registerReader(string $readerType, string $readerClass): void { - if (!is_a($readerClass, Reader\IReader::class, true)) { - throw new Reader\Exception('Registered readers must implement ' . Reader\IReader::class); + if (!is_a($readerClass, IReader::class, true)) { + throw new Reader\Exception('Registered readers must implement ' . IReader::class); } self::$readers[$readerType] = $readerClass; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php new file mode 100644 index 00000000..500151f0 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php @@ -0,0 +1,45 @@ +value; + } + + /** + * Set the formula value. + */ + public function setFormula(string $formula): self + { + if (!empty($formula)) { + $this->value = $formula; + } + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php index e539b7c5..db9c5f12 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php @@ -2,239 +2,54 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -class NamedRange +class NamedRange extends DefinedName { /** - * Range name. - * - * @var string - */ - private $name; - - /** - * Worksheet on which the named range can be resolved. - * - * @var Worksheet - */ - private $worksheet; - - /** - * Range of the referenced cells. - * - * @var string - */ - private $range; - - /** - * Is the named range local? (i.e. can only be used on $this->worksheet). - * - * @var bool - */ - private $localOnly; - - /** - * Scope. - * - * @var Worksheet - */ - private $scope; - - /** - * Create a new NamedRange. - * - * @param string $pName - * @param Worksheet $pWorksheet - * @param string $pRange - * @param bool $pLocalOnly - * @param null|Worksheet $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope. - * - * @throws Exception - */ - public function __construct($pName, Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null) - { - // Validate data - if (($pName === null) || ($pWorksheet === null) || ($pRange === null)) { - throw new Exception('Parameters can not be null.'); + * Create a new Named Range. + */ + public function __construct( + string $name, + ?Worksheet $worksheet = null, + string $range = 'A1', + bool $localOnly = false, + ?Worksheet $scope = null + ) { + if ($worksheet === null && $scope === null) { + throw new Exception('You must specify a worksheet or a scope for a Named Range'); } - - // Set local members - $this->name = $pName; - $this->worksheet = $pWorksheet; - $this->range = $pRange; - $this->localOnly = $pLocalOnly; - $this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null; + parent::__construct($name, $worksheet, $range, $localOnly, $scope); } /** - * Get name. - * - * @return string + * Get the range value. */ - public function getName() + public function getRange(): string { - return $this->name; + return $this->value; } /** - * Set name. - * - * @param string $value - * - * @return $this + * Set the range value. */ - public function setName($value) + public function setRange(string $range): self { - if ($value !== null) { - // Old title - $oldTitle = $this->name; - - // Re-attach - if ($this->worksheet !== null) { - $this->worksheet->getParent()->removeNamedRange($this->name, $this->worksheet); - } - $this->name = $value; - - if ($this->worksheet !== null) { - $this->worksheet->getParent()->addNamedRange($this); - } - - // New title - $newTitle = $this->name; - ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle); + if (!empty($range)) { + $this->value = $range; } return $this; } - /** - * Get worksheet. - * - * @return Worksheet - */ - public function getWorksheet() - { - return $this->worksheet; - } - - /** - * Set worksheet. - * - * @param Worksheet $value - * - * @return $this - */ - public function setWorksheet(Worksheet $value = null) + public function getCellsInRange(): array { - if ($value !== null) { - $this->worksheet = $value; + $range = $this->value; + if (substr($range, 0, 1) === '=') { + $range = substr($range, 1); } - return $this; - } - - /** - * Get range. - * - * @return string - */ - public function getRange() - { - return $this->range; - } - - /** - * Set range. - * - * @param string $value - * - * @return $this - */ - public function setRange($value) - { - if ($value !== null) { - $this->range = $value; - } - - return $this; - } - - /** - * Get localOnly. - * - * @return bool - */ - public function getLocalOnly() - { - return $this->localOnly; - } - - /** - * Set localOnly. - * - * @param bool $value - * - * @return $this - */ - public function setLocalOnly($value) - { - $this->localOnly = $value; - $this->scope = $value ? $this->worksheet : null; - - return $this; - } - - /** - * Get scope. - * - * @return null|Worksheet - */ - public function getScope() - { - return $this->scope; - } - - /** - * Set scope. - * - * @param null|Worksheet $value - * - * @return $this - */ - public function setScope(Worksheet $value = null) - { - $this->scope = $value; - $this->localOnly = $value != null; - - return $this; - } - - /** - * Resolve a named range to a regular cell range. - * - * @param string $pNamedRange Named range - * @param null|Worksheet $pSheet Scope. Use null for global scope - * - * @return NamedRange - */ - public static function resolveRange($pNamedRange, Worksheet $pSheet) - { - return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet); - } - - /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. - */ - public function __clone() - { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } + return Coordinate::extractAllCellReferencesInRange($range); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php index f7af1557..a137e78c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/BaseReader.php @@ -2,8 +2,11 @@ namespace PhpOffice\PhpSpreadsheet\Reader; +use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Shared\File; +use PhpOffice\PhpSpreadsheet\Spreadsheet; abstract class BaseReader implements IReader { @@ -37,7 +40,7 @@ abstract class BaseReader implements IReader * Restrict which sheets should be loaded? * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded. * - * @var array of string + * @var null|string[] */ protected $loadSheetsOnly; @@ -65,9 +68,9 @@ public function getReadDataOnly() return $this->readDataOnly; } - public function setReadDataOnly($pValue) + public function setReadDataOnly($readCellValuesOnly) { - $this->readDataOnly = (bool) $pValue; + $this->readDataOnly = (bool) $readCellValuesOnly; return $this; } @@ -77,9 +80,9 @@ public function getReadEmptyCells() return $this->readEmptyCells; } - public function setReadEmptyCells($pValue) + public function setReadEmptyCells($readEmptyCells) { - $this->readEmptyCells = (bool) $pValue; + $this->readEmptyCells = (bool) $readEmptyCells; return $this; } @@ -89,9 +92,9 @@ public function getIncludeCharts() return $this->includeCharts; } - public function setIncludeCharts($pValue) + public function setIncludeCharts($includeCharts) { - $this->includeCharts = (bool) $pValue; + $this->includeCharts = (bool) $includeCharts; return $this; } @@ -101,13 +104,13 @@ public function getLoadSheetsOnly() return $this->loadSheetsOnly; } - public function setLoadSheetsOnly($value) + public function setLoadSheetsOnly($sheetList) { - if ($value === null) { + if ($sheetList === null) { return $this->setLoadAllSheets(); } - $this->loadSheetsOnly = is_array($value) ? $value : [$value]; + $this->loadSheetsOnly = is_array($sheetList) ? $sheetList : [$sheetList]; return $this; } @@ -124,37 +127,64 @@ public function getReadFilter() return $this->readFilter; } - public function setReadFilter(IReadFilter $pValue) + public function setReadFilter(IReadFilter $readFilter) { - $this->readFilter = $pValue; + $this->readFilter = $readFilter; return $this; } public function getSecurityScanner() { - if (property_exists($this, 'securityScanner')) { - return $this->securityScanner; + return $this->securityScanner; + } + + protected function processFlags(int $flags): void + { + if (((bool) ($flags & self::LOAD_WITH_CHARTS)) === true) { + $this->setIncludeCharts(true); } + } - return null; + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet + { + throw new PhpSpreadsheetException('Reader classes must implement their own loadSpreadsheetFromFile() method'); } /** - * Open file for reading. - * - * @param string $pFilename + * Loads Spreadsheet from file. * - * @throws Exception + * @param int $flags the optional second parameter flags may be used to identify specific elements + * that should be loaded, but which won't be loaded by default, using these values: + * IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file */ - protected function openFile($pFilename) + public function load(string $filename, int $flags = 0): Spreadsheet { - File::assertFile($pFilename); + $this->processFlags($flags); - // Open file - $this->fileHandle = fopen($pFilename, 'r'); - if ($this->fileHandle === false) { - throw new Exception('Could not open file ' . $pFilename . ' for reading.'); + try { + return $this->loadSpreadsheetFromFile($filename); + } catch (ReaderException $e) { + throw $e; } } + + /** + * Open file for reading. + */ + protected function openFile(string $filename): void + { + $fileHandle = false; + if ($filename) { + File::assertFile($filename); + + // Open file + $fileHandle = fopen($filename, 'rb'); + } + if ($fileHandle === false) { + throw new ReaderException('Could not open file ' . $filename . ' for reading.'); + } + + $this->fileHandle = $fileHandle; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php index 47134098..e894e9a4 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv.php @@ -2,12 +2,34 @@ namespace PhpOffice\PhpSpreadsheet\Reader; +use PhpOffice\PhpSpreadsheet\Calculation\Calculation; +use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Csv\Delimiter; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Csv extends BaseReader { + const DEFAULT_FALLBACK_ENCODING = 'CP1252'; + const GUESS_ENCODING = 'guess'; + const UTF8_BOM = "\xEF\xBB\xBF"; + const UTF8_BOM_LEN = 3; + const UTF16BE_BOM = "\xfe\xff"; + const UTF16BE_BOM_LEN = 2; + const UTF16BE_LF = "\x00\x0a"; + const UTF16LE_BOM = "\xff\xfe"; + const UTF16LE_BOM_LEN = 2; + const UTF16LE_LF = "\x0a\x00"; + const UTF32BE_BOM = "\x00\x00\xfe\xff"; + const UTF32BE_BOM_LEN = 4; + const UTF32BE_LF = "\x00\x00\x00\x0a"; + const UTF32LE_BOM = "\xff\xfe\x00\x00"; + const UTF32LE_BOM_LEN = 4; + const UTF32LE_LF = "\x0a\x00\x00\x00"; + /** * Input encoding. * @@ -16,10 +38,17 @@ class Csv extends BaseReader private $inputEncoding = 'UTF-8'; /** - * Delimiter. + * Fallback encoding if guess strikes out. * * @var string */ + private $fallbackEncoding = self::DEFAULT_FALLBACK_ENCODING; + + /** + * Delimiter. + * + * @var ?string + */ private $delimiter; /** @@ -44,18 +73,35 @@ class Csv extends BaseReader private $contiguous = false; /** - * Row counter for loading rows contiguously. + * The character that can escape the enclosure. * - * @var int + * @var string */ - private $contiguousRow = -1; + private $escapeCharacter = '\\'; /** - * The character that can escape the enclosure. + * Callback for setting defaults in construction. * - * @var string + * @var ?callable */ - private $escapeCharacter = '\\'; + private static $constructorCallback; + + /** + * Attempt autodetect line endings (deprecated after PHP8.1)? + * + * @var bool + */ + private $testAutodetect = true; + + /** + * @var bool + */ + protected $castFormattedNumberToNumeric = false; + + /** + * @var bool + */ + protected $preserveNumericFormatting = false; /** * Create a new CSV Reader instance. @@ -63,74 +109,68 @@ class Csv extends BaseReader public function __construct() { parent::__construct(); + $callback = self::$constructorCallback; + if ($callback !== null) { + $callback($this); + } } /** - * Set input encoding. - * - * @param string $pValue Input encoding, eg: 'UTF-8' + * Set a callback to change the defaults. * - * @return $this + * The callback must accept the Csv Reader object as the first parameter, + * and it should return void. */ - public function setInputEncoding($pValue) + public static function setConstructorCallback(?callable $callback): void + { + self::$constructorCallback = $callback; + } + + public static function getConstructorCallback(): ?callable + { + return self::$constructorCallback; + } + + public function setInputEncoding(string $encoding): self { - $this->inputEncoding = $pValue; + $this->inputEncoding = $encoding; return $this; } - /** - * Get input encoding. - * - * @return string - */ - public function getInputEncoding() + public function getInputEncoding(): string { return $this->inputEncoding; } + public function setFallbackEncoding(string $fallbackEncoding): self + { + $this->fallbackEncoding = $fallbackEncoding; + + return $this; + } + + public function getFallbackEncoding(): string + { + return $this->fallbackEncoding; + } + /** * Move filepointer past any BOM marker. */ - protected function skipBOM() + protected function skipBOM(): void { rewind($this->fileHandle); - switch ($this->inputEncoding) { - case 'UTF-8': - fgets($this->fileHandle, 4) == "\xEF\xBB\xBF" ? - fseek($this->fileHandle, 3) : fseek($this->fileHandle, 0); - - break; - case 'UTF-16LE': - fgets($this->fileHandle, 3) == "\xFF\xFE" ? - fseek($this->fileHandle, 2) : fseek($this->fileHandle, 0); - - break; - case 'UTF-16BE': - fgets($this->fileHandle, 3) == "\xFE\xFF" ? - fseek($this->fileHandle, 2) : fseek($this->fileHandle, 0); - - break; - case 'UTF-32LE': - fgets($this->fileHandle, 5) == "\xFF\xFE\x00\x00" ? - fseek($this->fileHandle, 4) : fseek($this->fileHandle, 0); - - break; - case 'UTF-32BE': - fgets($this->fileHandle, 5) == "\x00\x00\xFE\xFF" ? - fseek($this->fileHandle, 4) : fseek($this->fileHandle, 0); - - break; - default: - break; + if (fgets($this->fileHandle, self::UTF8_BOM_LEN + 1) !== self::UTF8_BOM) { + rewind($this->fileHandle); } } /** * Identify any separator that is explicitly set in the file. */ - protected function checkSeparator() + protected function checkSeparator(): void { $line = fgets($this->fileHandle); if ($line === false) { @@ -149,140 +189,39 @@ protected function checkSeparator() /** * Infer the separator if it isn't explicitly set in the file or specified by the user. */ - protected function inferSeparator() + protected function inferSeparator(): void { if ($this->delimiter !== null) { return; } - $potentialDelimiters = [',', ';', "\t", '|', ':', ' ', '~']; - $counts = []; - foreach ($potentialDelimiters as $delimiter) { - $counts[$delimiter] = []; - } - - // Count how many times each of the potential delimiters appears in each line - $numberLines = 0; - while (($line = $this->getNextLine()) !== false && (++$numberLines < 1000)) { - $countLine = []; - for ($i = strlen($line) - 1; $i >= 0; --$i) { - $char = $line[$i]; - if (isset($counts[$char])) { - if (!isset($countLine[$char])) { - $countLine[$char] = 0; - } - ++$countLine[$char]; - } - } - foreach ($potentialDelimiters as $delimiter) { - $counts[$delimiter][] = $countLine[$delimiter] - ?? 0; - } - } + $inferenceEngine = new Delimiter($this->fileHandle, $this->escapeCharacter, $this->enclosure); // If number of lines is 0, nothing to infer : fall back to the default - if ($numberLines === 0) { - $this->delimiter = reset($potentialDelimiters); + if ($inferenceEngine->linesCounted() === 0) { + $this->delimiter = $inferenceEngine->getDefaultDelimiter(); $this->skipBOM(); return; } - // Calculate the mean square deviations for each delimiter (ignoring delimiters that haven't been found consistently) - $meanSquareDeviations = []; - $middleIdx = floor(($numberLines - 1) / 2); - - foreach ($potentialDelimiters as $delimiter) { - $series = $counts[$delimiter]; - sort($series); - - $median = ($numberLines % 2) - ? $series[$middleIdx] - : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2; - - if ($median === 0) { - continue; - } - - $meanSquareDeviations[$delimiter] = array_reduce( - $series, - function ($sum, $value) use ($median) { - return $sum + pow($value - $median, 2); - } - ) / count($series); - } - - // ... and pick the delimiter with the smallest mean square deviation (in case of ties, the order in potentialDelimiters is respected) - $min = INF; - foreach ($potentialDelimiters as $delimiter) { - if (!isset($meanSquareDeviations[$delimiter])) { - continue; - } - - if ($meanSquareDeviations[$delimiter] < $min) { - $min = $meanSquareDeviations[$delimiter]; - $this->delimiter = $delimiter; - } - } + $this->delimiter = $inferenceEngine->infer(); // If no delimiter could be detected, fall back to the default if ($this->delimiter === null) { - $this->delimiter = reset($potentialDelimiters); + $this->delimiter = $inferenceEngine->getDefaultDelimiter(); } $this->skipBOM(); } - /** - * Get the next full line from the file. - * - * @param string $line - * - * @return bool|string - */ - private function getNextLine($line = '') - { - // Get the next line in the file - $newLine = fgets($this->fileHandle); - - // Return false if there is no next line - if ($newLine === false) { - return false; - } - - // Add the new line to the line passed in - $line = $line . $newLine; - - // Drop everything that is enclosed to avoid counting false positives in enclosures - $enclosure = '(?escapeCharacter, '/') . ')' - . preg_quote($this->enclosure, '/'); - $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line); - - // See if we have any enclosures left in the line - // if we still have an enclosure then we need to read the next line as well - if (preg_match('/(' . $enclosure . ')/', $line) > 0) { - $line = $this->getNextLine($line); - } - - return $line; - } - /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). - * - * @param string $pFilename - * - * @throws Exception - * - * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo(string $filename): array { // Open file - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); - } - $this->openFile($pFilename); + $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any @@ -298,9 +237,11 @@ public function listWorksheetInfo($pFilename) $worksheetInfo[0]['totalColumns'] = 0; // Loop through each line of the file in turn - while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) { + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); + while (is_array($rowData)) { ++$worksheetInfo[0]['totalRows']; $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); } $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1); @@ -314,42 +255,75 @@ public function listWorksheetInfo($pFilename) /** * Loads Spreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); + } + + private function openFileOrMemory(string $filename): void + { + // Open file + $fhandle = $this->canRead($filename); + if (!$fhandle) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); + } + if ($this->inputEncoding === self::GUESS_ENCODING) { + $this->inputEncoding = self::guessEncoding($filename, $this->fallbackEncoding); + } + $this->openFile($filename); + if ($this->inputEncoding !== 'UTF-8') { + fclose($this->fileHandle); + $entireFile = file_get_contents($filename); + $this->fileHandle = fopen('php://memory', 'r+b'); + if ($this->fileHandle !== false && $entireFile !== false) { + $data = StringHelper::convertEncoding($entireFile, 'UTF-8', $this->inputEncoding); + fwrite($this->fileHandle, $data); + $this->skipBOM(); + } + } + } + + public function setTestAutoDetect(bool $value): void + { + $this->testAutodetect = $value; + } + + private function setAutoDetect(?string $value): ?string + { + $retVal = null; + if ($value !== null && $this->testAutodetect) { + $retVal2 = @ini_set('auto_detect_line_endings', $value); + if (is_string($retVal2)) { + $retVal = $retVal2; + } + } + + return $retVal; + } + + public function castFormattedNumberToNumeric( + bool $castFormattedNumberToNumeric, + bool $preserveNumericFormatting = false + ): void { + $this->castFormattedNumberToNumeric = $castFormattedNumberToNumeric; + $this->preserveNumericFormatting = $preserveNumericFormatting; } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. - * - * @param string $pFilename - * @param Spreadsheet $spreadsheet - * - * @throws Exception - * - * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { - $lineEnding = ini_get('auto_detect_line_endings'); - ini_set('auto_detect_line_endings', true); + // Deprecated in Php8.1 + $iniset = $this->setAutoDetect('1'); // Open file - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); - } - $this->openFile($pFilename); + $this->openFileOrMemory($filename); $fileHandle = $this->fileHandle; // Skip BOM, if any @@ -365,83 +339,118 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) // Set our starting row based on whether we're in contiguous mode or not $currentRow = 1; - if ($this->contiguous) { - $currentRow = ($this->contiguousRow == -1) ? $sheet->getHighestRow() : $this->contiguousRow; - } + $outRow = 0; // Loop through each line of the file in turn - while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure, $this->escapeCharacter)) !== false) { + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); + $valueBinder = Cell::getValueBinder(); + $preserveBooleanString = method_exists($valueBinder, 'getBooleanConversion') && $valueBinder->getBooleanConversion(); + while (is_array($rowData)) { + $noOutputYet = true; $columnLetter = 'A'; foreach ($rowData as $rowDatum) { - if ($rowDatum != '' && $this->readFilter->readCell($columnLetter, $currentRow)) { - // Convert encoding if necessary - if ($this->inputEncoding !== 'UTF-8') { - $rowDatum = StringHelper::convertEncoding($rowDatum, 'UTF-8', $this->inputEncoding); + $this->convertBoolean($rowDatum, $preserveBooleanString); + $numberFormatMask = $this->convertFormattedNumber($rowDatum); + if ($rowDatum !== '' && $this->readFilter->readCell($columnLetter, $currentRow)) { + if ($this->contiguous) { + if ($noOutputYet) { + $noOutputYet = false; + ++$outRow; + } + } else { + $outRow = $currentRow; } - + // Set basic styling for the value (Note that this could be overloaded by styling in a value binder) + $sheet->getCell($columnLetter . $outRow)->getStyle() + ->getNumberFormat() + ->setFormatCode($numberFormatMask); // Set cell value - $sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum); + $sheet->getCell($columnLetter . $outRow)->setValue($rowDatum); } ++$columnLetter; } + $rowData = fgetcsv($fileHandle, 0, $this->delimiter ?? '', $this->enclosure, $this->escapeCharacter); ++$currentRow; } // Close file fclose($fileHandle); - if ($this->contiguous) { - $this->contiguousRow = $currentRow; - } - - ini_set('auto_detect_line_endings', $lineEnding); + $this->setAutoDetect($iniset); // Return return $spreadsheet; } /** - * Get delimiter. + * Convert string true/false to boolean, and null to null-string. * - * @return string + * @param mixed $rowDatum */ - public function getDelimiter() + private function convertBoolean(&$rowDatum, bool $preserveBooleanString): void { - return $this->delimiter; + if (is_string($rowDatum) && !$preserveBooleanString) { + if (strcasecmp(Calculation::getTRUE(), $rowDatum) === 0 || strcasecmp('true', $rowDatum) === 0) { + $rowDatum = true; + } elseif (strcasecmp(Calculation::getFALSE(), $rowDatum) === 0 || strcasecmp('false', $rowDatum) === 0) { + $rowDatum = false; + } + } elseif ($rowDatum === null) { + $rowDatum = ''; + } } /** - * Set delimiter. - * - * @param string $delimiter Delimiter, eg: ',' + * Convert numeric strings to int or float values. * - * @return $this + * @param mixed $rowDatum */ - public function setDelimiter($delimiter) + private function convertFormattedNumber(&$rowDatum): string + { + $numberFormatMask = NumberFormat::FORMAT_GENERAL; + if ($this->castFormattedNumberToNumeric === true && is_string($rowDatum)) { + $numeric = str_replace( + [StringHelper::getThousandsSeparator(), StringHelper::getDecimalSeparator()], + ['', '.'], + $rowDatum + ); + + if (is_numeric($numeric)) { + $decimalPos = strpos($rowDatum, StringHelper::getDecimalSeparator()); + if ($this->preserveNumericFormatting === true) { + $numberFormatMask = (strpos($rowDatum, StringHelper::getThousandsSeparator()) !== false) + ? '#,##0' : '0'; + if ($decimalPos !== false) { + $decimals = strlen($rowDatum) - $decimalPos - 1; + $numberFormatMask .= '.' . str_repeat('0', min($decimals, 6)); + } + } + + $rowDatum = ($decimalPos !== false) ? (float) $numeric : (int) $numeric; + } + } + + return $numberFormatMask; + } + + public function getDelimiter(): ?string + { + return $this->delimiter; + } + + public function setDelimiter(?string $delimiter): self { $this->delimiter = $delimiter; return $this; } - /** - * Get enclosure. - * - * @return string - */ - public function getEnclosure() + public function getEnclosure(): string { return $this->enclosure; } - /** - * Set enclosure. - * - * @param string $enclosure Enclosure, defaults to " - * - * @return $this - */ - public function setEnclosure($enclosure) + public function setEnclosure(string $enclosure): self { if ($enclosure == '') { $enclosure = '"'; @@ -451,108 +460,66 @@ public function setEnclosure($enclosure) return $this; } - /** - * Get sheet index. - * - * @return int - */ - public function getSheetIndex() + public function getSheetIndex(): int { return $this->sheetIndex; } - /** - * Set sheet index. - * - * @param int $pValue Sheet index - * - * @return $this - */ - public function setSheetIndex($pValue) + public function setSheetIndex(int $indexValue): self { - $this->sheetIndex = $pValue; + $this->sheetIndex = $indexValue; return $this; } - /** - * Set Contiguous. - * - * @param bool $contiguous - * - * @return $this - */ - public function setContiguous($contiguous) + public function setContiguous(bool $contiguous): self { - $this->contiguous = (bool) $contiguous; - if (!$contiguous) { - $this->contiguousRow = -1; - } + $this->contiguous = $contiguous; return $this; } - /** - * Get Contiguous. - * - * @return bool - */ - public function getContiguous() + public function getContiguous(): bool { return $this->contiguous; } - /** - * Set escape backslashes. - * - * @param string $escapeCharacter - * - * @return $this - */ - public function setEscapeCharacter($escapeCharacter) + public function setEscapeCharacter(string $escapeCharacter): self { $this->escapeCharacter = $escapeCharacter; return $this; } - /** - * Get escape backslashes. - * - * @return string - */ - public function getEscapeCharacter() + public function getEscapeCharacter(): string { return $this->escapeCharacter; } /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { // Check if file exists try { - $this->openFile($pFilename); - } catch (Exception $e) { + $this->openFile($filename); + } catch (ReaderException $e) { return false; } fclose($this->fileHandle); // Trust file extension if any - $extension = strtolower(pathinfo($pFilename, PATHINFO_EXTENSION)); + $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (in_array($extension, ['csv', 'tsv'])) { return true; } // Attempt to guess mimetype - $type = mime_content_type($pFilename); + $type = mime_content_type($filename); $supportedTypes = [ + 'application/csv', 'text/csv', 'text/plain', 'inode/x-empty', @@ -560,4 +527,63 @@ public function canRead($pFilename) return in_array($type, $supportedTypes, true); } + + private static function guessEncodingTestNoBom(string &$encoding, string &$contents, string $compare, string $setEncoding): void + { + if ($encoding === '') { + $pos = strpos($contents, $compare); + if ($pos !== false && $pos % strlen($compare) === 0) { + $encoding = $setEncoding; + } + } + } + + private static function guessEncodingNoBom(string $filename): string + { + $encoding = ''; + $contents = file_get_contents($filename); + self::guessEncodingTestNoBom($encoding, $contents, self::UTF32BE_LF, 'UTF-32BE'); + self::guessEncodingTestNoBom($encoding, $contents, self::UTF32LE_LF, 'UTF-32LE'); + self::guessEncodingTestNoBom($encoding, $contents, self::UTF16BE_LF, 'UTF-16BE'); + self::guessEncodingTestNoBom($encoding, $contents, self::UTF16LE_LF, 'UTF-16LE'); + if ($encoding === '' && preg_match('//u', $contents) === 1) { + $encoding = 'UTF-8'; + } + + return $encoding; + } + + private static function guessEncodingTestBom(string &$encoding, string $first4, string $compare, string $setEncoding): void + { + if ($encoding === '') { + if ($compare === substr($first4, 0, strlen($compare))) { + $encoding = $setEncoding; + } + } + } + + private static function guessEncodingBom(string $filename): string + { + $encoding = ''; + $first4 = file_get_contents($filename, false, null, 0, 4); + if ($first4 !== false) { + self::guessEncodingTestBom($encoding, $first4, self::UTF8_BOM, 'UTF-8'); + self::guessEncodingTestBom($encoding, $first4, self::UTF16BE_BOM, 'UTF-16BE'); + self::guessEncodingTestBom($encoding, $first4, self::UTF32BE_BOM, 'UTF-32BE'); + self::guessEncodingTestBom($encoding, $first4, self::UTF32LE_BOM, 'UTF-32LE'); + self::guessEncodingTestBom($encoding, $first4, self::UTF16LE_BOM, 'UTF-16LE'); + } + + return $encoding; + } + + public static function guessEncoding(string $filename, string $dflt = self::DEFAULT_FALLBACK_ENCODING): string + { + $encoding = self::guessEncodingBom($filename); + if ($encoding === '') { + $encoding = self::guessEncodingNoBom($filename); + } + + return ($encoding === '') ? $dflt : $encoding; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php new file mode 100644 index 00000000..fc298957 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Csv/Delimiter.php @@ -0,0 +1,151 @@ +fileHandle = $fileHandle; + $this->escapeCharacter = $escapeCharacter; + $this->enclosure = $enclosure; + + $this->countPotentialDelimiters(); + } + + public function getDefaultDelimiter(): string + { + return self::POTENTIAL_DELIMETERS[0]; + } + + public function linesCounted(): int + { + return $this->numberLines; + } + + protected function countPotentialDelimiters(): void + { + $this->counts = array_fill_keys(self::POTENTIAL_DELIMETERS, []); + $delimiterKeys = array_flip(self::POTENTIAL_DELIMETERS); + + // Count how many times each of the potential delimiters appears in each line + $this->numberLines = 0; + while (($line = $this->getNextLine()) !== false && (++$this->numberLines < 1000)) { + $this->countDelimiterValues($line, $delimiterKeys); + } + } + + protected function countDelimiterValues(string $line, array $delimiterKeys): void + { + $splitString = str_split($line, 1); + if (is_array($splitString)) { + $distribution = array_count_values($splitString); + $countLine = array_intersect_key($distribution, $delimiterKeys); + + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + $this->counts[$delimiter][] = $countLine[$delimiter] ?? 0; + } + } + } + + public function infer(): ?string + { + // Calculate the mean square deviations for each delimiter + // (ignoring delimiters that haven't been found consistently) + $meanSquareDeviations = []; + $middleIdx = floor(($this->numberLines - 1) / 2); + + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + $series = $this->counts[$delimiter]; + sort($series); + + $median = ($this->numberLines % 2) + ? $series[$middleIdx] + : ($series[$middleIdx] + $series[$middleIdx + 1]) / 2; + + if ($median === 0) { + continue; + } + + $meanSquareDeviations[$delimiter] = array_reduce( + $series, + function ($sum, $value) use ($median) { + return $sum + ($value - $median) ** 2; + } + ) / count($series); + } + + // ... and pick the delimiter with the smallest mean square deviation + // (in case of ties, the order in potentialDelimiters is respected) + $min = INF; + foreach (self::POTENTIAL_DELIMETERS as $delimiter) { + if (!isset($meanSquareDeviations[$delimiter])) { + continue; + } + + if ($meanSquareDeviations[$delimiter] < $min) { + $min = $meanSquareDeviations[$delimiter]; + $this->delimiter = $delimiter; + } + } + + return $this->delimiter; + } + + /** + * Get the next full line from the file. + * + * @return false|string + */ + public function getNextLine() + { + $line = ''; + $enclosure = ($this->escapeCharacter === '' ? '' + : ('(?escapeCharacter, '/') . ')')) + . preg_quote($this->enclosure, '/'); + + do { + // Get the next line in the file + $newLine = fgets($this->fileHandle); + + // Return false if there is no next line + if ($newLine === false) { + return false; + } + + // Add the new line to the line passed in + $line = $line . $newLine; + + // Drop everything that is enclosed to avoid counting false positives in enclosures + $line = preg_replace('/(' . $enclosure . '.*' . $enclosure . ')/Us', '', $line); + + // See if we have any enclosures left in the line + // if we still have an enclosure then we need to read the next line as well + } while (preg_match('/(' . $enclosure . ')/', $line ?? '') > 0); + + return $line ?? false; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php index e104186a..8fdb162b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/DefaultReadFilter.php @@ -7,13 +7,13 @@ class DefaultReadFilter implements IReadFilter /** * Should this cell be read? * - * @param string $column Column address (as a string value like "A", or "IV") + * @param string $columnAddress Column address (as a string value like "A", or "IV") * @param int $row Row number * @param string $worksheetName Optional worksheet name * * @return bool */ - public function readCell($column, $row, $worksheetName = '') + public function readCell($columnAddress, $row, $worksheetName = '') { return true; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php index 44ab701d..ee2e8d3d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric.php @@ -4,24 +4,36 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\NamedRange; +use PhpOffice\PhpSpreadsheet\DefinedName; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\PageSetup; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Properties; +use PhpOffice\PhpSpreadsheet\Reader\Gnumeric\Styles; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; -use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Borders; -use PhpOffice\PhpSpreadsheet\Style\Fill; -use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; use XMLReader; class Gnumeric extends BaseReader { + const NAMESPACE_GNM = 'http://www.gnumeric.org/v10.dtd'; // gmr in old sheets + + const NAMESPACE_XSI = 'http://www.w3.org/2001/XMLSchema-instance'; + + const NAMESPACE_OFFICE = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'; + + const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink'; + + const NAMESPACE_DC = 'http://purl.org/dc/elements/1.1/'; + + const NAMESPACE_META = 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'; + + const NAMESPACE_OOO = 'http://openoffice.org/2004/office'; + /** * Shared Expressions. * @@ -29,8 +41,30 @@ class Gnumeric extends BaseReader */ private $expressions = []; + /** + * Spreadsheet shared across all functions. + * + * @var Spreadsheet + */ + private $spreadsheet; + + /** @var ReferenceHelper */ private $referenceHelper; + /** @var array */ + public static $mappings = [ + 'dataType' => [ + '10' => DataType::TYPE_NULL, + '20' => DataType::TYPE_BOOL, + '30' => DataType::TYPE_NUMERIC, // Integer doesn't exist in Excel + '40' => DataType::TYPE_NUMERIC, // Float + '50' => DataType::TYPE_ERROR, + '60' => DataType::TYPE_STRING, + //'70': // Cell Range + //'80': // Array + ], + ]; + /** * Create a new Gnumeric. */ @@ -43,51 +77,50 @@ public function __construct() /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @throws Exception - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { - File::assertFile($pFilename); - // Check if gzlib functions are available - if (!function_exists('gzread')) { - throw new Exception('gzlib library is not enabled'); + if (File::testFileNoThrow($filename) && function_exists('gzread')) { + // Read signature data (first 3 bytes) + $fh = fopen($filename, 'rb'); + if ($fh !== false) { + $data = fread($fh, 2); + fclose($fh); + } } - // Read signature data (first 3 bytes) - $fh = fopen($pFilename, 'r'); - $data = fread($fh, 2); - fclose($fh); + return isset($data) && $data === chr(0x1F) . chr(0x8B); + } - return $data == chr(0x1F) . chr(0x8B); + private static function matchXml(XMLReader $xml, string $expectedLocalName): bool + { + return $xml->namespaceURI === self::NAMESPACE_GNM + && $xml->localName === $expectedLocalName + && $xml->nodeType === XMLReader::ELEMENT; } /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); + File::assertFile($filename); $xml = new XMLReader(); - $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions()); + $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetNames = []; while ($xml->read()) { - if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) { + if (self::matchXml($xml, 'SheetName')) { $xml->read(); // Move onto the value node $worksheetNames[] = (string) $xml->value; - } elseif ($xml->name == 'gnm:Sheets') { + } elseif (self::matchXml($xml, 'Sheets')) { // break out of the loop once we've got our sheet names rather than parse the entire file break; } @@ -99,21 +132,21 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename); $xml = new XMLReader(); - $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($pFilename)), null, Settings::getLibXmlLoaderOptions()); + $xml->xml($this->securityScanner->scanFile('compress.zlib://' . realpath($filename)), null, Settings::getLibXmlLoaderOptions()); $xml->setParserProperty(2, true); $worksheetInfo = []; while ($xml->read()) { - if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) { + if (self::matchXml($xml, 'Sheet')) { $tmpInfo = [ 'worksheetName' => '', 'lastColumnLetter' => 'A', @@ -123,14 +156,14 @@ public function listWorksheetInfo($pFilename) ]; while ($xml->read()) { - if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) { + if (self::matchXml($xml, 'Name')) { $xml->read(); // Move onto the value node $tmpInfo['worksheetName'] = (string) $xml->value; - } elseif ($xml->name == 'gnm:MaxCol' && $xml->nodeType == XMLReader::ELEMENT) { + } elseif (self::matchXml($xml, 'MaxCol')) { $xml->read(); // Move onto the value node $tmpInfo['lastColumnIndex'] = (int) $xml->value; $tmpInfo['totalColumns'] = (int) $xml->value + 1; - } elseif ($xml->name == 'gnm:MaxRow' && $xml->nodeType == XMLReader::ELEMENT) { + } elseif (self::matchXml($xml, 'MaxRow')) { $xml->read(); // Move onto the value node $tmpInfo['totalRows'] = (int) $xml->value + 1; @@ -164,236 +197,95 @@ private function gzfileGetContents($filename) return $data; } + public static function gnumericMappings(): array + { + return array_merge(self::$mappings, Styles::$mappings); + } + + private function processComments(SimpleXMLElement $sheet): void + { + if ((!$this->readDataOnly) && (isset($sheet->Objects))) { + foreach ($sheet->Objects->children(self::NAMESPACE_GNM) as $key => $comment) { + $commentAttributes = $comment->attributes(); + // Only comment objects are handled at the moment + if ($commentAttributes && $commentAttributes->Text) { + $this->spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound) + ->setAuthor((string) $commentAttributes->Author) + ->setText($this->parseRichText((string) $commentAttributes->Text)); + } + } + } + } + + /** + * @param mixed $value + */ + private static function testSimpleXml($value): SimpleXMLElement + { + return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); + } + /** * Loads Spreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); + $spreadsheet->removeSheetByIndex(0); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. - * - * @param string $pFilename - * @param Spreadsheet $spreadsheet - * - * @throws Exception - * - * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting(string $filename, Spreadsheet $spreadsheet): Spreadsheet { - File::assertFile($pFilename); + $this->spreadsheet = $spreadsheet; + File::assertFile($filename); - $gFileData = $this->gzfileGetContents($pFilename); + $gFileData = $this->gzfileGetContents($filename); - $xml = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); - $namespacesMeta = $xml->getNamespaces(true); + $xml2 = simplexml_load_string($this->securityScanner->scan($gFileData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions()); + $xml = self::testSimpleXml($xml2); - $gnmXML = $xml->children($namespacesMeta['gnm']); - - $docProps = $spreadsheet->getProperties(); - // Document Properties are held differently, depending on the version of Gnumeric - if (isset($namespacesMeta['office'])) { - $officeXML = $xml->children($namespacesMeta['office']); - $officeDocXML = $officeXML->{'document-meta'}; - $officeDocMetaXML = $officeDocXML->meta; - - foreach ($officeDocMetaXML as $officePropertyData) { - $officePropertyDC = []; - if (isset($namespacesMeta['dc'])) { - $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); - } - foreach ($officePropertyDC as $propertyName => $propertyValue) { - $propertyValue = (string) $propertyValue; - switch ($propertyName) { - case 'title': - $docProps->setTitle(trim($propertyValue)); - - break; - case 'subject': - $docProps->setSubject(trim($propertyValue)); - - break; - case 'creator': - $docProps->setCreator(trim($propertyValue)); - $docProps->setLastModifiedBy(trim($propertyValue)); - - break; - case 'date': - $creationDate = strtotime(trim($propertyValue)); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); - - break; - case 'description': - $docProps->setDescription(trim($propertyValue)); - - break; - } - } - $officePropertyMeta = []; - if (isset($namespacesMeta['meta'])) { - $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); - } - foreach ($officePropertyMeta as $propertyName => $propertyValue) { - $attributes = $propertyValue->attributes($namespacesMeta['meta']); - $propertyValue = (string) $propertyValue; - switch ($propertyName) { - case 'keyword': - $docProps->setKeywords(trim($propertyValue)); - - break; - case 'initial-creator': - $docProps->setCreator(trim($propertyValue)); - $docProps->setLastModifiedBy(trim($propertyValue)); - - break; - case 'creation-date': - $creationDate = strtotime(trim($propertyValue)); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); - - break; - case 'user-defined': - [, $attrName] = explode(':', $attributes['name']); - switch ($attrName) { - case 'publisher': - $docProps->setCompany(trim($propertyValue)); - - break; - case 'category': - $docProps->setCategory(trim($propertyValue)); - - break; - case 'manager': - $docProps->setManager(trim($propertyValue)); - - break; - } - - break; - } - } - } - } elseif (isset($gnmXML->Summary)) { - foreach ($gnmXML->Summary->Item as $summaryItem) { - $propertyName = $summaryItem->name; - $propertyValue = $summaryItem->{'val-string'}; - switch ($propertyName) { - case 'title': - $docProps->setTitle(trim($propertyValue)); - - break; - case 'comments': - $docProps->setDescription(trim($propertyValue)); - - break; - case 'keywords': - $docProps->setKeywords(trim($propertyValue)); - - break; - case 'category': - $docProps->setCategory(trim($propertyValue)); - - break; - case 'manager': - $docProps->setManager(trim($propertyValue)); - - break; - case 'author': - $docProps->setCreator(trim($propertyValue)); - $docProps->setLastModifiedBy(trim($propertyValue)); - - break; - case 'company': - $docProps->setCompany(trim($propertyValue)); - - break; - } - } - } + $gnmXML = $xml->children(self::NAMESPACE_GNM); + (new Properties($this->spreadsheet))->readProperties($xml, $gnmXML); $worksheetID = 0; - foreach ($gnmXML->Sheets->Sheet as $sheet) { + foreach ($gnmXML->Sheets->Sheet as $sheetOrNull) { + $sheet = self::testSimpleXml($sheetOrNull); $worksheetName = (string) $sheet->Name; - if ((isset($this->loadSheetsOnly)) && (!in_array($worksheetName, $this->loadSheetsOnly))) { + if (is_array($this->loadSheetsOnly) && !in_array($worksheetName, $this->loadSheetsOnly, true)) { continue; } $maxRow = $maxCol = 0; // Create new Worksheet - $spreadsheet->createSheet(); - $spreadsheet->setActiveSheetIndex($worksheetID); + $this->spreadsheet->createSheet(); + $this->spreadsheet->setActiveSheetIndex($worksheetID); // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet // name in line with the formula, not the reverse - $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); - - if ((!$this->readDataOnly) && (isset($sheet->PrintInformation))) { - if (isset($sheet->PrintInformation->Margins)) { - foreach ($sheet->PrintInformation->Margins->children('gnm', true) as $key => $margin) { - $marginAttributes = $margin->attributes(); - $marginSize = 72 / 100; // Default - switch ($marginAttributes['PrefUnit']) { - case 'mm': - $marginSize = (int) ($marginAttributes['Points']) / 100; - - break; - } - switch ($key) { - case 'top': - $spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize); - - break; - case 'bottom': - $spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize); - - break; - case 'left': - $spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize); - - break; - case 'right': - $spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize); - - break; - case 'header': - $spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize); - - break; - case 'footer': - $spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize); - - break; - } - } - } + $this->spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); + + if (!$this->readDataOnly) { + (new PageSetup($this->spreadsheet)) + ->printInformation($sheet) + ->sheetMargins($sheet); } - foreach ($sheet->Cells->Cell as $cell) { - $cellAttributes = $cell->attributes(); + foreach ($sheet->Cells->Cell as $cellOrNull) { + $cell = self::testSimpleXml($cellOrNull); + $cellAttributes = self::testSimpleXml($cell->attributes()); $row = (int) $cellAttributes->Row + 1; $column = (int) $cellAttributes->Col; - if ($row > $maxRow) { - $maxRow = $row; - } - if ($column > $maxCol) { - $maxCol = $column; - } + $maxRow = max($maxRow, $row); + $maxCol = max($maxCol, $column); $column = Coordinate::stringFromColumnIndex($column + 1); @@ -404,472 +296,235 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) } } - $ValueType = $cellAttributes->ValueType; - $ExprID = (string) $cellAttributes->ExprID; - $type = DataType::TYPE_FORMULA; - if ($ExprID > '') { - if (((string) $cell) > '') { - $this->expressions[$ExprID] = [ - 'column' => $cellAttributes->Col, - 'row' => $cellAttributes->Row, - 'formula' => (string) $cell, - ]; - } else { - $expression = $this->expressions[$ExprID]; - - $cell = $this->referenceHelper->updateFormulaReferences( - $expression['formula'], - 'A1', - $cellAttributes->Col - $expression['column'], - $cellAttributes->Row - $expression['row'], - $worksheetName - ); - } - $type = DataType::TYPE_FORMULA; - } else { - switch ($ValueType) { - case '10': // NULL - $type = DataType::TYPE_NULL; - - break; - case '20': // Boolean - $type = DataType::TYPE_BOOL; - $cell = $cell == 'TRUE'; - - break; - case '30': // Integer - $cell = (int) $cell; - // Excel 2007+ doesn't differentiate between integer and float, so set the value and dropthru to the next (numeric) case - // no break - case '40': // Float - $type = DataType::TYPE_NUMERIC; - - break; - case '50': // Error - $type = DataType::TYPE_ERROR; - - break; - case '60': // String - $type = DataType::TYPE_STRING; - - break; - case '70': // Cell Range - case '80': // Array - } - } - $spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit($cell, $type); + $this->loadCell($cell, $worksheetName, $cellAttributes, $column, $row); } - if ((!$this->readDataOnly) && (isset($sheet->Objects))) { - foreach ($sheet->Objects->children('gnm', true) as $key => $comment) { - $commentAttributes = $comment->attributes(); - // Only comment objects are handled at the moment - if ($commentAttributes->Text) { - $spreadsheet->getActiveSheet()->getComment((string) $commentAttributes->ObjectBound)->setAuthor((string) $commentAttributes->Author)->setText($this->parseRichText((string) $commentAttributes->Text)); - } - } - } - foreach ($sheet->Styles->StyleRegion as $styleRegion) { - $styleAttributes = $styleRegion->attributes(); - if (($styleAttributes['startRow'] <= $maxRow) && - ($styleAttributes['startCol'] <= $maxCol)) { - $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1); - $startRow = $styleAttributes['startRow'] + 1; - - $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; - $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1); - $endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow']; - $endRow += 1; - $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; - - $styleAttributes = $styleRegion->Style->attributes(); - - // We still set the number format mask for date/time values, even if readDataOnly is true - if ((!$this->readDataOnly) || - (Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) { - $styleArray = []; - $styleArray['numberFormat']['formatCode'] = (string) $styleAttributes['Format']; - // If readDataOnly is false, we set all formatting information - if (!$this->readDataOnly) { - switch ($styleAttributes['HAlign']) { - case '1': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_GENERAL; - - break; - case '2': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_LEFT; - - break; - case '4': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_RIGHT; - - break; - case '8': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_CENTER; - - break; - case '16': - case '64': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_CENTER_CONTINUOUS; - - break; - case '32': - $styleArray['alignment']['horizontal'] = Alignment::HORIZONTAL_JUSTIFY; - - break; - } - - switch ($styleAttributes['VAlign']) { - case '1': - $styleArray['alignment']['vertical'] = Alignment::VERTICAL_TOP; - - break; - case '2': - $styleArray['alignment']['vertical'] = Alignment::VERTICAL_BOTTOM; - - break; - case '4': - $styleArray['alignment']['vertical'] = Alignment::VERTICAL_CENTER; - - break; - case '8': - $styleArray['alignment']['vertical'] = Alignment::VERTICAL_JUSTIFY; - - break; - } - - $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1'; - $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1'; - $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0; - - $RGB = self::parseGnumericColour($styleAttributes['Fore']); - $styleArray['font']['color']['rgb'] = $RGB; - $RGB = self::parseGnumericColour($styleAttributes['Back']); - $shade = $styleAttributes['Shade']; - if (($RGB != '000000') || ($shade != '0')) { - $styleArray['fill']['color']['rgb'] = $styleArray['fill']['startColor']['rgb'] = $RGB; - $RGB2 = self::parseGnumericColour($styleAttributes['PatternColor']); - $styleArray['fill']['endColor']['rgb'] = $RGB2; - switch ($shade) { - case '1': - $styleArray['fill']['fillType'] = Fill::FILL_SOLID; - - break; - case '2': - $styleArray['fill']['fillType'] = Fill::FILL_GRADIENT_LINEAR; - - break; - case '3': - $styleArray['fill']['fillType'] = Fill::FILL_GRADIENT_PATH; - - break; - case '4': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKDOWN; - - break; - case '5': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKGRAY; - - break; - case '6': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKGRID; - - break; - case '7': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKHORIZONTAL; - - break; - case '8': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKTRELLIS; - - break; - case '9': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKUP; - - break; - case '10': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_DARKVERTICAL; - - break; - case '11': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_GRAY0625; - - break; - case '12': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_GRAY125; - - break; - case '13': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTDOWN; - - break; - case '14': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTGRAY; - - break; - case '15': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTGRID; - - break; - case '16': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTHORIZONTAL; - - break; - case '17': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTTRELLIS; - - break; - case '18': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTUP; - - break; - case '19': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_LIGHTVERTICAL; - - break; - case '20': - $styleArray['fill']['fillType'] = Fill::FILL_PATTERN_MEDIUMGRAY; - - break; - } - } - - $fontAttributes = $styleRegion->Style->Font->attributes(); - $styleArray['font']['name'] = (string) $styleRegion->Style->Font; - $styleArray['font']['size'] = (int) ($fontAttributes['Unit']); - $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1'; - $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1'; - $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1'; - switch ($fontAttributes['Underline']) { - case '1': - $styleArray['font']['underline'] = Font::UNDERLINE_SINGLE; - - break; - case '2': - $styleArray['font']['underline'] = Font::UNDERLINE_DOUBLE; - - break; - case '3': - $styleArray['font']['underline'] = Font::UNDERLINE_SINGLEACCOUNTING; - - break; - case '4': - $styleArray['font']['underline'] = Font::UNDERLINE_DOUBLEACCOUNTING; - - break; - default: - $styleArray['font']['underline'] = Font::UNDERLINE_NONE; - - break; - } - switch ($fontAttributes['Script']) { - case '1': - $styleArray['font']['superscript'] = true; - - break; - case '-1': - $styleArray['font']['subscript'] = true; - - break; - } - - if (isset($styleRegion->Style->StyleBorder)) { - if (isset($styleRegion->Style->StyleBorder->Top)) { - $styleArray['borders']['top'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Top->attributes()); - } - if (isset($styleRegion->Style->StyleBorder->Bottom)) { - $styleArray['borders']['bottom'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Bottom->attributes()); - } - if (isset($styleRegion->Style->StyleBorder->Left)) { - $styleArray['borders']['left'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Left->attributes()); - } - if (isset($styleRegion->Style->StyleBorder->Right)) { - $styleArray['borders']['right'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Right->attributes()); - } - if ((isset($styleRegion->Style->StyleBorder->Diagonal)) && (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}))) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH; - } elseif (isset($styleRegion->Style->StyleBorder->Diagonal)) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP; - } elseif (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'})) { - $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}->attributes()); - $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN; - } - } - if (isset($styleRegion->Style->HyperLink)) { - // TO DO - $hyperlink = $styleRegion->Style->HyperLink->attributes(); - } - } - $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); - } - } + if ($sheet->Styles !== null) { + (new Styles($this->spreadsheet, $this->readDataOnly))->read($sheet, $maxRow, $maxCol); } - if ((!$this->readDataOnly) && (isset($sheet->Cols))) { - // Column Widths - $columnAttributes = $sheet->Cols->attributes(); - $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; - $c = 0; - foreach ($sheet->Cols->ColInfo as $columnOverride) { - $columnAttributes = $columnOverride->attributes(); - $column = $columnAttributes['No']; - $columnWidth = $columnAttributes['Unit'] / 5.4; - $hidden = (isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1'); - $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; - while ($c < $column) { - $spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth); - ++$c; - } - while (($c < ($column + $columnCount)) && ($c <= $maxCol)) { - $spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($columnWidth); - if ($hidden) { - $spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setVisible(false); - } - ++$c; - } - } - while ($c <= $maxCol) { - $spreadsheet->getActiveSheet()->getColumnDimension(Coordinate::stringFromColumnIndex($c + 1))->setWidth($defaultWidth); - ++$c; - } - } - - if ((!$this->readDataOnly) && (isset($sheet->Rows))) { - // Row Heights - $rowAttributes = $sheet->Rows->attributes(); - $defaultHeight = $rowAttributes['DefaultSizePts']; - $r = 0; - - foreach ($sheet->Rows->RowInfo as $rowOverride) { - $rowAttributes = $rowOverride->attributes(); - $row = $rowAttributes['No']; - $rowHeight = $rowAttributes['Unit']; - $hidden = (isset($rowAttributes['Hidden'])) && ($rowAttributes['Hidden'] == '1'); - $rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1; - while ($r < $row) { - ++$r; - $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); - } - while (($r < ($row + $rowCount)) && ($r < $maxRow)) { - ++$r; - $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); - if ($hidden) { - $spreadsheet->getActiveSheet()->getRowDimension($r)->setVisible(false); - } - } - } - while ($r < $maxRow) { - ++$r; - $spreadsheet->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); - } - } - - // Handle Merged Cells in this worksheet - if (isset($sheet->MergedRegions)) { - foreach ($sheet->MergedRegions->Merge as $mergeCells) { - if (strpos($mergeCells, ':') !== false) { - $spreadsheet->getActiveSheet()->mergeCells($mergeCells); - } - } - } + $this->processComments($sheet); + $this->processColumnWidths($sheet, $maxCol); + $this->processRowHeights($sheet, $maxRow); + $this->processMergedCells($sheet); + $this->processAutofilter($sheet); + $this->setSelectedCells($sheet); ++$worksheetID; } - // Loop through definedNames (global named ranges) - if (isset($gnmXML->Names)) { - foreach ($gnmXML->Names->Name as $namedRange) { - $name = (string) $namedRange->name; - $range = (string) $namedRange->value; - if (stripos($range, '#REF!') !== false) { - continue; - } + $this->processDefinedNames($gnmXML); - $range = Worksheet::extractSheetTitle($range, true); - $range[0] = trim($range[0], "'"); - if ($worksheet = $spreadsheet->getSheetByName($range[0])) { - $extractedRange = str_replace('$', '', $range[1]); - $spreadsheet->addNamedRange(new NamedRange($name, $worksheet, $extractedRange)); - } - } - } + $this->setSelectedSheet($gnmXML); // Return - return $spreadsheet; + return $this->spreadsheet; } - private static function parseBorderAttributes($borderAttributes) + private function setSelectedSheet(SimpleXMLElement $gnmXML): void { - $styleArray = []; - if (isset($borderAttributes['Color'])) { - $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); + if (isset($gnmXML->UIData)) { + $attributes = self::testSimpleXml($gnmXML->UIData->attributes()); + $selectedSheet = (int) $attributes['SelectedTab']; + $this->spreadsheet->setActiveSheetIndex($selectedSheet); } + } - switch ($borderAttributes['Style']) { - case '0': - $styleArray['borderStyle'] = Border::BORDER_NONE; + private function setSelectedCells(?SimpleXMLElement $sheet): void + { + if ($sheet !== null && isset($sheet->Selections)) { + foreach ($sheet->Selections as $selection) { + $startCol = (int) ($selection->StartCol ?? 0); + $startRow = (int) ($selection->StartRow ?? 0) + 1; + $endCol = (int) ($selection->EndCol ?? $startCol); + $endRow = (int) ($selection->endRow ?? 0) + 1; - break; - case '1': - $styleArray['borderStyle'] = Border::BORDER_THIN; + $startColumn = Coordinate::stringFromColumnIndex($startCol + 1); + $endColumn = Coordinate::stringFromColumnIndex($endCol + 1); - break; - case '2': - $styleArray['borderStyle'] = Border::BORDER_MEDIUM; + $startCell = "{$startColumn}{$startRow}"; + $endCell = "{$endColumn}{$endRow}"; + $selectedRange = $startCell . (($endCell !== $startCell) ? ':' . $endCell : ''); + $this->spreadsheet->getActiveSheet()->setSelectedCell($selectedRange); break; - case '3': - $styleArray['borderStyle'] = Border::BORDER_SLANTDASHDOT; + } + } + } - break; - case '4': - $styleArray['borderStyle'] = Border::BORDER_DASHED; + private function processMergedCells(?SimpleXMLElement $sheet): void + { + // Handle Merged Cells in this worksheet + if ($sheet !== null && isset($sheet->MergedRegions)) { + foreach ($sheet->MergedRegions->Merge as $mergeCells) { + if (strpos((string) $mergeCells, ':') !== false) { + $this->spreadsheet->getActiveSheet()->mergeCells($mergeCells); + } + } + } + } - break; - case '5': - $styleArray['borderStyle'] = Border::BORDER_THICK; + private function processAutofilter(?SimpleXMLElement $sheet): void + { + if ($sheet !== null && isset($sheet->Filters)) { + foreach ($sheet->Filters->Filter as $autofilter) { + if ($autofilter !== null) { + $attributes = $autofilter->attributes(); + if (isset($attributes['Area'])) { + $this->spreadsheet->getActiveSheet()->setAutoFilter((string) $attributes['Area']); + } + } + } + } + } - break; - case '6': - $styleArray['borderStyle'] = Border::BORDER_DOUBLE; + private function setColumnWidth(int $whichColumn, float $defaultWidth): void + { + $columnDimension = $this->spreadsheet->getActiveSheet() + ->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); + if ($columnDimension !== null) { + $columnDimension->setWidth($defaultWidth); + } + } - break; - case '7': - $styleArray['borderStyle'] = Border::BORDER_DOTTED; + private function setColumnInvisible(int $whichColumn): void + { + $columnDimension = $this->spreadsheet->getActiveSheet() + ->getColumnDimension(Coordinate::stringFromColumnIndex($whichColumn + 1)); + if ($columnDimension !== null) { + $columnDimension->setVisible(false); + } + } - break; - case '8': - $styleArray['borderStyle'] = Border::BORDER_MEDIUMDASHED; + private function processColumnLoop(int $whichColumn, int $maxCol, ?SimpleXMLElement $columnOverride, float $defaultWidth): int + { + $columnOverride = self::testSimpleXml($columnOverride); + $columnAttributes = self::testSimpleXml($columnOverride->attributes()); + $column = $columnAttributes['No']; + $columnWidth = ((float) $columnAttributes['Unit']) / 5.4; + $hidden = (isset($columnAttributes['Hidden'])) && ((string) $columnAttributes['Hidden'] == '1'); + $columnCount = (int) ($columnAttributes['Count'] ?? 1); + while ($whichColumn < $column) { + $this->setColumnWidth($whichColumn, $defaultWidth); + ++$whichColumn; + } + while (($whichColumn < ($column + $columnCount)) && ($whichColumn <= $maxCol)) { + $this->setColumnWidth($whichColumn, $columnWidth); + if ($hidden) { + $this->setColumnInvisible($whichColumn); + } + ++$whichColumn; + } - break; - case '9': - $styleArray['borderStyle'] = Border::BORDER_DASHDOT; + return $whichColumn; + } - break; - case '10': - $styleArray['borderStyle'] = Border::BORDER_MEDIUMDASHDOT; + private function processColumnWidths(?SimpleXMLElement $sheet, int $maxCol): void + { + if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Cols))) { + // Column Widths + $defaultWidth = 0; + $columnAttributes = $sheet->Cols->attributes(); + if ($columnAttributes !== null) { + $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; + } + $whichColumn = 0; + foreach ($sheet->Cols->ColInfo as $columnOverride) { + $whichColumn = $this->processColumnLoop($whichColumn, $maxCol, $columnOverride, $defaultWidth); + } + while ($whichColumn <= $maxCol) { + $this->setColumnWidth($whichColumn, $defaultWidth); + ++$whichColumn; + } + } + } - break; - case '11': - $styleArray['borderStyle'] = Border::BORDER_DASHDOTDOT; + private function setRowHeight(int $whichRow, float $defaultHeight): void + { + $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); + if ($rowDimension !== null) { + $rowDimension->setRowHeight($defaultHeight); + } + } - break; - case '12': - $styleArray['borderStyle'] = Border::BORDER_MEDIUMDASHDOTDOT; + private function setRowInvisible(int $whichRow): void + { + $rowDimension = $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow); + if ($rowDimension !== null) { + $rowDimension->setVisible(false); + } + } - break; - case '13': - $styleArray['borderStyle'] = Border::BORDER_MEDIUMDASHDOTDOT; + private function processRowLoop(int $whichRow, int $maxRow, ?SimpleXMLElement $rowOverride, float $defaultHeight): int + { + $rowOverride = self::testSimpleXml($rowOverride); + $rowAttributes = self::testSimpleXml($rowOverride->attributes()); + $row = $rowAttributes['No']; + $rowHeight = (float) $rowAttributes['Unit']; + $hidden = (isset($rowAttributes['Hidden'])) && ((string) $rowAttributes['Hidden'] == '1'); + $rowCount = (int) ($rowAttributes['Count'] ?? 1); + while ($whichRow < $row) { + ++$whichRow; + $this->setRowHeight($whichRow, $defaultHeight); + } + while (($whichRow < ($row + $rowCount)) && ($whichRow < $maxRow)) { + ++$whichRow; + $this->setRowHeight($whichRow, $rowHeight); + if ($hidden) { + $this->setRowInvisible($whichRow); + } + } - break; + return $whichRow; + } + + private function processRowHeights(?SimpleXMLElement $sheet, int $maxRow): void + { + if ((!$this->readDataOnly) && $sheet !== null && (isset($sheet->Rows))) { + // Row Heights + $defaultHeight = 0; + $rowAttributes = $sheet->Rows->attributes(); + if ($rowAttributes !== null) { + $defaultHeight = (float) $rowAttributes['DefaultSizePts']; + } + $whichRow = 0; + + foreach ($sheet->Rows->RowInfo as $rowOverride) { + $whichRow = $this->processRowLoop($whichRow, $maxRow, $rowOverride, $defaultHeight); + } + // never executed, I can't figure out any circumstances + // under which it would be executed, and, even if + // such exist, I'm not convinced this is needed. + //while ($whichRow < $maxRow) { + // ++$whichRow; + // $this->spreadsheet->getActiveSheet()->getRowDimension($whichRow)->setRowHeight($defaultHeight); + //} } + } + + private function processDefinedNames(?SimpleXMLElement $gnmXML): void + { + // Loop through definedNames (global named ranges) + if ($gnmXML !== null && isset($gnmXML->Names)) { + foreach ($gnmXML->Names->Name as $definedName) { + $name = (string) $definedName->name; + $value = (string) $definedName->value; + if (stripos($value, '#REF!') !== false) { + continue; + } - return $styleArray; + [$worksheetName] = Worksheet::extractSheetTitle($value, true); + $worksheetName = trim($worksheetName, "'"); + $worksheet = $this->spreadsheet->getSheetByName($worksheetName); + // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet + if ($worksheet !== null) { + $this->spreadsheet->addDefinedName(DefinedName::createInstance($name, $worksheet, $value)); + } + } + } } - private function parseRichText($is) + private function parseRichText(string $is): RichText { $value = new RichText(); $value->createText($is); @@ -877,13 +532,50 @@ private function parseRichText($is) return $value; } - private static function parseGnumericColour($gnmColour) - { - [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour); - $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); - $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); - $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); + private function loadCell( + SimpleXMLElement $cell, + string $worksheetName, + SimpleXMLElement $cellAttributes, + string $column, + int $row + ): void { + $ValueType = $cellAttributes->ValueType; + $ExprID = (string) $cellAttributes->ExprID; + $type = DataType::TYPE_FORMULA; + if ($ExprID > '') { + if (((string) $cell) > '') { + $this->expressions[$ExprID] = [ + 'column' => $cellAttributes->Col, + 'row' => $cellAttributes->Row, + 'formula' => (string) $cell, + ]; + } else { + $expression = $this->expressions[$ExprID]; + + $cell = $this->referenceHelper->updateFormulaReferences( + $expression['formula'], + 'A1', + $cellAttributes->Col - $expression['column'], + $cellAttributes->Row - $expression['row'], + $worksheetName + ); + } + $type = DataType::TYPE_FORMULA; + } else { + $vtype = (string) $ValueType; + if (array_key_exists($vtype, self::$mappings['dataType'])) { + $type = self::$mappings['dataType'][$vtype]; + } + if ($vtype === '20') { // Boolean + $cell = $cell == 'TRUE'; + } + } - return $gnmR . $gnmG . $gnmB; + $this->spreadsheet->getActiveSheet()->getCell($column . $row)->setValueExplicit((string) $cell, $type); + if (isset($cellAttributes->ValueFormat)) { + $this->spreadsheet->getActiveSheet()->getCell($column . $row) + ->getStyle()->getNumberFormat() + ->setFormatCode((string) $cellAttributes->ValueFormat); + } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php new file mode 100644 index 00000000..5b501e0f --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/PageSetup.php @@ -0,0 +1,142 @@ +spreadsheet = $spreadsheet; + } + + public function printInformation(SimpleXMLElement $sheet): self + { + if (isset($sheet->PrintInformation)) { + $printInformation = $sheet->PrintInformation[0]; + if (!$printInformation) { + return $this; + } + + $scale = (string) $printInformation->Scale->attributes()['percentage']; + $pageOrder = (string) $printInformation->order; + $orientation = (string) $printInformation->orientation; + $horizontalCentered = (string) $printInformation->hcenter->attributes()['value']; + $verticalCentered = (string) $printInformation->vcenter->attributes()['value']; + + $this->spreadsheet->getActiveSheet()->getPageSetup() + ->setPageOrder($pageOrder === 'r_then_d' ? WorksheetPageSetup::PAGEORDER_OVER_THEN_DOWN : WorksheetPageSetup::PAGEORDER_DOWN_THEN_OVER) + ->setScale((int) $scale) + ->setOrientation($orientation ?? WorksheetPageSetup::ORIENTATION_DEFAULT) + ->setHorizontalCentered((bool) $horizontalCentered) + ->setVerticalCentered((bool) $verticalCentered); + } + + return $this; + } + + public function sheetMargins(SimpleXMLElement $sheet): self + { + if (isset($sheet->PrintInformation, $sheet->PrintInformation->Margins)) { + $marginSet = [ + // Default Settings + 'top' => 0.75, + 'header' => 0.3, + 'left' => 0.7, + 'right' => 0.7, + 'bottom' => 0.75, + 'footer' => 0.3, + ]; + + $marginSet = $this->buildMarginSet($sheet, $marginSet); + $this->adjustMargins($marginSet); + } + + return $this; + } + + private function buildMarginSet(SimpleXMLElement $sheet, array $marginSet): array + { + foreach ($sheet->PrintInformation->Margins->children(Gnumeric::NAMESPACE_GNM) as $key => $margin) { + $marginAttributes = $margin->attributes(); + $marginSize = ($marginAttributes['Points']) ?? 72; // Default is 72pt + // Convert value in points to inches + $marginSize = PageMargins::fromPoints((float) $marginSize); + $marginSet[$key] = $marginSize; + } + + return $marginSet; + } + + private function adjustMargins(array $marginSet): void + { + foreach ($marginSet as $key => $marginSize) { + // Gnumeric is quirky in the way it displays the header/footer values: + // header is actually the sum of top and header; footer is actually the sum of bottom and footer + // then top is actually the header value, and bottom is actually the footer value + switch ($key) { + case 'left': + case 'right': + $this->sheetMargin($key, $marginSize); + + break; + case 'top': + $this->sheetMargin($key, $marginSet['header'] ?? 0); + + break; + case 'bottom': + $this->sheetMargin($key, $marginSet['footer'] ?? 0); + + break; + case 'header': + $this->sheetMargin($key, ($marginSet['top'] ?? 0) - $marginSize); + + break; + case 'footer': + $this->sheetMargin($key, ($marginSet['bottom'] ?? 0) - $marginSize); + + break; + } + } + } + + private function sheetMargin(string $key, float $marginSize): void + { + switch ($key) { + case 'top': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setTop($marginSize); + + break; + case 'bottom': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setBottom($marginSize); + + break; + case 'left': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setLeft($marginSize); + + break; + case 'right': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setRight($marginSize); + + break; + case 'header': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setHeader($marginSize); + + break; + case 'footer': + $this->spreadsheet->getActiveSheet()->getPageMargins()->setFooter($marginSize); + + break; + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php new file mode 100644 index 00000000..23d4067b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Properties.php @@ -0,0 +1,164 @@ +spreadsheet = $spreadsheet; + } + + private function docPropertiesOld(SimpleXMLElement $gnmXML): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($gnmXML->Summary->Item as $summaryItem) { + $propertyName = $summaryItem->name; + $propertyValue = $summaryItem->{'val-string'}; + switch ($propertyName) { + case 'title': + $docProps->setTitle(trim($propertyValue)); + + break; + case 'comments': + $docProps->setDescription(trim($propertyValue)); + + break; + case 'keywords': + $docProps->setKeywords(trim($propertyValue)); + + break; + case 'category': + $docProps->setCategory(trim($propertyValue)); + + break; + case 'manager': + $docProps->setManager(trim($propertyValue)); + + break; + case 'author': + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + + break; + case 'company': + $docProps->setCompany(trim($propertyValue)); + + break; + } + } + } + + private function docPropertiesDC(SimpleXMLElement $officePropertyDC): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = trim((string) $propertyValue); + switch ($propertyName) { + case 'title': + $docProps->setTitle($propertyValue); + + break; + case 'subject': + $docProps->setSubject($propertyValue); + + break; + case 'creator': + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + + break; + case 'date': + $creationDate = $propertyValue; + $docProps->setModified($creationDate); + + break; + case 'description': + $docProps->setDescription($propertyValue); + + break; + } + } + } + + private function docPropertiesMeta(SimpleXMLElement $officePropertyMeta): void + { + $docProps = $this->spreadsheet->getProperties(); + foreach ($officePropertyMeta as $propertyName => $propertyValue) { + if ($propertyValue !== null) { + $attributes = $propertyValue->attributes(Gnumeric::NAMESPACE_META); + $propertyValue = trim((string) $propertyValue); + switch ($propertyName) { + case 'keyword': + $docProps->setKeywords($propertyValue); + + break; + case 'initial-creator': + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + + break; + case 'creation-date': + $creationDate = $propertyValue; + $docProps->setCreated($creationDate); + + break; + case 'user-defined': + if ($attributes) { + [, $attrName] = explode(':', (string) $attributes['name']); + $this->userDefinedProperties($attrName, $propertyValue); + } + + break; + } + } + } + } + + private function userDefinedProperties(string $attrName, string $propertyValue): void + { + $docProps = $this->spreadsheet->getProperties(); + switch ($attrName) { + case 'publisher': + $docProps->setCompany($propertyValue); + + break; + case 'category': + $docProps->setCategory($propertyValue); + + break; + case 'manager': + $docProps->setManager($propertyValue); + + break; + } + } + + public function readProperties(SimpleXMLElement $xml, SimpleXMLElement $gnmXML): void + { + $officeXML = $xml->children(Gnumeric::NAMESPACE_OFFICE); + if (!empty($officeXML)) { + $officeDocXML = $officeXML->{'document-meta'}; + $officeDocMetaXML = $officeDocXML->meta; + + foreach ($officeDocMetaXML as $officePropertyData) { + $officePropertyDC = $officePropertyData->children(Gnumeric::NAMESPACE_DC); + $this->docPropertiesDC($officePropertyDC); + + $officePropertyMeta = $officePropertyData->children(Gnumeric::NAMESPACE_META); + $this->docPropertiesMeta($officePropertyMeta); + } + } elseif (isset($gnmXML->Summary)) { + $this->docPropertiesOld($gnmXML); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php new file mode 100644 index 00000000..e2e9d561 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Gnumeric/Styles.php @@ -0,0 +1,278 @@ + [ + '0' => Border::BORDER_NONE, + '1' => Border::BORDER_THIN, + '2' => Border::BORDER_MEDIUM, + '3' => Border::BORDER_SLANTDASHDOT, + '4' => Border::BORDER_DASHED, + '5' => Border::BORDER_THICK, + '6' => Border::BORDER_DOUBLE, + '7' => Border::BORDER_DOTTED, + '8' => Border::BORDER_MEDIUMDASHED, + '9' => Border::BORDER_DASHDOT, + '10' => Border::BORDER_MEDIUMDASHDOT, + '11' => Border::BORDER_DASHDOTDOT, + '12' => Border::BORDER_MEDIUMDASHDOTDOT, + '13' => Border::BORDER_MEDIUMDASHDOTDOT, + ], + 'fillType' => [ + '1' => Fill::FILL_SOLID, + '2' => Fill::FILL_PATTERN_DARKGRAY, + '3' => Fill::FILL_PATTERN_MEDIUMGRAY, + '4' => Fill::FILL_PATTERN_LIGHTGRAY, + '5' => Fill::FILL_PATTERN_GRAY125, + '6' => Fill::FILL_PATTERN_GRAY0625, + '7' => Fill::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe + '8' => Fill::FILL_PATTERN_DARKVERTICAL, // vertical stripe + '9' => Fill::FILL_PATTERN_DARKDOWN, // diagonal stripe + '10' => Fill::FILL_PATTERN_DARKUP, // reverse diagonal stripe + '11' => Fill::FILL_PATTERN_DARKGRID, // diagoanl crosshatch + '12' => Fill::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch + '13' => Fill::FILL_PATTERN_LIGHTHORIZONTAL, + '14' => Fill::FILL_PATTERN_LIGHTVERTICAL, + '15' => Fill::FILL_PATTERN_LIGHTUP, + '16' => Fill::FILL_PATTERN_LIGHTDOWN, + '17' => Fill::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch + '18' => Fill::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch + ], + 'horizontal' => [ + '1' => Alignment::HORIZONTAL_GENERAL, + '2' => Alignment::HORIZONTAL_LEFT, + '4' => Alignment::HORIZONTAL_RIGHT, + '8' => Alignment::HORIZONTAL_CENTER, + '16' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + '32' => Alignment::HORIZONTAL_JUSTIFY, + '64' => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + ], + 'underline' => [ + '1' => Font::UNDERLINE_SINGLE, + '2' => Font::UNDERLINE_DOUBLE, + '3' => Font::UNDERLINE_SINGLEACCOUNTING, + '4' => Font::UNDERLINE_DOUBLEACCOUNTING, + ], + 'vertical' => [ + '1' => Alignment::VERTICAL_TOP, + '2' => Alignment::VERTICAL_BOTTOM, + '4' => Alignment::VERTICAL_CENTER, + '8' => Alignment::VERTICAL_JUSTIFY, + ], + ]; + + public function __construct(Spreadsheet $spreadsheet, bool $readDataOnly) + { + $this->spreadsheet = $spreadsheet; + $this->readDataOnly = $readDataOnly; + } + + public function read(SimpleXMLElement $sheet, int $maxRow, int $maxCol): void + { + if ($sheet->Styles->StyleRegion !== null) { + $this->readStyles($sheet->Styles->StyleRegion, $maxRow, $maxCol); + } + } + + private function readStyles(SimpleXMLElement $styleRegion, int $maxRow, int $maxCol): void + { + foreach ($styleRegion as $style) { + $styleAttributes = $style->attributes(); + if ($styleAttributes !== null && ($styleAttributes['startRow'] <= $maxRow) && ($styleAttributes['startCol'] <= $maxCol)) { + $cellRange = $this->readStyleRange($styleAttributes, $maxCol, $maxRow); + + $styleAttributes = $style->Style->attributes(); + + $styleArray = []; + // We still set the number format mask for date/time values, even if readDataOnly is true + // so that we can identify whether a float is a float or a date value + $formatCode = $styleAttributes ? (string) $styleAttributes['Format'] : null; + if ($formatCode && Date::isDateTimeFormatCode($formatCode)) { + $styleArray['numberFormat']['formatCode'] = $formatCode; + } + if ($this->readDataOnly === false && $styleAttributes !== null) { + // If readDataOnly is false, we set all formatting information + $styleArray['numberFormat']['formatCode'] = $formatCode; + $styleArray = $this->readStyle($styleArray, $styleAttributes, $style); + } + $this->spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); + } + } + } + + private function addBorderDiagonal(SimpleXMLElement $srssb, array &$styleArray): void + { + if (isset($srssb->Diagonal, $srssb->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_BOTH; + } elseif (isset($srssb->Diagonal)) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->Diagonal->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_UP; + } elseif (isset($srssb->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($srssb->{'Rev-Diagonal'}->attributes()); + $styleArray['borders']['diagonalDirection'] = Borders::DIAGONAL_DOWN; + } + } + + private function addBorderStyle(SimpleXMLElement $srssb, array &$styleArray, string $direction): void + { + $ucDirection = ucfirst($direction); + if (isset($srssb->$ucDirection)) { + $styleArray['borders'][$direction] = self::parseBorderAttributes($srssb->$ucDirection->attributes()); + } + } + + private function calcRotation(SimpleXMLElement $styleAttributes): int + { + $rotation = (int) $styleAttributes->Rotation; + if ($rotation >= 270 && $rotation <= 360) { + $rotation -= 360; + } + $rotation = (abs($rotation) > 90) ? 0 : $rotation; + + return $rotation; + } + + private static function addStyle(array &$styleArray, string $key, string $value): void + { + if (array_key_exists($value, self::$mappings[$key])) { + $styleArray[$key] = self::$mappings[$key][$value]; + } + } + + private static function addStyle2(array &$styleArray, string $key1, string $key, string $value): void + { + if (array_key_exists($value, self::$mappings[$key])) { + $styleArray[$key1][$key] = self::$mappings[$key][$value]; + } + } + + private static function parseBorderAttributes(?SimpleXMLElement $borderAttributes): array + { + $styleArray = []; + if ($borderAttributes !== null) { + if (isset($borderAttributes['Color'])) { + $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes['Color']); + } + + self::addStyle($styleArray, 'borderStyle', (string) $borderAttributes['Style']); + } + + return $styleArray; + } + + private static function parseGnumericColour(string $gnmColour): string + { + [$gnmR, $gnmG, $gnmB] = explode(':', $gnmColour); + $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); + + return $gnmR . $gnmG . $gnmB; + } + + private function addColors(array &$styleArray, SimpleXMLElement $styleAttributes): void + { + $RGB = self::parseGnumericColour((string) $styleAttributes['Fore']); + $styleArray['font']['color']['rgb'] = $RGB; + $RGB = self::parseGnumericColour((string) $styleAttributes['Back']); + $shade = (string) $styleAttributes['Shade']; + if (($RGB !== '000000') || ($shade !== '0')) { + $RGB2 = self::parseGnumericColour((string) $styleAttributes['PatternColor']); + if ($shade === '1') { + $styleArray['fill']['startColor']['rgb'] = $RGB; + $styleArray['fill']['endColor']['rgb'] = $RGB2; + } else { + $styleArray['fill']['endColor']['rgb'] = $RGB; + $styleArray['fill']['startColor']['rgb'] = $RGB2; + } + self::addStyle2($styleArray, 'fill', 'fillType', $shade); + } + } + + private function readStyleRange(SimpleXMLElement $styleAttributes, int $maxCol, int $maxRow): string + { + $startColumn = Coordinate::stringFromColumnIndex((int) $styleAttributes['startCol'] + 1); + $startRow = $styleAttributes['startRow'] + 1; + + $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; + $endColumn = Coordinate::stringFromColumnIndex($endColumn + 1); + + $endRow = 1 + (($styleAttributes['endRow'] > $maxRow) ? $maxRow : (int) $styleAttributes['endRow']); + $cellRange = $startColumn . $startRow . ':' . $endColumn . $endRow; + + return $cellRange; + } + + private function readStyle(array $styleArray, SimpleXMLElement $styleAttributes, SimpleXMLElement $style): array + { + self::addStyle2($styleArray, 'alignment', 'horizontal', (string) $styleAttributes['HAlign']); + self::addStyle2($styleArray, 'alignment', 'vertical', (string) $styleAttributes['VAlign']); + $styleArray['alignment']['wrapText'] = $styleAttributes['WrapText'] == '1'; + $styleArray['alignment']['textRotation'] = $this->calcRotation($styleAttributes); + $styleArray['alignment']['shrinkToFit'] = $styleAttributes['ShrinkToFit'] == '1'; + $styleArray['alignment']['indent'] = ((int) ($styleAttributes['Indent']) > 0) ? $styleAttributes['indent'] : 0; + + $this->addColors($styleArray, $styleAttributes); + + $fontAttributes = $style->Style->Font->attributes(); + if ($fontAttributes !== null) { + $styleArray['font']['name'] = (string) $style->Style->Font; + $styleArray['font']['size'] = (int) ($fontAttributes['Unit']); + $styleArray['font']['bold'] = $fontAttributes['Bold'] == '1'; + $styleArray['font']['italic'] = $fontAttributes['Italic'] == '1'; + $styleArray['font']['strikethrough'] = $fontAttributes['StrikeThrough'] == '1'; + self::addStyle2($styleArray, 'font', 'underline', (string) $fontAttributes['Underline']); + + switch ($fontAttributes['Script']) { + case '1': + $styleArray['font']['superscript'] = true; + + break; + case '-1': + $styleArray['font']['subscript'] = true; + + break; + } + } + + if (isset($style->Style->StyleBorder)) { + $srssb = $style->Style->StyleBorder; + $this->addBorderStyle($srssb, $styleArray, 'top'); + $this->addBorderStyle($srssb, $styleArray, 'bottom'); + $this->addBorderStyle($srssb, $styleArray, 'left'); + $this->addBorderStyle($srssb, $styleArray, 'right'); + $this->addBorderDiagonal($srssb, $styleArray); + } + if (isset($style->Style->HyperLink)) { + // TO DO + $hyperlink = $style->Style->HyperLink->attributes(); + } + + return $styleArray; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php index a255cfd9..15c9f625 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Html.php @@ -7,6 +7,7 @@ use DOMNode; use DOMText; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; @@ -16,8 +17,8 @@ use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use Throwable; -/** PhpSpreadsheet root directory */ class Html extends BaseReader { /** @@ -121,6 +122,7 @@ class Html extends BaseReader ], // Italic ]; + /** @var array */ protected $rowspan = []; /** @@ -134,16 +136,12 @@ public function __construct() /** * Validate that the current file is an HTML file. - * - * @param string $pFilename - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { // Check if file exists try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (Exception $e) { return false; } @@ -158,19 +156,19 @@ public function canRead($pFilename) return $startWithTag && $containsTags && $endsWithTag; } - private function readBeginning() + private function readBeginning(): string { fseek($this->fileHandle, 0); - return fread($this->fileHandle, self::TEST_SAMPLE_SIZE); + return (string) fread($this->fileHandle, self::TEST_SAMPLE_SIZE); } - private function readEnding() + private function readEnding(): string { $meta = stream_get_meta_data($this->fileHandle); $filename = $meta['uri']; - $size = filesize($filename); + $size = (int) filesize($filename); if ($size === 0) { return ''; } @@ -182,52 +180,50 @@ private function readEnding() fseek($this->fileHandle, $size - $blockSize); - return fread($this->fileHandle, $blockSize); + return (string) fread($this->fileHandle, $blockSize); } - private static function startsWithTag($data) + private static function startsWithTag(string $data): bool { return '<' === substr(trim($data), 0, 1); } - private static function endsWithTag($data) + private static function endsWithTag(string $data): bool { return '>' === substr(trim($data), -1, 1); } - private static function containsTags($data) + private static function containsTags(string $data): bool { return strlen($data) !== strlen(strip_tags($data)); } /** * Loads Spreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** * Set input encoding. * - * @param string $pValue Input encoding, eg: 'ANSI' + * @param string $inputEncoding Input encoding, eg: 'ANSI' * * @return $this + * + * @codeCoverageIgnore + * + * @deprecated no use is made of this property */ - public function setInputEncoding($pValue) + public function setInputEncoding($inputEncoding) { - $this->inputEncoding = $pValue; + $this->inputEncoding = $inputEncoding; return $this; } @@ -236,6 +232,10 @@ public function setInputEncoding($pValue) * Get input encoding. * * @return string + * + * @codeCoverageIgnore + * + * @deprecated no use is made of this property */ public function getInputEncoding() { @@ -243,13 +243,17 @@ public function getInputEncoding() } // Data Array used for testing only, should write to Spreadsheet object on completion of tests + + /** @var array */ protected $dataArray = []; + /** @var int */ protected $tableLevel = 0; + /** @var array */ protected $nestedColumn = ['A']; - protected function setTableStartColumn($column) + protected function setTableStartColumn(string $column): string { if ($this->tableLevel == 0) { $column = 'A'; @@ -260,19 +264,26 @@ protected function setTableStartColumn($column) return $this->nestedColumn[$this->tableLevel]; } - protected function getTableStartColumn() + protected function getTableStartColumn(): string { return $this->nestedColumn[$this->tableLevel]; } - protected function releaseTableStartColumn() + protected function releaseTableStartColumn(): string { --$this->tableLevel; return array_pop($this->nestedColumn); } - protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent) + /** + * Flush cell. + * + * @param string $column + * @param int|string $row + * @param mixed $cellContent + */ + protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent): void { if (is_string($cellContent)) { // Simple String content @@ -291,313 +302,371 @@ protected function flushCell(Worksheet $sheet, $column, $row, &$cellContent) $cellContent = (string) ''; } - /** - * @param DOMNode $element - * @param Worksheet $sheet - * @param int $row - * @param string $column - * @param string $cellContent - */ - protected function processDomElement(DOMNode $element, Worksheet $sheet, &$row, &$column, &$cellContent) + private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void { - foreach ($element->childNodes as $child) { - if ($child instanceof DOMText) { - $domText = preg_replace('/\s+/u', ' ', trim($child->nodeValue)); - if (is_string($cellContent)) { - // simply append the text if the cell content is a plain text string - $cellContent .= $domText; - } - // but if we have a rich text run instead, we need to append it correctly - // TODO - } elseif ($child instanceof DOMElement) { - $attributeArray = []; - foreach ($child->attributes as $attribute) { - $attributeArray[$attribute->name] = $attribute->value; - } + $attributeArray = []; + foreach (($child->attributes ?? []) as $attribute) { + $attributeArray[$attribute->name] = $attribute->value; + } - switch ($child->nodeName) { - case 'meta': - foreach ($attributeArray as $attributeName => $attributeValue) { - // Extract character set, so we can convert to UTF-8 if required - if ($attributeName === 'charset') { - $this->setInputEncoding($attributeValue); - } - } - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + if ($child->nodeName === 'body') { + $row = 1; + $column = 'A'; + $cellContent = ''; + $this->tableLevel = 0; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } else { + $this->processDomElementTitle($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - break; - case 'title': - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - $sheet->setTitle($cellContent, true, false); - $cellContent = ''; + private function processDomElementTitle(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'title') { + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $sheet->setTitle($cellContent, true, true); + $cellContent = ''; + } else { + $this->processDomElementSpanEtc($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - break; - case 'span': - case 'div': - case 'font': - case 'i': - case 'em': - case 'strong': - case 'b': - if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { - $sheet->getComment($column . $row) - ->getText() - ->createTextRun($child->textContent); + private const SPAN_ETC = ['span', 'div', 'font', 'i', 'em', 'strong', 'b']; - break; - } + private function processDomElementSpanEtc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if (in_array((string) $child->nodeName, self::SPAN_ETC, true)) { + if (isset($attributeArray['class']) && $attributeArray['class'] === 'comment') { + $sheet->getComment($column . $row) + ->getText() + ->createTextRun($child->textContent); + } else { + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } - if ($cellContent > '') { - $cellContent .= ' '; - } - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - if ($cellContent > '') { - $cellContent .= ' '; - } + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } + } else { + $this->processDomElementHr($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - if (isset($this->formats[$child->nodeName])) { - $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); - } + private function processDomElementHr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'hr') { + $this->flushCell($sheet, $column, $row, $cellContent); + ++$row; + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } + ++$row; + } + // fall through to br + $this->processDomElementBr($sheet, $row, $column, $cellContent, $child, $attributeArray); + } - break; - case 'hr': - $this->flushCell($sheet, $column, $row, $cellContent); - ++$row; + private function processDomElementBr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'br' || $child->nodeName === 'hr') { + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n and set the cell to wrap + $cellContent .= "\n"; + $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); + } else { + // Otherwise flush our existing content and move the row cursor on + $this->flushCell($sheet, $column, $row, $cellContent); + ++$row; + } + } else { + $this->processDomElementA($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } + + private function processDomElementA(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'a') { + foreach ($attributeArray as $attributeName => $attributeValue) { + switch ($attributeName) { + case 'href': + $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); if (isset($this->formats[$child->nodeName])) { $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); - } else { - $cellContent = '----------'; - $this->flushCell($sheet, $column, $row, $cellContent); - } - ++$row; - // Add a break after a horizontal rule, simply by allowing the code to dropthru - // no break - case 'br': - if ($this->tableLevel > 0) { - // If we're inside a table, replace with a \n and set the cell to wrap - $cellContent .= "\n"; - $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); - } else { - // Otherwise flush our existing content and move the row cursor on - $this->flushCell($sheet, $column, $row, $cellContent); - ++$row; } break; - case 'a': - foreach ($attributeArray as $attributeName => $attributeValue) { - switch ($attributeName) { - case 'href': - $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); - if (isset($this->formats[$child->nodeName])) { - $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); - } - - break; - case 'class': - if ($attributeValue === 'comment-indicator') { - break; // Ignore - it's just a red square. - } - } + case 'class': + if ($attributeValue === 'comment-indicator') { + break; // Ignore - it's just a red square. } - $cellContent .= ' '; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } + } + // no idea why this should be needed + //$cellContent .= ' '; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } else { + $this->processDomElementH1Etc($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - break; - case 'h1': - case 'h2': - case 'h3': - case 'h4': - case 'h5': - case 'h6': - case 'ol': - case 'ul': - case 'p': - if ($this->tableLevel > 0) { - // If we're inside a table, replace with a \n - $cellContent .= "\n"; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - } else { - if ($cellContent > '') { - $this->flushCell($sheet, $column, $row, $cellContent); - ++$row; - } - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - $this->flushCell($sheet, $column, $row, $cellContent); - - if (isset($this->formats[$child->nodeName])) { - $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); - } - - ++$row; - $column = 'A'; - } + private const H1_ETC = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p']; - break; - case 'li': - if ($this->tableLevel > 0) { - // If we're inside a table, replace with a \n - $cellContent .= "\n"; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - } else { - if ($cellContent > '') { - $this->flushCell($sheet, $column, $row, $cellContent); - } - ++$row; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - $this->flushCell($sheet, $column, $row, $cellContent); - $column = 'A'; - } + private function processDomElementH1Etc(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if (in_array((string) $child->nodeName, self::H1_ETC, true)) { + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= $cellContent ? "\n" : ''; + $sheet->getStyle($column . $row)->getAlignment()->setWrapText(true); + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } else { + if ($cellContent > '') { + $this->flushCell($sheet, $column, $row, $cellContent); + ++$row; + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); - break; - case 'img': - $this->insertImage($sheet, $column, $row, $attributeArray); + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } - break; - case 'table': - $this->flushCell($sheet, $column, $row, $cellContent); - $column = $this->setTableStartColumn($column); - if ($this->tableLevel > 1) { - --$row; - } - $this->processDomElement($child, $sheet, $row, $column, $cellContent); - $column = $this->releaseTableStartColumn(); - if ($this->tableLevel > 1) { - ++$column; - } else { - ++$row; - } + ++$row; + $column = 'A'; + } + } else { + $this->processDomElementLi($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - break; - case 'thead': - case 'tbody': - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + private function processDomElementLi(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'li') { + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= $cellContent ? "\n" : ''; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } else { + if ($cellContent > '') { + $this->flushCell($sheet, $column, $row, $cellContent); + } + ++$row; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); + $column = 'A'; + } + } else { + $this->processDomElementImg($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - break; - case 'tr': - $column = $this->getTableStartColumn(); - $cellContent = ''; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + private function processDomElementImg(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'img') { + $this->insertImage($sheet, $column, $row, $attributeArray); + } else { + $this->processDomElementTable($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - if (isset($attributeArray['height'])) { - $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); - } + private function processDomElementTable(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'table') { + $this->flushCell($sheet, $column, $row, $cellContent); + $column = $this->setTableStartColumn($column); + if ($this->tableLevel > 1 && $row > 1) { + --$row; + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $column = $this->releaseTableStartColumn(); + if ($this->tableLevel > 1) { + ++$column; + } else { + ++$row; + } + } else { + $this->processDomElementTr($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - ++$row; + private function processDomElementTr(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName === 'tr') { + $column = $this->getTableStartColumn(); + $cellContent = ''; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); - break; - case 'th': - case 'td': - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + if (isset($attributeArray['height'])) { + $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); + } - while (isset($this->rowspan[$column . $row])) { - ++$column; - } + ++$row; + } else { + $this->processDomElementThTdOther($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - // apply inline style - $this->applyInlineStyle($sheet, $row, $column, $attributeArray); - - $this->flushCell($sheet, $column, $row, $cellContent); - - if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { - //create merging rowspan and colspan - $columnTo = $column; - for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { - ++$columnTo; - } - $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); - foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { - $this->rowspan[$value] = true; - } - $sheet->mergeCells($range); - $column = $columnTo; - } elseif (isset($attributeArray['rowspan'])) { - //create merging rowspan - $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); - foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { - $this->rowspan[$value] = true; - } - $sheet->mergeCells($range); - } elseif (isset($attributeArray['colspan'])) { - //create merging colspan - $columnTo = $column; - for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { - ++$columnTo; - } - $sheet->mergeCells($column . $row . ':' . $columnTo . $row); - $column = $columnTo; - } elseif (isset($attributeArray['bgcolor'])) { - $sheet->getStyle($column . $row)->applyFromArray( - [ - 'fill' => [ - 'fillType' => Fill::FILL_SOLID, - 'color' => ['rgb' => $attributeArray['bgcolor']], - ], - ] - ); - } + private function processDomElementThTdOther(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + if ($child->nodeName !== 'td' && $child->nodeName !== 'th') { + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } else { + $this->processDomElementThTd($sheet, $row, $column, $cellContent, $child, $attributeArray); + } + } - if (isset($attributeArray['width'])) { - $sheet->getColumnDimension($column)->setWidth($attributeArray['width']); - } + private function processDomElementBgcolor(Worksheet $sheet, int $row, string $column, array $attributeArray): void + { + if (isset($attributeArray['bgcolor'])) { + $sheet->getStyle("$column$row")->applyFromArray( + [ + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, + 'color' => ['rgb' => $this->getStyleColor($attributeArray['bgcolor'])], + ], + ] + ); + } + } - if (isset($attributeArray['height'])) { - $sheet->getRowDimension($row)->setRowHeight($attributeArray['height']); - } + private function processDomElementWidth(Worksheet $sheet, string $column, array $attributeArray): void + { + if (isset($attributeArray['width'])) { + $sheet->getColumnDimension($column)->setWidth((new CssDimension($attributeArray['width']))->width()); + } + } - if (isset($attributeArray['align'])) { - $sheet->getStyle($column . $row)->getAlignment()->setHorizontal($attributeArray['align']); - } + private function processDomElementHeight(Worksheet $sheet, int $row, array $attributeArray): void + { + if (isset($attributeArray['height'])) { + $sheet->getRowDimension($row)->setRowHeight((new CssDimension($attributeArray['height']))->height()); + } + } - if (isset($attributeArray['valign'])) { - $sheet->getStyle($column . $row)->getAlignment()->setVertical($attributeArray['valign']); - } + private function processDomElementAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void + { + if (isset($attributeArray['align'])) { + $sheet->getStyle($column . $row)->getAlignment()->setHorizontal($attributeArray['align']); + } + } - if (isset($attributeArray['data-format'])) { - $sheet->getStyle($column . $row)->getNumberFormat()->setFormatCode($attributeArray['data-format']); - } + private function processDomElementVAlign(Worksheet $sheet, int $row, string $column, array $attributeArray): void + { + if (isset($attributeArray['valign'])) { + $sheet->getStyle($column . $row)->getAlignment()->setVertical($attributeArray['valign']); + } + } + + private function processDomElementDataFormat(Worksheet $sheet, int $row, string $column, array $attributeArray): void + { + if (isset($attributeArray['data-format'])) { + $sheet->getStyle($column . $row)->getNumberFormat()->setFormatCode($attributeArray['data-format']); + } + } - ++$column; + private function processDomElementThTd(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child, array &$attributeArray): void + { + while (isset($this->rowspan[$column . $row])) { + ++$column; + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); - break; - case 'body': - $row = 1; - $column = 'A'; - $cellContent = ''; - $this->tableLevel = 0; - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + // apply inline style + $this->applyInlineStyle($sheet, $row, $column, $attributeArray); - break; - default: - $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $this->flushCell($sheet, $column, $row, $cellContent); + + $this->processDomElementBgcolor($sheet, $row, $column, $attributeArray); + $this->processDomElementWidth($sheet, $column, $attributeArray); + $this->processDomElementHeight($sheet, $row, $attributeArray); + $this->processDomElementAlign($sheet, $row, $column, $attributeArray); + $this->processDomElementVAlign($sheet, $row, $column, $attributeArray); + $this->processDomElementDataFormat($sheet, $row, $column, $attributeArray); + + if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { + //create merging rowspan and colspan + $columnTo = $column; + for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { + ++$columnTo; + } + $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); + foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { + $this->rowspan[$value] = true; + } + $sheet->mergeCells($range); + $column = $columnTo; + } elseif (isset($attributeArray['rowspan'])) { + //create merging rowspan + $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); + foreach (Coordinate::extractAllCellReferencesInRange($range) as $value) { + $this->rowspan[$value] = true; + } + $sheet->mergeCells($range); + } elseif (isset($attributeArray['colspan'])) { + //create merging colspan + $columnTo = $column; + for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { + ++$columnTo; + } + $sheet->mergeCells($column . $row . ':' . $columnTo . $row); + $column = $columnTo; + } + + ++$column; + } + + protected function processDomElement(DOMNode $element, Worksheet $sheet, int &$row, string &$column, string &$cellContent): void + { + foreach ($element->childNodes as $child) { + if ($child instanceof DOMText) { + $domText = preg_replace('/\s+/u', ' ', trim($child->nodeValue ?: '')); + if (is_string($cellContent)) { + // simply append the text if the cell content is a plain text string + $cellContent .= $domText; } + // but if we have a rich text run instead, we need to append it correctly + // TODO + } elseif ($child instanceof DOMElement) { + $this->processDomElementBody($sheet, $row, $column, $cellContent, $child); } } } /** - * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. + * Make sure mb_convert_encoding returns string. * - * @param string $pFilename - * @param Spreadsheet $spreadsheet + * @param mixed $result + */ + private static function ensureString($result): string + { + return is_string($result) ? $result : ''; + } + + /** + * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * - * @throws Exception + * @param string $filename * * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { // Validate - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid HTML file.'); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid HTML file.'); } // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object - $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scanFile($pFilename), 'HTML-ENTITIES', 'UTF-8')); + try { + $convert = mb_convert_encoding($this->securityScanner->scanFile($filename), 'HTML-ENTITIES', 'UTF-8'); + $loaded = $dom->loadHTML(self::ensureString($convert)); + } catch (Throwable $e) { + $loaded = false; + } if ($loaded === false) { - throw new Exception('Failed to load ' . $pFilename . ' as a DOM Document'); + throw new Exception('Failed to load ' . $filename . ' as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet); @@ -607,18 +676,20 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) * Spreadsheet from content. * * @param string $content - * @param null|Spreadsheet $spreadsheet - * - * @return Spreadsheet */ public function loadFromString($content, ?Spreadsheet $spreadsheet = null): Spreadsheet { // Create a new DOM object $dom = new DOMDocument(); // Reload the HTML file into the DOM object - $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8')); + try { + $convert = mb_convert_encoding($this->securityScanner->scan($content), 'HTML-ENTITIES', 'UTF-8'); + $loaded = $dom->loadHTML(self::ensureString($convert)); + } catch (Throwable $e) { + $loaded = false; + } if ($loaded === false) { - throw new Exception('Failed to load content as a DOM Document'); + throw new Exception('Failed to load content as a DOM Document', 0, $e ?? null); } return $this->loadDocument($dom, $spreadsheet ?? new Spreadsheet()); @@ -626,13 +697,6 @@ public function loadFromString($content, ?Spreadsheet $spreadsheet = null): Spre /** * Loads PhpSpreadsheet from DOMDocument into PhpSpreadsheet instance. - * - * @param DOMDocument $document - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Exception - * - * @return Spreadsheet */ private function loadDocument(DOMDocument $document, Spreadsheet $spreadsheet): Spreadsheet { @@ -667,13 +731,13 @@ public function getSheetIndex() /** * Set sheet index. * - * @param int $pValue Sheet index + * @param int $sheetIndex Sheet index * * @return $this */ - public function setSheetIndex($pValue) + public function setSheetIndex($sheetIndex) { - $this->sheetIndex = $pValue; + $this->sheetIndex = $sheetIndex; return $this; } @@ -688,18 +752,36 @@ public function setSheetIndex($pValue) * TODO : * - Implement to other propertie, such as border * - * @param Worksheet $sheet * @param int $row * @param string $column * @param array $attributeArray */ - private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) + private function applyInlineStyle(Worksheet &$sheet, $row, $column, $attributeArray): void { if (!isset($attributeArray['style'])) { return; } - $cellStyle = $sheet->getStyle($column . $row); + if (isset($attributeArray['rowspan'], $attributeArray['colspan'])) { + $columnTo = $column; + for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { + ++$columnTo; + } + $range = $column . $row . ':' . $columnTo . ($row + (int) $attributeArray['rowspan'] - 1); + $cellStyle = $sheet->getStyle($range); + } elseif (isset($attributeArray['rowspan'])) { + $range = $column . $row . ':' . $column . ($row + (int) $attributeArray['rowspan'] - 1); + $cellStyle = $sheet->getStyle($range); + } elseif (isset($attributeArray['colspan'])) { + $columnTo = $column; + for ($i = 0; $i < (int) $attributeArray['colspan'] - 1; ++$i) { + ++$columnTo; + } + $range = $column . $row . ':' . $columnTo . $row; + $cellStyle = $sheet->getStyle($range); + } else { + $cellStyle = $sheet->getStyle($column . $row); + } // add color styles (background & text) from dom element,currently support : td & th, using ONLY inline css style with RGB color $styles = explode(';', $attributeArray['style']); @@ -707,6 +789,7 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) $value = explode(':', $st); $styleName = isset($value[0]) ? trim($value[0]) : null; $styleValue = isset($value[1]) ? trim($value[1]) : null; + $styleValueString = (string) $styleValue; if (!$styleName) { continue; @@ -715,7 +798,7 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) switch ($styleName) { case 'background': case 'background-color': - $styleColor = $this->getStyleColor($styleValue); + $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; @@ -725,7 +808,7 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) break; case 'color': - $styleColor = $this->getStyleColor($styleValue); + $styleColor = $this->getStyleColor($styleValueString); if (!$styleColor) { continue 2; @@ -736,27 +819,27 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) break; case 'border': - $this->setBorderStyle($cellStyle, $styleValue, 'allBorders'); + $this->setBorderStyle($cellStyle, $styleValueString, 'allBorders'); break; case 'border-top': - $this->setBorderStyle($cellStyle, $styleValue, 'top'); + $this->setBorderStyle($cellStyle, $styleValueString, 'top'); break; case 'border-bottom': - $this->setBorderStyle($cellStyle, $styleValue, 'bottom'); + $this->setBorderStyle($cellStyle, $styleValueString, 'bottom'); break; case 'border-left': - $this->setBorderStyle($cellStyle, $styleValue, 'left'); + $this->setBorderStyle($cellStyle, $styleValueString, 'left'); break; case 'border-right': - $this->setBorderStyle($cellStyle, $styleValue, 'right'); + $this->setBorderStyle($cellStyle, $styleValueString, 'right'); break; @@ -782,7 +865,7 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) break; case 'font-family': - $cellStyle->getFont()->setName(str_replace('\'', '', $styleValue)); + $cellStyle->getFont()->setName(str_replace('\'', '', $styleValueString)); break; @@ -801,25 +884,25 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) break; case 'text-align': - $cellStyle->getAlignment()->setHorizontal($styleValue); + $cellStyle->getAlignment()->setHorizontal($styleValueString); break; case 'vertical-align': - $cellStyle->getAlignment()->setVertical($styleValue); + $cellStyle->getAlignment()->setVertical($styleValueString); break; case 'width': $sheet->getColumnDimension($column)->setWidth( - str_replace('px', '', $styleValue) + (new CssDimension($styleValue ?? ''))->width() ); break; case 'height': $sheet->getRowDimension($row)->setRowHeight( - str_replace('px', '', $styleValue) + (new CssDimension($styleValue ?? ''))->height() ); break; @@ -833,7 +916,7 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) case 'text-indent': $cellStyle->getAlignment()->setIndent( - (int) str_replace(['px'], '', $styleValue) + (int) str_replace(['px'], '', $styleValueString) ); break; @@ -844,28 +927,25 @@ private function applyInlineStyle(&$sheet, $row, $column, $attributeArray) /** * Check if has #, so we can get clean hex. * - * @param $value + * @param mixed $value * * @return null|string */ public function getStyleColor($value) { - if (strpos($value, '#') === 0) { + $value = (string) $value; + if (strpos($value ?? '', '#') === 0) { return substr($value, 1); } - return null; + return \PhpOffice\PhpSpreadsheet\Helper\Html::colourNameLookup($value); } /** - * @param Worksheet $sheet * @param string $column * @param int $row - * @param array $attributes - * - * @throws \PhpOffice\PhpSpreadsheet\Exception */ - private function insertImage(Worksheet $sheet, $column, $row, array $attributes) + private function insertImage(Worksheet $sheet, $column, $row, array $attributes): void { if (!isset($attributes['src'])) { return; @@ -874,7 +954,7 @@ private function insertImage(Worksheet $sheet, $column, $row, array $attributes) $src = urldecode($attributes['src']); $width = isset($attributes['width']) ? (float) $attributes['width'] : null; $height = isset($attributes['height']) ? (float) $attributes['height'] : null; - $name = isset($attributes['alt']) ? (float) $attributes['alt'] : null; + $name = $attributes['alt'] ?? null; $drawing = new Drawing(); $drawing->setPath($src); @@ -905,6 +985,28 @@ private function insertImage(Worksheet $sheet, $column, $row, array $attributes) ); } + private const BORDER_MAPPINGS = [ + 'dash-dot' => Border::BORDER_DASHDOT, + 'dash-dot-dot' => Border::BORDER_DASHDOTDOT, + 'dashed' => Border::BORDER_DASHED, + 'dotted' => Border::BORDER_DOTTED, + 'double' => Border::BORDER_DOUBLE, + 'hair' => Border::BORDER_HAIR, + 'medium' => Border::BORDER_MEDIUM, + 'medium-dashed' => Border::BORDER_MEDIUMDASHED, + 'medium-dash-dot' => Border::BORDER_MEDIUMDASHDOT, + 'medium-dash-dot-dot' => Border::BORDER_MEDIUMDASHDOTDOT, + 'none' => Border::BORDER_NONE, + 'slant-dash-dot' => Border::BORDER_SLANTDASHDOT, + 'solid' => Border::BORDER_THIN, + 'thick' => Border::BORDER_THICK, + ]; + + public static function getBorderMappings(): array + { + return self::BORDER_MAPPINGS; + } + /** * Map html border style to PhpSpreadsheet border style. * @@ -914,48 +1016,29 @@ private function insertImage(Worksheet $sheet, $column, $row, array $attributes) */ public function getBorderStyle($style) { - switch ($style) { - case 'solid': - return Border::BORDER_THIN; - case 'dashed': - return Border::BORDER_DASHED; - case 'dotted': - return Border::BORDER_DOTTED; - case 'medium': - return Border::BORDER_MEDIUM; - case 'thick': - return Border::BORDER_THICK; - case 'none': - return Border::BORDER_NONE; - case 'dash-dot': - return Border::BORDER_DASHDOT; - case 'dash-dot-dot': - return Border::BORDER_DASHDOTDOT; - case 'double': - return Border::BORDER_DOUBLE; - case 'hair': - return Border::BORDER_HAIR; - case 'medium-dash-dot': - return Border::BORDER_MEDIUMDASHDOT; - case 'medium-dash-dot-dot': - return Border::BORDER_MEDIUMDASHDOTDOT; - case 'medium-dashed': - return Border::BORDER_MEDIUMDASHED; - case 'slant-dash-dot': - return Border::BORDER_SLANTDASHDOT; - } - - return null; + return self::BORDER_MAPPINGS[$style] ?? null; } /** - * @param Style $cellStyle * @param string $styleValue * @param string $type */ - private function setBorderStyle(Style $cellStyle, $styleValue, $type) + private function setBorderStyle(Style $cellStyle, $styleValue, $type): void { - [, $borderStyle, $color] = explode(' ', $styleValue); + if (trim($styleValue) === Border::BORDER_NONE) { + $borderStyle = Border::BORDER_NONE; + $color = null; + } else { + $borderArray = explode(' ', $styleValue); + $borderCount = count($borderArray); + if ($borderCount >= 3) { + $borderStyle = $borderArray[1]; + $color = $borderArray[2]; + } else { + $borderStyle = $borderArray[0]; + $color = $borderArray[1] ?? null; + } + } $cellStyle->applyFromArray([ 'borders' => [ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php index ccfe05ad..9f68a7f3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReadFilter.php @@ -7,11 +7,11 @@ interface IReadFilter /** * Should this cell be read? * - * @param string $column Column address (as a string value like "A", or "IV") + * @param string $columnAddress Column address (as a string value like "A", or "IV") * @param int $row Row number * @param string $worksheetName Optional worksheet name * * @return bool */ - public function readCell($column, $row, $worksheetName = ''); + public function readCell($columnAddress, $row, $worksheetName = ''); } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php index 70a7a200..d73662b4 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/IReader.php @@ -4,6 +4,8 @@ interface IReader { + public const LOAD_WITH_CHARTS = 1; + /** * IReader constructor. */ @@ -11,12 +13,8 @@ public function __construct(); /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @return bool */ - public function canRead($pFilename); + public function canRead(string $filename): bool; /** * Read data only? @@ -32,11 +30,11 @@ public function getReadDataOnly(); * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information. * Set to false (the default) to advise the Reader to read both data and formatting for cells. * - * @param bool $pValue + * @param bool $readDataOnly * * @return IReader */ - public function setReadDataOnly($pValue); + public function setReadDataOnly($readDataOnly); /** * Read empty cells? @@ -52,11 +50,11 @@ public function getReadEmptyCells(); * Set to true (the default) to advise the Reader read data values for all cells, irrespective of value. * Set to false to advise the Reader to ignore cells containing a null value or an empty string. * - * @param bool $pValue + * @param bool $readEmptyCells * * @return IReader */ - public function setReadEmptyCells($pValue); + public function setReadEmptyCells($readEmptyCells); /** * Read charts in workbook? @@ -74,11 +72,11 @@ public function getIncludeCharts(); * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. * Set to false (the default) to discard charts. * - * @param bool $pValue + * @param bool $includeCharts * * @return IReader */ - public function setIncludeCharts($pValue); + public function setIncludeCharts($includeCharts); /** * Get which sheets to load @@ -118,20 +116,14 @@ public function getReadFilter(); /** * Set read filter. * - * @param IReadFilter $pValue - * * @return IReader */ - public function setReadFilter(IReadFilter $pValue); + public function setReadFilter(IReadFilter $readFilter); /** * Loads PhpSpreadsheet from file. * - * @param string $pFilename - * - * @throws Exception - * * @return \PhpOffice\PhpSpreadsheet\Spreadsheet */ - public function load($pFilename); + public function load(string $filename, int $flags = 0); } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php index 5fff07aa..fcafc047 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods.php @@ -2,11 +2,16 @@ namespace PhpOffice\PhpSpreadsheet\Reader; -use DateTime; -use DateTimeZone; -use PhpOffice\PhpSpreadsheet\Calculation\Calculation; +use DOMAttr; +use DOMDocument; +use DOMElement; +use DOMNode; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; +use PhpOffice\PhpSpreadsheet\Reader\Ods\AutoFilter; +use PhpOffice\PhpSpreadsheet\Reader\Ods\DefinedNames; +use PhpOffice\PhpSpreadsheet\Reader\Ods\FormulaTranslator; +use PhpOffice\PhpSpreadsheet\Reader\Ods\PageSettings; use PhpOffice\PhpSpreadsheet\Reader\Ods\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\RichText\RichText; @@ -15,11 +20,14 @@ use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; +use Throwable; use XMLReader; use ZipArchive; class Ods extends BaseReader { + const INITIAL_FILE = 'content.xml'; + /** * Create a new Ods Reader instance. */ @@ -31,78 +39,63 @@ public function __construct() /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @throws Exception - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { - File::assertFile($pFilename); - $mimeType = 'UNKNOWN'; // Load file - $zip = new ZipArchive(); - if ($zip->open($pFilename) === true) { - // check if it is an OOXML archive - $stat = $zip->statName('mimetype'); - if ($stat && ($stat['size'] <= 255)) { - $mimeType = $zip->getFromName($stat['name']); - } elseif ($zip->statName('META-INF/manifest.xml')) { - $xml = simplexml_load_string( - $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $namespacesContent = $xml->getNamespaces(true); - if (isset($namespacesContent['manifest'])) { - $manifest = $xml->children($namespacesContent['manifest']); - foreach ($manifest as $manifestDataSet) { - $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); - if ($manifestAttributes->{'full-path'} == '/') { - $mimeType = (string) $manifestAttributes->{'media-type'}; - - break; + if (File::testFileNoThrow($filename, '')) { + $zip = new ZipArchive(); + if ($zip->open($filename) === true) { + // check if it is an OOXML archive + $stat = $zip->statName('mimetype'); + if ($stat && ($stat['size'] <= 255)) { + $mimeType = $zip->getFromName($stat['name']); + } elseif ($zip->statName('META-INF/manifest.xml')) { + $xml = simplexml_load_string( + $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')), + 'SimpleXMLElement', + Settings::getLibXmlLoaderOptions() + ); + $namespacesContent = $xml->getNamespaces(true); + if (isset($namespacesContent['manifest'])) { + $manifest = $xml->children($namespacesContent['manifest']); + foreach ($manifest as $manifestDataSet) { + $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); + if ($manifestAttributes && $manifestAttributes->{'full-path'} == '/') { + $mimeType = (string) $manifestAttributes->{'media-type'}; + + break; + } } } } - } - $zip->close(); - - return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; + $zip->close(); + } } - return false; + return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet'; } /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return string[] */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); - - $zip = new ZipArchive(); - if (!$zip->open($pFilename)) { - throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.'); - } + File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; $xml = new XMLReader(); $xml->xml( - $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'), + $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); @@ -112,7 +105,7 @@ public function listWorksheetNames($pFilename) $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node - while ($xml->name !== 'office:body') { + while (self::getXmlName($xml) !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { @@ -121,12 +114,13 @@ public function listWorksheetNames($pFilename) } // Now read each node until we find our first table:table node while ($xml->read()) { - if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + $xmlName = self::getXmlName($xml); + if ($xmlName == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { // Loop through each table:table node reading the table:name attribute for each worksheet name do { $worksheetNames[] = $xml->getAttribute('table:name'); $xml->next(); - } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); + } while (self::getXmlName($xml) == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); } } } @@ -137,26 +131,19 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; - $zip = new ZipArchive(); - if (!$zip->open($pFilename)) { - throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.'); - } - $xml = new XMLReader(); $xml->xml( - $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'), + $this->securityScanner->scanFile('zip://' . realpath($filename) . '#' . self::INITIAL_FILE), null, Settings::getLibXmlLoaderOptions() ); @@ -166,7 +153,7 @@ public function listWorksheetInfo($pFilename) $xml->read(); while ($xml->read()) { // Quickly jump through to the office:body node - while ($xml->name !== 'office:body') { + while (self::getXmlName($xml) !== 'office:body') { if ($xml->isEmptyElement) { $xml->read(); } else { @@ -175,7 +162,7 @@ public function listWorksheetInfo($pFilename) } // Now read each node until we find our first table:table node while ($xml->read()) { - if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + if (self::getXmlName($xml) == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { $worksheetNames[] = $xml->getAttribute('table:name'); $tmpInfo = [ @@ -190,7 +177,7 @@ public function listWorksheetInfo($pFilename) $currCells = 0; do { $xml->read(); - if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { + if (self::getXmlName($xml) == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { $rowspan = $xml->getAttribute('table:number-rows-repeated'); $rowspan = empty($rowspan) ? 1 : $rowspan; $tmpInfo['totalRows'] += $rowspan; @@ -199,23 +186,23 @@ public function listWorksheetInfo($pFilename) // Step into the row $xml->read(); do { - if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + $doread = true; + if (self::getXmlName($xml) == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { if (!$xml->isEmptyElement) { ++$currCells; $xml->next(); - } else { - $xml->read(); + $doread = false; } - } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + } elseif (self::getXmlName($xml) == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { $mergeSize = $xml->getAttribute('table:number-columns-repeated'); $currCells += (int) $mergeSize; - $xml->read(); - } else { + } + if ($doread) { $xml->read(); } - } while ($xml->name != 'table:table-row'); + } while (self::getXmlName($xml) != 'table:table-row'); } - } while ($xml->name != 'table:table'); + } while (self::getXmlName($xml) != 'table:table'); $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; @@ -229,48 +216,44 @@ public function listWorksheetInfo($pFilename) } /** - * Loads PhpSpreadsheet from file. - * - * @param string $pFilename + * Counteract Phpstan caching. * - * @throws Exception - * - * @return Spreadsheet + * @phpstan-impure + */ + private static function getXmlName(XMLReader $xml): string + { + return $xml->name; + } + + /** + * Loads PhpSpreadsheet from file. */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * - * @param string $pFilename - * @param Spreadsheet $spreadsheet - * - * @throws Exception + * @param string $filename * * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { - File::assertFile($pFilename); - - $timezoneObj = new DateTimeZone('Europe/London'); - $GMT = new \DateTimeZone('UTC'); + File::assertFile($filename, self::INITIAL_FILE); $zip = new ZipArchive(); - if (!$zip->open($pFilename)) { - throw new Exception("Could not open {$pFilename} for reading! Error opening file."); - } + $zip->open($filename); // Meta - $xml = simplexml_load_string( + $xml = @simplexml_load_string( $this->securityScanner->scan($zip->getFromName('meta.xml')), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() @@ -283,11 +266,21 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) (new DocumentProperties($spreadsheet))->load($xml, $namespacesMeta); - // Content + // Styles - $dom = new \DOMDocument('1.01', 'UTF-8'); + $dom = new DOMDocument('1.01', 'UTF-8'); $dom->loadXML( - $this->securityScanner->scan($zip->getFromName('content.xml')), + $this->securityScanner->scan($zip->getFromName('styles.xml')), + Settings::getLibXmlLoaderOptions() + ); + + $pageSettings = new PageSettings($dom); + + // Main Content + + $dom = new DOMDocument('1.01', 'UTF-8'); + $dom->loadXML( + $this->securityScanner->scan($zip->getFromName(self::INITIAL_FILE)), Settings::getLibXmlLoaderOptions() ); @@ -296,26 +289,36 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $textNs = $dom->lookupNamespaceUri('text'); $xlinkNs = $dom->lookupNamespaceUri('xlink'); + $pageSettings->readStyleCrossReferences($dom); + + $autoFilterReader = new AutoFilter($spreadsheet, $tableNs); + $definedNameReader = new DefinedNames($spreadsheet, $tableNs); + + // Content $spreadsheets = $dom->getElementsByTagNameNS($officeNs, 'body') ->item(0) ->getElementsByTagNameNS($officeNs, 'spreadsheet'); foreach ($spreadsheets as $workbookData) { - /** @var \DOMElement $workbookData */ + /** @var DOMElement $workbookData */ $tables = $workbookData->getElementsByTagNameNS($tableNs, 'table'); $worksheetID = 0; foreach ($tables as $worksheetDataSet) { - /** @var \DOMElement $worksheetDataSet */ + /** @var DOMElement $worksheetDataSet */ $worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name'); // Check loadSheetsOnly - if (isset($this->loadSheetsOnly) + if ( + isset($this->loadSheetsOnly) && $worksheetName - && !in_array($worksheetName, $this->loadSheetsOnly)) { + && !in_array($worksheetName, $this->loadSheetsOnly) + ) { continue; } + $worksheetStyleName = $worksheetDataSet->getAttributeNS($tableNs, 'style-name'); + // Create sheet if ($worksheetID > 0) { $spreadsheet->createSheet(); // First sheet is added by default @@ -326,13 +329,13 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in // formula cells... during the load, all formulae should be correct, and we're simply // bringing the worksheet name in line with the formula, not the reverse - $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); + $spreadsheet->getActiveSheet()->setTitle((string) $worksheetName, false, false); } // Go through every child of table element $rowID = 1; foreach ($worksheetDataSet->childNodes as $childNode) { - /** @var \DOMElement $childNode */ + /** @var DOMElement $childNode */ // Filter elements which are not under the "table" ns if ($childNode->namespaceURI != $tableNs) { @@ -360,15 +363,14 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) break; case 'table-row': if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) { - $rowRepeats = $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); + $rowRepeats = (int) $childNode->getAttributeNS($tableNs, 'number-rows-repeated'); } else { $rowRepeats = 1; } $columnID = 'A'; - foreach ($childNode->childNodes as $key => $cellData) { - // @var \DOMElement $cellData - + /** @var DOMElement $cellData */ + foreach ($childNode->childNodes as $cellData) { if ($this->getReadFilter() !== null) { if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { ++$columnID; @@ -405,11 +407,11 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) // Content - /** @var \DOMElement[] $paragraphs */ + /** @var DOMElement[] $paragraphs */ $paragraphs = []; foreach ($cellData->childNodes as $item) { - /** @var \DOMElement $item */ + /** @var DOMElement $item */ // Filter text:p elements if ($item->nodeName == 'text:p') { @@ -455,9 +457,10 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $type = DataType::TYPE_NUMERIC; $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value'); - if (floor($dataValue) == $dataValue) { - $dataValue = (int) $dataValue; - } + // percentage should always be float + //if (floor($dataValue) == $dataValue) { + // $dataValue = (int) $dataValue; + //} $formatting = NumberFormat::FORMAT_PERCENTAGE_00; break; @@ -478,8 +481,6 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) if (floor($dataValue) == $dataValue) { if ($dataValue == (int) $dataValue) { $dataValue = (int) $dataValue; - } else { - $dataValue = (float) $dataValue; } } @@ -487,22 +488,7 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) case 'date': $type = DataType::TYPE_NUMERIC; $value = $cellData->getAttributeNS($officeNs, 'date-value'); - - $dateObj = new DateTime($value, $GMT); - $dateObj->setTimeZone($timezoneObj); - [$year, $month, $day, $hour, $minute, $second] = explode( - ' ', - $dateObj->format('Y m d H i s') - ); - - $dataValue = Date::formattedPHPToExcel( - (int) $year, - (int) $month, - (int) $day, - (int) $hour, - (int) $minute, - (int) $second - ); + $dataValue = Date::convertIsoDate($value); if ($dataValue != floor($dataValue)) { $formatting = NumberFormat::FORMAT_DATE_XLSX15 @@ -520,7 +506,7 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $dataValue = Date::PHPToExcel( strtotime( - '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS')) + '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS') ?? []) ) ); $formatting = NumberFormat::FORMAT_DATE_TIME4; @@ -537,30 +523,7 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1); - $temp = explode('"', $cellDataFormula); - $tKey = false; - foreach ($temp as &$value) { - // Only replace in alternate array entries (i.e. non-quoted blocks) - if ($tKey = !$tKey) { - // Cell range reference in another sheet - $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/U', '$1!$2:$3', $value); - - // Cell reference in another sheet - $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/U', '$1!$2', $value); - - // Cell range reference - $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/U', '$1:$2', $value); - - // Simple cell reference - $value = preg_replace('/\[\.([^\.]+)\]/U', '$1', $value); - - $value = Calculation::translateSeparator(';', ',', $value, $inBraces); - } - } - unset($value); - - // Then rebuild the formula string - $cellDataFormula = implode('"', $temp); + $cellDataFormula = FormulaTranslator::convertToExcelFormulaValue($cellDataFormula); } if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) { @@ -616,30 +579,7 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) } // Merged cells - if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned') - || $cellData->hasAttributeNS($tableNs, 'number-rows-spanned') - ) { - if (($type !== DataType::TYPE_NULL) || (!$this->readDataOnly)) { - $columnTo = $columnID; - - if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) { - $columnIndex = Coordinate::columnIndexFromString($columnID); - $columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned'); - $columnIndex -= 2; - - $columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1); - } - - $rowTo = $rowID; - - if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) { - $rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1; - } - - $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo; - $spreadsheet->getActiveSheet()->mergeCells($cellRange); - } - } + $this->processMergedCells($cellData, $tableNs, $type, $columnID, $rowID, $spreadsheet); ++$columnID; } @@ -648,40 +588,111 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) break; } } + $pageSettings->setPrintSettingsForWorksheet($spreadsheet->getActiveSheet(), $worksheetStyleName); ++$worksheetID; } + + $autoFilterReader->read($workbookData); + $definedNameReader->read($workbookData); + } + $spreadsheet->setActiveSheetIndex(0); + + if ($zip->locateName('settings.xml') !== false) { + $this->processSettings($zip, $spreadsheet); } // Return return $spreadsheet; } + private function processSettings(ZipArchive $zip, Spreadsheet $spreadsheet): void + { + $dom = new DOMDocument('1.01', 'UTF-8'); + $dom->loadXML( + $this->securityScanner->scan($zip->getFromName('settings.xml')), + Settings::getLibXmlLoaderOptions() + ); + //$xlinkNs = $dom->lookupNamespaceUri('xlink'); + $configNs = $dom->lookupNamespaceUri('config'); + //$oooNs = $dom->lookupNamespaceUri('ooo'); + $officeNs = $dom->lookupNamespaceUri('office'); + $settings = $dom->getElementsByTagNameNS($officeNs, 'settings') + ->item(0); + $this->lookForActiveSheet($settings, $spreadsheet, $configNs); + $this->lookForSelectedCells($settings, $spreadsheet, $configNs); + } + + private function lookForActiveSheet(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void + { + /** @var DOMElement $t */ + foreach ($settings->getElementsByTagNameNS($configNs, 'config-item') as $t) { + if ($t->getAttributeNs($configNs, 'name') === 'ActiveTable') { + try { + $spreadsheet->setActiveSheetIndexByName($t->nodeValue ?: ''); + } catch (Throwable $e) { + // do nothing + } + + break; + } + } + } + + private function lookForSelectedCells(DOMElement $settings, Spreadsheet $spreadsheet, string $configNs): void + { + /** @var DOMElement $t */ + foreach ($settings->getElementsByTagNameNS($configNs, 'config-item-map-named') as $t) { + if ($t->getAttributeNs($configNs, 'name') === 'Tables') { + foreach ($t->getElementsByTagNameNS($configNs, 'config-item-map-entry') as $ws) { + $setRow = $setCol = ''; + $wsname = $ws->getAttributeNs($configNs, 'name'); + foreach ($ws->getElementsByTagNameNS($configNs, 'config-item') as $configItem) { + $attrName = $configItem->getAttributeNs($configNs, 'name'); + if ($attrName === 'CursorPositionX') { + $setCol = $configItem->nodeValue; + } + if ($attrName === 'CursorPositionY') { + $setRow = $configItem->nodeValue; + } + } + $this->setSelected($spreadsheet, $wsname, "$setCol", "$setRow"); + } + + break; + } + } + } + + private function setSelected(Spreadsheet $spreadsheet, string $wsname, string $setCol, string $setRow): void + { + if (is_numeric($setCol) && is_numeric($setRow)) { + try { + $spreadsheet->getSheetByName($wsname)->setSelectedCellByColumnAndRow($setCol + 1, $setRow + 1); + } catch (Throwable $e) { + // do nothing + } + } + } + /** * Recursively scan element. * - * @param \DOMNode $element - * * @return string */ - protected function scanElementForText(\DOMNode $element) + protected function scanElementForText(DOMNode $element) { $str = ''; foreach ($element->childNodes as $child) { - /** @var \DOMNode $child */ + /** @var DOMNode $child */ if ($child->nodeType == XML_TEXT_NODE) { $str .= $child->nodeValue; } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') { // It's a space // Multiple spaces? - /** @var \DOMAttr $cAttr */ + /** @var DOMAttr $cAttr */ $cAttr = $child->attributes->getNamedItem('c'); - if ($cAttr) { - $multiplier = (int) $cAttr->nodeValue; - } else { - $multiplier = 1; - } - + $multiplier = self::getMultiplier($cAttr); $str .= str_repeat(' ', $multiplier); } @@ -693,6 +704,17 @@ protected function scanElementForText(\DOMNode $element) return $str; } + private static function getMultiplier(?DOMAttr $cAttr): int + { + if ($cAttr) { + $multiplier = (int) $cAttr->nodeValue; + } else { + $multiplier = 1; + } + + return $multiplier; + } + /** * @param string $is * @@ -705,4 +727,39 @@ private function parseRichText($is) return $value; } + + private function processMergedCells( + DOMElement $cellData, + string $tableNs, + string $type, + string $columnID, + int $rowID, + Spreadsheet $spreadsheet + ): void { + if ( + $cellData->hasAttributeNS($tableNs, 'number-columns-spanned') + || $cellData->hasAttributeNS($tableNs, 'number-rows-spanned') + ) { + if (($type !== DataType::TYPE_NULL) || ($this->readDataOnly === false)) { + $columnTo = $columnID; + + if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) { + $columnIndex = Coordinate::columnIndexFromString($columnID); + $columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned'); + $columnIndex -= 2; + + $columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1); + } + + $rowTo = $rowID; + + if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) { + $rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1; + } + + $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo; + $spreadsheet->getActiveSheet()->mergeCells($cellRange); + } + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php new file mode 100644 index 00000000..1f5f975d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/AutoFilter.php @@ -0,0 +1,45 @@ +readAutoFilters($workbookData); + } + + protected function readAutoFilters(DOMElement $workbookData): void + { + $databases = $workbookData->getElementsByTagNameNS($this->tableNs, 'database-ranges'); + + foreach ($databases as $autofilters) { + foreach ($autofilters->childNodes as $autofilter) { + $autofilterRange = $this->getAttributeValue($autofilter, 'target-range-address'); + if ($autofilterRange !== null) { + $baseAddress = FormulaTranslator::convertToExcelAddressValue($autofilterRange); + $this->spreadsheet->getActiveSheet()->setAutoFilter($baseAddress); + } + } + } + } + + protected function getAttributeValue(?DOMNode $node, string $attributeName): ?string + { + if ($node !== null && $node->attributes !== null) { + $attribute = $node->attributes->getNamedItemNS( + $this->tableNs, + $attributeName + ); + + if ($attribute !== null) { + return $attribute->nodeValue; + } + } + + return null; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseLoader.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseLoader.php new file mode 100644 index 00000000..b06691f4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/BaseLoader.php @@ -0,0 +1,27 @@ +spreadsheet = $spreadsheet; + $this->tableNs = $tableNs; + } + + abstract public function read(DOMElement $workbookData): void; +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php new file mode 100644 index 00000000..e0ab8900 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/DefinedNames.php @@ -0,0 +1,66 @@ +readDefinedRanges($workbookData); + $this->readDefinedExpressions($workbookData); + } + + /** + * Read any Named Ranges that are defined in this spreadsheet. + */ + protected function readDefinedRanges(DOMElement $workbookData): void + { + $namedRanges = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-range'); + foreach ($namedRanges as $definedNameElement) { + $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); + $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); + $range = $definedNameElement->getAttributeNS($this->tableNs, 'cell-range-address'); + + $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); + $range = FormulaTranslator::convertToExcelAddressValue($range); + + $this->addDefinedName($baseAddress, $definedName, $range); + } + } + + /** + * Read any Named Formulae that are defined in this spreadsheet. + */ + protected function readDefinedExpressions(DOMElement $workbookData): void + { + $namedExpressions = $workbookData->getElementsByTagNameNS($this->tableNs, 'named-expression'); + foreach ($namedExpressions as $definedNameElement) { + $definedName = $definedNameElement->getAttributeNS($this->tableNs, 'name'); + $baseAddress = $definedNameElement->getAttributeNS($this->tableNs, 'base-cell-address'); + $expression = $definedNameElement->getAttributeNS($this->tableNs, 'expression'); + + $baseAddress = FormulaTranslator::convertToExcelAddressValue($baseAddress); + $expression = substr($expression, strpos($expression, ':=') + 1); + $expression = FormulaTranslator::convertToExcelFormulaValue($expression); + + $this->addDefinedName($baseAddress, $definedName, $expression); + } + } + + /** + * Assess scope and store the Defined Name. + */ + private function addDefinedName(string $baseAddress, string $definedName, string $value): void + { + [$sheetReference] = Worksheet::extractSheetTitle($baseAddress, true); + $worksheet = $this->spreadsheet->getSheetByName($sheetReference); + // Worksheet might still be null if we're only loading selected sheets rather than the full spreadsheet + if ($worksheet !== null) { + $this->spreadsheet->addDefinedName(DefinedName::createInstance((string) $definedName, $worksheet, $value)); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php new file mode 100644 index 00000000..f2ad1a3d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/FormulaTranslator.php @@ -0,0 +1,81 @@ +setDomNameSpaces($styleDom); + $this->readPageSettingStyles($styleDom); + $this->readStyleMasterLookup($styleDom); + } + + private function setDomNameSpaces(DOMDocument $styleDom): void + { + $this->officeNs = $styleDom->lookupNamespaceUri('office'); + $this->stylesNs = $styleDom->lookupNamespaceUri('style'); + $this->stylesFo = $styleDom->lookupNamespaceUri('fo'); + } + + private function readPageSettingStyles(DOMDocument $styleDom): void + { + $styles = $styleDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles') + ->item(0) + ->getElementsByTagNameNS($this->stylesNs, 'page-layout'); + + foreach ($styles as $styleSet) { + $styleName = $styleSet->getAttributeNS($this->stylesNs, 'name'); + $pageLayoutProperties = $styleSet->getElementsByTagNameNS($this->stylesNs, 'page-layout-properties')[0]; + $styleOrientation = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-orientation'); + $styleScale = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'scale-to'); + $stylePrintOrder = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'print-page-order'); + $centered = $pageLayoutProperties->getAttributeNS($this->stylesNs, 'table-centering'); + + $marginLeft = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-left'); + $marginRight = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-right'); + $marginTop = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-top'); + $marginBottom = $pageLayoutProperties->getAttributeNS($this->stylesFo, 'margin-bottom'); + $header = $styleSet->getElementsByTagNameNS($this->stylesNs, 'header-style')[0]; + $headerProperties = $header->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0]; + $marginHeader = isset($headerProperties) ? $headerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; + $footer = $styleSet->getElementsByTagNameNS($this->stylesNs, 'footer-style')[0]; + $footerProperties = $footer->getElementsByTagNameNS($this->stylesNs, 'header-footer-properties')[0]; + $marginFooter = isset($footerProperties) ? $footerProperties->getAttributeNS($this->stylesFo, 'min-height') : null; + + $this->pageLayoutStyles[$styleName] = (object) [ + 'orientation' => $styleOrientation ?: PageSetup::ORIENTATION_DEFAULT, + 'scale' => $styleScale ?: 100, + 'printOrder' => $stylePrintOrder, + 'horizontalCentered' => $centered === 'horizontal' || $centered === 'both', + 'verticalCentered' => $centered === 'vertical' || $centered === 'both', + // margin size is already stored in inches, so no UOM conversion is required + 'marginLeft' => (float) $marginLeft ?? 0.7, + 'marginRight' => (float) $marginRight ?? 0.7, + 'marginTop' => (float) $marginTop ?? 0.3, + 'marginBottom' => (float) $marginBottom ?? 0.3, + 'marginHeader' => (float) $marginHeader ?? 0.45, + 'marginFooter' => (float) $marginFooter ?? 0.45, + ]; + } + } + + private function readStyleMasterLookup(DOMDocument $styleDom): void + { + $styleMasterLookup = $styleDom->getElementsByTagNameNS($this->officeNs, 'master-styles') + ->item(0) + ->getElementsByTagNameNS($this->stylesNs, 'master-page'); + + foreach ($styleMasterLookup as $styleMasterSet) { + $styleMasterName = $styleMasterSet->getAttributeNS($this->stylesNs, 'name'); + $pageLayoutName = $styleMasterSet->getAttributeNS($this->stylesNs, 'page-layout-name'); + $this->masterPrintStylesCrossReference[$styleMasterName] = $pageLayoutName; + } + } + + public function readStyleCrossReferences(DOMDocument $contentDom): void + { + $styleXReferences = $contentDom->getElementsByTagNameNS($this->officeNs, 'automatic-styles') + ->item(0) + ->getElementsByTagNameNS($this->stylesNs, 'style'); + + foreach ($styleXReferences as $styleXreferenceSet) { + $styleXRefName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'name'); + $stylePageLayoutName = $styleXreferenceSet->getAttributeNS($this->stylesNs, 'master-page-name'); + if (!empty($stylePageLayoutName)) { + $this->masterStylesCrossReference[$styleXRefName] = $stylePageLayoutName; + } + } + } + + public function setPrintSettingsForWorksheet(Worksheet $worksheet, string $styleName): void + { + if (!array_key_exists($styleName, $this->masterStylesCrossReference)) { + return; + } + $masterStyleName = $this->masterStylesCrossReference[$styleName]; + + if (!array_key_exists($masterStyleName, $this->masterPrintStylesCrossReference)) { + return; + } + $printSettingsIndex = $this->masterPrintStylesCrossReference[$masterStyleName]; + + if (!array_key_exists($printSettingsIndex, $this->pageLayoutStyles)) { + return; + } + $printSettings = $this->pageLayoutStyles[$printSettingsIndex]; + + $worksheet->getPageSetup() + ->setOrientation($printSettings->orientation ?? PageSetup::ORIENTATION_DEFAULT) + ->setPageOrder($printSettings->printOrder === 'ltr' ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER) + ->setScale((int) trim($printSettings->scale, '%')) + ->setHorizontalCentered($printSettings->horizontalCentered) + ->setVerticalCentered($printSettings->verticalCentered); + + $worksheet->getPageMargins() + ->setLeft($printSettings->marginLeft) + ->setRight($printSettings->marginRight) + ->setTop($printSettings->marginTop) + ->setBottom($printSettings->marginBottom) + ->setHeader($printSettings->marginHeader) + ->setFooter($printSettings->marginFooter); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php index c5c7caf8..fc789367 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Ods/Properties.php @@ -4,6 +4,7 @@ use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use SimpleXMLElement; class Properties { @@ -14,7 +15,7 @@ public function __construct(Spreadsheet $spreadsheet) $this->spreadsheet = $spreadsheet; } - public function load(\SimpleXMLElement $xml, $namespacesMeta) + public function load(SimpleXMLElement $xml, $namespacesMeta): void { $docProps = $this->spreadsheet->getProperties(); $officeProperty = $xml->children($namespacesMeta['office']); @@ -25,7 +26,7 @@ public function load(\SimpleXMLElement $xml, $namespacesMeta) $this->setCoreProperties($docProps, $officePropertiesDC); } - $officePropertyMeta = (object) []; + $officePropertyMeta = []; if (isset($namespacesMeta['dc'])) { $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); } @@ -35,7 +36,7 @@ public function load(\SimpleXMLElement $xml, $namespacesMeta) } } - private function setCoreProperties(DocumentProperties $docProps, \SimpleXMLElement $officePropertyDC) + private function setCoreProperties(DocumentProperties $docProps, SimpleXMLElement $officePropertyDC): void { foreach ($officePropertyDC as $propertyName => $propertyValue) { $propertyValue = (string) $propertyValue; @@ -53,14 +54,8 @@ private function setCoreProperties(DocumentProperties $docProps, \SimpleXMLEleme $docProps->setLastModifiedBy($propertyValue); break; - case 'creation-date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); - $docProps->setModified($creationDate); - - break; - case 'keyword': - $docProps->setKeywords($propertyValue); + case 'date': + $docProps->setModified($propertyValue); break; case 'description': @@ -73,10 +68,10 @@ private function setCoreProperties(DocumentProperties $docProps, \SimpleXMLEleme private function setMetaProperties( $namespacesMeta, - \SimpleXMLElement $propertyValue, + SimpleXMLElement $propertyValue, $propertyName, DocumentProperties $docProps - ) { + ): void { $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']); $propertyValue = (string) $propertyValue; switch ($propertyName) { @@ -89,8 +84,7 @@ private function setMetaProperties( break; case 'creation-date': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); + $docProps->setCreated($propertyValue); break; case 'user-defined': @@ -100,7 +94,7 @@ private function setMetaProperties( } } - private function setUserDefinedProperty($propertyValueAttributes, $propertyValue, DocumentProperties $docProps) + private function setUserDefinedProperty($propertyValueAttributes, $propertyValue, DocumentProperties $docProps): void { $propertyValueName = ''; $propertyValueType = DocumentProperties::PROPERTY_TYPE_STRING; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php index 732f0bf6..8155b838 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Security/XmlScanner.php @@ -3,7 +3,6 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Security; use PhpOffice\PhpSpreadsheet\Reader; -use PhpOffice\PhpSpreadsheet\Settings; class XmlScanner { @@ -18,6 +17,11 @@ class XmlScanner private static $libxmlDisableEntityLoaderValue; + /** + * @var bool + */ + private static $shutdownRegistered = false; + public function __construct($pattern = 'pattern = $pattern; @@ -25,7 +29,10 @@ public function __construct($pattern = 'disableEntityLoaderCheck(); // A fatal error will bypass the destructor, so we register a shutdown here - register_shutdown_function([__CLASS__, 'shutdown']); + if (!self::$shutdownRegistered) { + self::$shutdownRegistered = true; + register_shutdown_function([__CLASS__, 'shutdown']); + } } public static function getInstance(Reader\IReader $reader) @@ -61,9 +68,9 @@ public static function threadSafeLibxmlDisableEntityLoaderAvailability() return false; } - private function disableEntityLoaderCheck() + private function disableEntityLoaderCheck(): void { - if (Settings::getLibXmlDisableEntityLoader()) { + if (\PHP_VERSION_ID < 80000) { $libxmlDisableEntityLoaderValue = libxml_disable_entity_loader(true); if (self::$libxmlDisableEntityLoaderValue === null) { @@ -72,9 +79,9 @@ private function disableEntityLoaderCheck() } } - public static function shutdown() + public static function shutdown(): void { - if (self::$libxmlDisableEntityLoaderValue !== null) { + if (self::$libxmlDisableEntityLoaderValue !== null && \PHP_VERSION_ID < 80000) { libxml_disable_entity_loader(self::$libxmlDisableEntityLoaderValue); self::$libxmlDisableEntityLoaderValue = null; } @@ -85,7 +92,7 @@ public function __destruct() self::shutdown(); } - public function setAdditionalCallback(callable $callback) + public function setAdditionalCallback(callable $callback): void { $this->callback = $callback; } @@ -114,8 +121,6 @@ private function toUtf8($xml) * * @param mixed $xml * - * @throws Reader\Exception - * * @return string */ public function scan($xml) @@ -143,8 +148,6 @@ public function scan($xml) * * @param string $filestream * - * @throws Reader\Exception - * * @return string */ public function scanFile($filestream) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php index 9912e937..c33f0202 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Slk.php @@ -4,9 +4,11 @@ use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Border; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Slk extends BaseReader { @@ -38,6 +40,20 @@ class Slk extends BaseReader */ private $format = 0; + /** + * Fonts. + * + * @var array + */ + private $fonts = []; + + /** + * Font Count. + * + * @var int + */ + private $fontcount = 0; + /** * Create a new SYLK Reader instance. */ @@ -48,22 +64,17 @@ public function __construct() /** * Validate that the current file is a SYLK file. - * - * @param string $pFilename - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { - // Check if file exists try { - $this->openFile($pFilename); - } catch (Exception $e) { + $this->openFile($filename); + } catch (ReaderException $e) { return false; } // Read sample data (first 2 KB will do) - $data = fread($this->fileHandle, 2048); + $data = (string) fread($this->fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); @@ -78,16 +89,28 @@ public function canRead($pFilename) return $hasDelimiter && $hasId; } + private function canReadOrBust(string $filename): void + { + if (!$this->canRead($filename)) { + throw new ReaderException($filename . ' is an Invalid SYLK file.'); + } + $this->openFile($filename); + } + /** * Set input encoding. * - * @param string $pValue Input encoding, eg: 'ANSI' + * @deprecated no use is made of this property + * + * @param string $inputEncoding Input encoding, eg: 'ANSI' * * @return $this + * + * @codeCoverageIgnore */ - public function setInputEncoding($pValue) + public function setInputEncoding($inputEncoding) { - $this->inputEncoding = $pValue; + $this->inputEncoding = $inputEncoding; return $this; } @@ -95,7 +118,11 @@ public function setInputEncoding($pValue) /** * Get input encoding. * + * @deprecated no use is made of this property + * * @return string + * + * @codeCoverageIgnore */ public function getInputEncoding() { @@ -105,31 +132,23 @@ public function getInputEncoding() /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { // Open file - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); - } - $this->openFile($pFilename); + $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); $worksheetInfo = []; - $worksheetInfo[0]['worksheetName'] = 'Worksheet'; - $worksheetInfo[0]['lastColumnLetter'] = 'A'; - $worksheetInfo[0]['lastColumnIndex'] = 0; - $worksheetInfo[0]['totalRows'] = 0; - $worksheetInfo[0]['totalColumns'] = 0; + $worksheetInfo[0]['worksheetName'] = basename($filename, '.slk'); // loop through one row (line) at a time in the file $rowIndex = 0; + $columnIndex = 0; while (($rowData = fgets($fileHandle)) !== false) { $columnIndex = 0; @@ -141,28 +160,26 @@ public function listWorksheetInfo($pFilename) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); $dataType = array_shift($rowData); - if ($dataType == 'C') { - // Read cell value data + if ($dataType == 'B') { foreach ($rowData as $rowDatum) { switch ($rowDatum[0]) { - case 'C': case 'X': - $columnIndex = substr($rowDatum, 1) - 1; + $columnIndex = (int) substr($rowDatum, 1) - 1; break; - case 'R': case 'Y': $rowIndex = substr($rowDatum, 1); break; } - - $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); - $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); } + + break; } } + $worksheetInfo[0]['lastColumnIndex'] = $columnIndex; + $worksheetInfo[0]['totalRows'] = $rowIndex; $worksheetInfo[0]['lastColumnLetter'] = Coordinate::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex'] + 1); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; @@ -174,39 +191,325 @@ public function listWorksheetInfo($pFilename) /** * Loads PhpSpreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); + return $this->loadIntoExisting($filename, $spreadsheet); + } + + private const COLOR_ARRAY = [ + 'FF00FFFF', // 0 - cyan + 'FF000000', // 1 - black + 'FFFFFFFF', // 2 - white + 'FFFF0000', // 3 - red + 'FF00FF00', // 4 - green + 'FF0000FF', // 5 - blue + 'FFFFFF00', // 6 - yellow + 'FFFF00FF', // 7 - magenta + ]; + + private const FONT_STYLE_MAPPINGS = [ + 'B' => 'bold', + 'I' => 'italic', + 'U' => 'underline', + ]; + + private function processFormula(string $rowDatum, bool &$hasCalculatedValue, string &$cellDataFormula, string $row, string $column): void + { + $cellDataFormula = '=' . substr($rowDatum, 1); + // Convert R1C1 style references to A1 style references (but only when not quoted) + $temp = explode('"', $cellDataFormula); + $key = false; + foreach ($temp as &$value) { + // Only count/replace in alternate array entries + $key = !$key; + if ($key) { + preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach ($cellReferences as $cellReference) { + $rowReference = $cellReference[2][0]; + // Empty R reference is the current row + if ($rowReference == '') { + $rowReference = $row; + } + // Bracketed R references are relative to the current row + if ($rowReference[0] == '[') { + $rowReference = (int) $row + (int) trim($rowReference, '[]'); + } + $columnReference = $cellReference[4][0]; + // Empty C reference is the current column + if ($columnReference == '') { + $columnReference = $column; + } + // Bracketed C references are relative to the current column + if ($columnReference[0] == '[') { + $columnReference = (int) $column + (int) trim($columnReference, '[]'); + } + $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; + + $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); + } + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"', $temp); + $hasCalculatedValue = true; + } + + private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void + { + // Read cell value data + $hasCalculatedValue = false; + $cellDataFormula = $cellData = ''; + foreach ($rowData as $rowDatum) { + switch ($rowDatum[0]) { + case 'C': + case 'X': + $column = substr($rowDatum, 1); + + break; + case 'R': + case 'Y': + $row = substr($rowDatum, 1); + + break; + case 'K': + $cellData = substr($rowDatum, 1); + + break; + case 'E': + $this->processFormula($rowDatum, $hasCalculatedValue, $cellDataFormula, $row, $column); + + break; + case 'A': + $comment = substr($rowDatum, 1); + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + $spreadsheet->getActiveSheet() + ->getComment("$columnLetter$row") + ->getText() + ->createText($comment); + + break; + } + } + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + $cellData = Calculation::unwrapResult($cellData); + + // Set cell value + $this->processCFinal($spreadsheet, $hasCalculatedValue, $cellDataFormula, $cellData, "$columnLetter$row"); + } + + private function processCFinal(Spreadsheet &$spreadsheet, bool $hasCalculatedValue, string $cellDataFormula, string $cellData, string $coordinate): void + { + // Set cell value + $spreadsheet->getActiveSheet()->getCell($coordinate)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); + if ($hasCalculatedValue) { + $cellData = Calculation::unwrapResult($cellData); + $spreadsheet->getActiveSheet()->getCell($coordinate)->setCalculatedValue($cellData); + } + } + + private function processFRecord(array $rowData, Spreadsheet &$spreadsheet, string &$row, string &$column): void + { + // Read cell formatting + $formatStyle = $columnWidth = ''; + $startCol = $endCol = ''; + $fontStyle = ''; + $styleData = []; + foreach ($rowData as $rowDatum) { + switch ($rowDatum[0]) { + case 'C': + case 'X': + $column = substr($rowDatum, 1); + + break; + case 'R': + case 'Y': + $row = substr($rowDatum, 1); + + break; + case 'P': + $formatStyle = $rowDatum; + + break; + case 'W': + [$startCol, $endCol, $columnWidth] = explode(' ', substr($rowDatum, 1)); + + break; + case 'S': + $this->styleSettings($rowDatum, $styleData, $fontStyle); + + break; + } + } + $this->addFormats($spreadsheet, $formatStyle, $row, $column); + $this->addFonts($spreadsheet, $fontStyle, $row, $column); + $this->addStyle($spreadsheet, $styleData, $row, $column); + $this->addWidth($spreadsheet, $columnWidth, $startCol, $endCol); + } + + private const STYLE_SETTINGS_FONT = ['D' => 'bold', 'I' => 'italic']; + + private const STYLE_SETTINGS_BORDER = [ + 'B' => 'bottom', + 'L' => 'left', + 'R' => 'right', + 'T' => 'top', + ]; + + private function styleSettings(string $rowDatum, array &$styleData, string &$fontStyle): void + { + $styleSettings = substr($rowDatum, 1); + $iMax = strlen($styleSettings); + for ($i = 0; $i < $iMax; ++$i) { + $char = $styleSettings[$i]; + if (array_key_exists($char, self::STYLE_SETTINGS_FONT)) { + $styleData['font'][self::STYLE_SETTINGS_FONT[$char]] = true; + } elseif (array_key_exists($char, self::STYLE_SETTINGS_BORDER)) { + $styleData['borders'][self::STYLE_SETTINGS_BORDER[$char]]['borderStyle'] = Border::BORDER_THIN; + } elseif ($char == 'S') { + $styleData['fill']['fillType'] = \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_PATTERN_GRAY125; + } elseif ($char == 'M') { + if (preg_match('/M([1-9]\\d*)/', $styleSettings, $matches)) { + $fontStyle = $matches[1]; + } + } + } + } + + private function addFormats(Spreadsheet &$spreadsheet, string $formatStyle, string $row, string $column): void + { + if ($formatStyle && $column > '' && $row > '') { + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + if (isset($this->formats[$formatStyle])) { + $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]); + } + } + } + + private function addFonts(Spreadsheet &$spreadsheet, string $fontStyle, string $row, string $column): void + { + if ($fontStyle && $column > '' && $row > '') { + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + if (isset($this->fonts[$fontStyle])) { + $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->fonts[$fontStyle]); + } + } + } + + private function addStyle(Spreadsheet &$spreadsheet, array $styleData, string $row, string $column): void + { + if ((!empty($styleData)) && $column > '' && $row > '') { + $columnLetter = Coordinate::stringFromColumnIndex((int) $column); + $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); + } + } + + private function addWidth(Spreadsheet $spreadsheet, string $columnWidth, string $startCol, string $endCol): void + { + if ($columnWidth > '') { + if ($startCol == $endCol) { + $startCol = Coordinate::stringFromColumnIndex((int) $startCol); + $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); + } else { + $startCol = Coordinate::stringFromColumnIndex((int) $startCol); + $endCol = Coordinate::stringFromColumnIndex((int) $endCol); + $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth((float) $columnWidth); + do { + $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth((float) $columnWidth); + } while ($startCol !== $endCol); + } + } + } + + private function processPRecord(array $rowData, Spreadsheet &$spreadsheet): void + { + // Read shared styles + $formatArray = []; + $fromFormats = ['\-', '\ ']; + $toFormats = ['-', ' ']; + foreach ($rowData as $rowDatum) { + switch ($rowDatum[0]) { + case 'P': + $formatArray['numberFormat']['formatCode'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); + + break; + case 'E': + case 'F': + $formatArray['font']['name'] = substr($rowDatum, 1); + + break; + case 'M': + $formatArray['font']['size'] = substr($rowDatum, 1) / 20; + + break; + case 'L': + $this->processPColors($rowDatum, $formatArray); + + break; + case 'S': + $this->processPFontStyles($rowDatum, $formatArray); + + break; + } + } + $this->processPFinal($spreadsheet, $formatArray); + } + + private function processPColors(string $rowDatum, array &$formatArray): void + { + if (preg_match('/L([1-9]\\d*)/', $rowDatum, $matches)) { + $fontColor = $matches[1] % 8; + $formatArray['font']['color']['argb'] = self::COLOR_ARRAY[$fontColor]; + } + } + + private function processPFontStyles(string $rowDatum, array &$formatArray): void + { + $styleSettings = substr($rowDatum, 1); + $iMax = strlen($styleSettings); + for ($i = 0; $i < $iMax; ++$i) { + if (array_key_exists($styleSettings[$i], self::FONT_STYLE_MAPPINGS)) { + $formatArray['font'][self::FONT_STYLE_MAPPINGS[$styleSettings[$i]]] = true; + } + } + } + + private function processPFinal(Spreadsheet &$spreadsheet, array $formatArray): void + { + if (array_key_exists('numberFormat', $formatArray)) { + $this->formats['P' . $this->format] = $formatArray; + ++$this->format; + } elseif (array_key_exists('font', $formatArray)) { + ++$this->fontcount; + $this->fonts[$this->fontcount] = $formatArray; + if ($this->fontcount === 1) { + $spreadsheet->getDefaultStyle()->applyFromArray($formatArray); + } + } } /** * Loads PhpSpreadsheet from file into PhpSpreadsheet instance. * - * @param string $pFilename - * @param Spreadsheet $spreadsheet - * - * @throws Exception + * @param string $filename * * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { // Open file - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); - } - $this->openFile($pFilename); + $this->canReadOrBust($filename); $fileHandle = $this->fileHandle; rewind($fileHandle); @@ -215,251 +518,32 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $spreadsheet->createSheet(); } $spreadsheet->setActiveSheetIndex($this->sheetIndex); - - $fromFormats = ['\-', '\ ']; - $toFormats = ['-', ' ']; + $spreadsheet->getActiveSheet()->setTitle(substr(basename($filename, '.slk'), 0, Worksheet::SHEET_TITLE_MAXIMUM_LENGTH)); // Loop through file $column = $row = ''; // loop through one row (line) at a time in the file - while (($rowData = fgets($fileHandle)) !== false) { + while (($rowDataTxt = fgets($fileHandle)) !== false) { // convert SYLK encoded $rowData to UTF-8 - $rowData = StringHelper::SYLKtoUTF8($rowData); + $rowDataTxt = StringHelper::SYLKtoUTF8($rowDataTxt); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) - $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); + $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowDataTxt))))); $dataType = array_shift($rowData); - // Read shared styles if ($dataType == 'P') { - $formatArray = []; - foreach ($rowData as $rowDatum) { - switch ($rowDatum[0]) { - case 'P': - $formatArray['numberFormat']['formatCode'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); - - break; - case 'E': - case 'F': - $formatArray['font']['name'] = substr($rowDatum, 1); - - break; - case 'L': - $formatArray['font']['size'] = substr($rowDatum, 1); - - break; - case 'S': - $styleSettings = substr($rowDatum, 1); - $iMax = strlen($styleSettings); - for ($i = 0; $i < $iMax; ++$i) { - switch ($styleSettings[$i]) { - case 'I': - $formatArray['font']['italic'] = true; - - break; - case 'D': - $formatArray['font']['bold'] = true; - - break; - case 'T': - $formatArray['borders']['top']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'B': - $formatArray['borders']['bottom']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'L': - $formatArray['borders']['left']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'R': - $formatArray['borders']['right']['borderStyle'] = Border::BORDER_THIN; - - break; - } - } - - break; - } - } - $this->formats['P' . $this->format++] = $formatArray; - // Read cell value data + // Read shared styles + $this->processPRecord($rowData, $spreadsheet); } elseif ($dataType == 'C') { - $hasCalculatedValue = false; - $cellData = $cellDataFormula = ''; - foreach ($rowData as $rowDatum) { - switch ($rowDatum[0]) { - case 'C': - case 'X': - $column = substr($rowDatum, 1); - - break; - case 'R': - case 'Y': - $row = substr($rowDatum, 1); - - break; - case 'K': - $cellData = substr($rowDatum, 1); - - break; - case 'E': - $cellDataFormula = '=' . substr($rowDatum, 1); - // Convert R1C1 style references to A1 style references (but only when not quoted) - $temp = explode('"', $cellDataFormula); - $key = false; - foreach ($temp as &$value) { - // Only count/replace in alternate array entries - if ($key = !$key) { - preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); - // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way - // through the formula from left to right. Reversing means that we work right to left.through - // the formula - $cellReferences = array_reverse($cellReferences); - // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, - // then modify the formula to use that new reference - foreach ($cellReferences as $cellReference) { - $rowReference = $cellReference[2][0]; - // Empty R reference is the current row - if ($rowReference == '') { - $rowReference = $row; - } - // Bracketed R references are relative to the current row - if ($rowReference[0] == '[') { - $rowReference = $row + trim($rowReference, '[]'); - } - $columnReference = $cellReference[4][0]; - // Empty C reference is the current column - if ($columnReference == '') { - $columnReference = $column; - } - // Bracketed C references are relative to the current column - if ($columnReference[0] == '[') { - $columnReference = $column + trim($columnReference, '[]'); - } - $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; - - $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); - } - } - } - unset($value); - // Then rebuild the formula string - $cellDataFormula = implode('"', $temp); - $hasCalculatedValue = true; - - break; - } - } - $columnLetter = Coordinate::stringFromColumnIndex($column); - $cellData = Calculation::unwrapResult($cellData); - - // Set cell value - $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); - if ($hasCalculatedValue) { - $cellData = Calculation::unwrapResult($cellData); - $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setCalculatedValue($cellData); - } - // Read cell formatting + // Read cell value data + $this->processCRecord($rowData, $spreadsheet, $row, $column); } elseif ($dataType == 'F') { - $formatStyle = $columnWidth = $styleSettings = ''; - $styleData = []; - foreach ($rowData as $rowDatum) { - switch ($rowDatum[0]) { - case 'C': - case 'X': - $column = substr($rowDatum, 1); - - break; - case 'R': - case 'Y': - $row = substr($rowDatum, 1); - - break; - case 'P': - $formatStyle = $rowDatum; - - break; - case 'W': - [$startCol, $endCol, $columnWidth] = explode(' ', substr($rowDatum, 1)); - - break; - case 'S': - $styleSettings = substr($rowDatum, 1); - $iMax = strlen($styleSettings); - for ($i = 0; $i < $iMax; ++$i) { - switch ($styleSettings[$i]) { - case 'I': - $styleData['font']['italic'] = true; - - break; - case 'D': - $styleData['font']['bold'] = true; - - break; - case 'T': - $styleData['borders']['top']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'B': - $styleData['borders']['bottom']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'L': - $styleData['borders']['left']['borderStyle'] = Border::BORDER_THIN; - - break; - case 'R': - $styleData['borders']['right']['borderStyle'] = Border::BORDER_THIN; - - break; - } - } - - break; - } - } - if (($formatStyle > '') && ($column > '') && ($row > '')) { - $columnLetter = Coordinate::stringFromColumnIndex($column); - if (isset($this->formats[$formatStyle])) { - $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]); - } - } - if ((!empty($styleData)) && ($column > '') && ($row > '')) { - $columnLetter = Coordinate::stringFromColumnIndex($column); - $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData); - } - if ($columnWidth > '') { - if ($startCol == $endCol) { - $startCol = Coordinate::stringFromColumnIndex($startCol); - $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); - } else { - $startCol = Coordinate::stringFromColumnIndex($startCol); - $endCol = Coordinate::stringFromColumnIndex($endCol); - $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); - do { - $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); - } while ($startCol != $endCol); - } - } + // Read cell formatting + $this->processFRecord($rowData, $spreadsheet, $row, $column); } else { - foreach ($rowData as $rowDatum) { - switch ($rowDatum[0]) { - case 'C': - case 'X': - $column = substr($rowDatum, 1); - - break; - case 'R': - case 'Y': - $row = substr($rowDatum, 1); - - break; - } - } + $this->columnRowFromRowData($rowData, $column, $row); } } @@ -470,6 +554,18 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) return $spreadsheet; } + private function columnRowFromRowData(array $rowData, string &$column, string &$row): void + { + foreach ($rowData as $rowDatum) { + $char0 = $rowDatum[0]; + if ($char0 === 'X' || $char0 == 'C') { + $column = substr($rowDatum, 1); + } elseif ($char0 === 'Y' || $char0 == 'R') { + $row = substr($rowDatum, 1); + } + } + } + /** * Get sheet index. * @@ -483,13 +579,13 @@ public function getSheetIndex() /** * Set sheet index. * - * @param int $pValue Sheet index + * @param int $sheetIndex Sheet index * * @return $this */ - public function setSheetIndex($pValue) + public function setSheetIndex($sheetIndex) { - $this->sheetIndex = $pValue; + $this->sheetIndex = $sheetIndex; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php index 313d7216..d1f14ae1 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls.php @@ -7,6 +7,9 @@ use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\NamedRange; +use PhpOffice\PhpSpreadsheet\Reader\Xls\ConditionalFormatting; +use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\CellFont; +use PhpOffice\PhpSpreadsheet\Reader\Xls\Style\FillPattern; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\CodePage; use PhpOffice\PhpSpreadsheet\Shared\Date; @@ -16,9 +19,12 @@ use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLERead; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +use PhpOffice\PhpSpreadsheet\Shared\Xls as SharedXls; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Borders; +use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; @@ -140,6 +146,8 @@ class Xls extends BaseReader const XLS_TYPE_SHEETLAYOUT = 0x0862; const XLS_TYPE_XFEXT = 0x087d; const XLS_TYPE_PAGELAYOUTVIEW = 0x088b; + const XLS_TYPE_CFHEADER = 0x01b0; + const XLS_TYPE_CFRULE = 0x01b1; const XLS_TYPE_UNKNOWN = 0xffff; // Encryption type @@ -224,7 +232,7 @@ class Xls extends BaseReader /** * Shared fonts. * - * @var array + * @var Font[] */ private $objFonts; @@ -374,7 +382,7 @@ class Xls extends BaseReader * * @var int */ - private $encryptionStartPos = false; + private $encryptionStartPos = 0; /** * The current RC4 decryption object. @@ -417,21 +425,19 @@ public function __construct() /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { - File::assertFile($pFilename); + if (!File::testFileNoThrow($filename)) { + return false; + } try { // Use ParseXL for the hard work. $ole = new OLERead(); // get excel data - $ole->read($pFilename); + $ole->read($filename); return true; } catch (PhpSpreadsheetException $e) { @@ -439,23 +445,30 @@ public function canRead($pFilename) } } + public function setCodepage(string $codepage): void + { + if (!CodePage::validate($codepage)) { + throw new PhpSpreadsheetException('Unknown codepage: ' . $codepage); + } + + $this->codepage = $codepage; + } + /** * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object. * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); + File::assertFile($filename); $worksheetNames = []; // Read the OLE file - $this->loadOLE($pFilename); + $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); @@ -502,20 +515,18 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename); $worksheetInfo = []; // Read the OLE file - $this->loadOLE($pFilename); + $this->loadOLE($filename); // total byte size of Excel data (workbook global substream + sheet substreams) $this->dataSize = strlen($this->data); @@ -615,17 +626,11 @@ public function listWorksheetInfo($pFilename) /** * Loads PhpSpreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Read the OLE file - $this->loadOLE($pFilename); + $this->loadOLE($filename); // Initialisations $this->spreadsheet = new Spreadsheet(); @@ -646,7 +651,7 @@ public function load($pFilename) // initialize $this->pos = 0; - $this->codepage = 'CP1252'; + $this->codepage = $this->codepage ?: CodePage::DEFAULT_CODE_PAGE; $this->formats = []; $this->objFonts = []; $this->palette = []; @@ -656,7 +661,7 @@ public function load($pFilename) $this->definedname = []; $this->sst = []; $this->drawingGroupData = ''; - $this->xfIndex = ''; + $this->xfIndex = 0; $this->mapCellXfIndex = []; $this->mapCellStyleXfIndex = []; @@ -798,9 +803,10 @@ public function load($pFilename) } // treat MSODRAWINGGROUP records, workbook-level Escher + $escherWorkbook = null; if (!$this->readDataOnly && $this->drawingGroupData) { - $escherWorkbook = new Escher(); - $reader = new Xls\Escher($escherWorkbook); + $escher = new Escher(); + $reader = new Xls\Escher($escher); $escherWorkbook = $reader->load($this->drawingGroupData); } @@ -1031,6 +1037,14 @@ public function load($pFilename) case self::XLS_TYPE_DATAVALIDATION: $this->readDataValidation(); + break; + case self::XLS_TYPE_CFHEADER: + $cellRangeAddresses = $this->readCFHeader(); + + break; + case self::XLS_TYPE_CFRULE: + $this->readCFRule($cellRangeAddresses ?? []); + break; case self::XLS_TYPE_SHEETLAYOUT: $this->readSheetLayout(); @@ -1097,12 +1111,12 @@ public function load($pFilename) $endOffsetX = $spContainer->getEndOffsetX(); $endOffsetY = $spContainer->getEndOffsetY(); - $width = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); - $height = \PhpOffice\PhpSpreadsheet\Shared\Xls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); + $width = SharedXls::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); + $height = SharedXls::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); // calculate offsetX and offsetY of the shape - $offsetX = $startOffsetX * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeCol($this->phpSheet, $startColumn) / 1024; - $offsetY = $startOffsetY * \PhpOffice\PhpSpreadsheet\Shared\Xls::sizeRow($this->phpSheet, $startRow) / 256; + $offsetX = (int) ($startOffsetX * SharedXls::sizeCol($this->phpSheet, $startColumn) / 1024); + $offsetY = (int) ($startOffsetY * SharedXls::sizeRow($this->phpSheet, $startRow) / 256); switch ($obj['otObjType']) { case 0x19: @@ -1130,38 +1144,44 @@ public function load($pFilename) continue 2; } - $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); - $BSE = $BSECollection[$BSEindex - 1]; - $blipType = $BSE->getBlipType(); - - // need check because some blip types are not supported by Escher reader such as EMF - if ($blip = $BSE->getBlip()) { - $ih = imagecreatefromstring($blip->getData()); - $drawing = new MemoryDrawing(); - $drawing->setImageResource($ih); - - // width, height, offsetX, offsetY - $drawing->setResizeProportional(false); - $drawing->setWidth($width); - $drawing->setHeight($height); - $drawing->setOffsetX($offsetX); - $drawing->setOffsetY($offsetY); - - switch ($blipType) { - case BSE::BLIPTYPE_JPEG: - $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); - $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG); - - break; - case BSE::BLIPTYPE_PNG: - $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG); - $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG); - - break; - } + if ($escherWorkbook) { + $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); + $BSE = $BSECollection[$BSEindex - 1]; + $blipType = $BSE->getBlipType(); + + // need check because some blip types are not supported by Escher reader such as EMF + if ($blip = $BSE->getBlip()) { + $ih = imagecreatefromstring($blip->getData()); + if ($ih !== false) { + $drawing = new MemoryDrawing(); + $drawing->setImageResource($ih); + + // width, height, offsetX, offsetY + $drawing->setResizeProportional(false); + $drawing->setWidth($width); + $drawing->setHeight($height); + $drawing->setOffsetX($offsetX); + $drawing->setOffsetY($offsetY); + + switch ($blipType) { + case BSE::BLIPTYPE_JPEG: + $drawing->setRenderingFunction(MemoryDrawing::RENDERING_JPEG); + $drawing->setMimeType(MemoryDrawing::MIMETYPE_JPEG); + + break; + case BSE::BLIPTYPE_PNG: + imagealphablending($ih, false); + imagesavealpha($ih, true); + $drawing->setRenderingFunction(MemoryDrawing::RENDERING_PNG); + $drawing->setMimeType(MemoryDrawing::MIMETYPE_PNG); + + break; + } - $drawing->setWorksheet($this->phpSheet); - $drawing->setCoordinates($spContainer->getStartCoordinates()); + $drawing->setWorksheet($this->phpSheet); + $drawing->setCoordinates($spContainer->getStartCoordinates()); + } + } } break; @@ -1254,10 +1274,10 @@ public function load($pFilename) [$firstColumn, $firstRow] = Coordinate::coordinateFromString($coordinateStrings[0]); [$lastColumn, $lastRow] = Coordinate::coordinateFromString($coordinateStrings[1]); - if ($firstColumn == 'A' and $lastColumn == 'IV') { + if ($firstColumn == 'A' && $lastColumn == 'IV') { // then we have repeating rows $docSheet->getPageSetup()->setRowsToRepeatAtTop([$firstRow, $lastRow]); - } elseif ($firstRow == 1 and $lastRow == 65536) { + } elseif ($firstRow == 1 && $lastRow == 65536) { // then we have repeating columns $docSheet->getPageSetup()->setColumnsToRepeatAtLeft([$firstColumn, $lastColumn]); } @@ -1272,8 +1292,10 @@ public function load($pFilename) // Extract range if (strpos($definedName['formula'], '!') !== false) { $explodes = Worksheet::extractSheetTitle($definedName['formula'], true); - if (($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) || - ($docSheet = $this->spreadsheet->getSheetByName(trim($explodes[0], "'")))) { + if ( + ($docSheet = $this->spreadsheet->getSheetByName($explodes[0])) || + ($docSheet = $this->spreadsheet->getSheetByName(trim($explodes[0], "'"))) + ) { $extractedRange = $explodes[1]; $extractedRange = str_replace('$', '', $extractedRange); @@ -1288,7 +1310,7 @@ public function load($pFilename) // TODO Provide support for named values } } - $this->data = null; + $this->data = ''; return $this->spreadsheet; } @@ -1352,14 +1374,14 @@ private function readRecordData($data, $pos, $len) /** * Use OLE reader to extract the relevant data streams from the OLE file. * - * @param string $pFilename + * @param string $filename */ - private function loadOLE($pFilename) + private function loadOLE($filename): void { // OLE reader $ole = new OLERead(); // get excel data, - $ole->read($pFilename); + $ole->read($filename); // Get workbook data: workbook stream + sheet streams $this->data = $ole->getStream($ole->wrkbook); // Get summary information data @@ -1371,7 +1393,7 @@ private function loadOLE($pFilename) /** * Read summary information. */ - private function readSummaryInformation() + private function readSummaryInformation(): void { if (!isset($this->summaryInformation)) { return; @@ -1446,34 +1468,34 @@ private function readSummaryInformation() switch ($id) { case 0x01: // Code Page - $codePage = CodePage::numberToName($value); + $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Title - $this->spreadsheet->getProperties()->setTitle($value); + $this->spreadsheet->getProperties()->setTitle("$value"); break; case 0x03: // Subject - $this->spreadsheet->getProperties()->setSubject($value); + $this->spreadsheet->getProperties()->setSubject("$value"); break; case 0x04: // Author (Creator) - $this->spreadsheet->getProperties()->setCreator($value); + $this->spreadsheet->getProperties()->setCreator("$value"); break; case 0x05: // Keywords - $this->spreadsheet->getProperties()->setKeywords($value); + $this->spreadsheet->getProperties()->setKeywords("$value"); break; case 0x06: // Comments (Description) - $this->spreadsheet->getProperties()->setDescription($value); + $this->spreadsheet->getProperties()->setDescription("$value"); break; case 0x07: // Template // Not supported by PhpSpreadsheet break; case 0x08: // Last Saved By (LastModifiedBy) - $this->spreadsheet->getProperties()->setLastModifiedBy($value); + $this->spreadsheet->getProperties()->setLastModifiedBy("$value"); break; case 0x09: // Revision @@ -1518,7 +1540,7 @@ private function readSummaryInformation() /** * Read additional document summary information. */ - private function readDocumentSummaryInformation() + private function readDocumentSummaryInformation(): void { if (!isset($this->documentSummaryInformation)) { return; @@ -1598,11 +1620,11 @@ private function readDocumentSummaryInformation() switch ($id) { case 0x01: // Code Page - $codePage = CodePage::numberToName($value); + $codePage = CodePage::numberToName((int) $value); break; case 0x02: // Category - $this->spreadsheet->getProperties()->setCategory($value); + $this->spreadsheet->getProperties()->setCategory("$value"); break; case 0x03: // Presentation Target @@ -1639,11 +1661,11 @@ private function readDocumentSummaryInformation() // Not supported by PhpSpreadsheet break; case 0x0E: // Manager - $this->spreadsheet->getProperties()->setManager($value); + $this->spreadsheet->getProperties()->setManager("$value"); break; case 0x0F: // Company - $this->spreadsheet->getProperties()->setCompany($value); + $this->spreadsheet->getProperties()->setCompany("$value"); break; case 0x10: // Links up-to-date @@ -1656,7 +1678,7 @@ private function readDocumentSummaryInformation() /** * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. */ - private function readDefault() + private function readDefault(): void { $length = self::getUInt2d($this->data, $this->pos + 2); @@ -1668,7 +1690,7 @@ private function readDefault() * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. */ - private function readNote() + private function readNote(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -1698,7 +1720,8 @@ private function readNote() // max 2048 bytes will probably throw a wobbly. $row = self::getUInt2d($recordData, 0); $extension = true; - $cellAddress = array_pop(array_keys($this->phpSheet->getComments())); + $arrayKeys = array_keys($this->phpSheet->getComments()); + $cellAddress = array_pop($arrayKeys); } $cellAddress = str_replace('$', '', $cellAddress); @@ -1721,7 +1744,7 @@ private function readNote() /** * The TEXT Object record contains the text associated with a cell annotation. */ - private function readTextObject() + private function readTextObject(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -1768,7 +1791,7 @@ private function readTextObject() /** * Read BOF. */ - private function readBof() + private function readBof(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = substr($this->data, $this->pos + 4, $length); @@ -1819,7 +1842,7 @@ private function readBof() * are based on the source of Spreadsheet-ParseExcel: * https://metacpan.org/release/Spreadsheet-ParseExcel */ - private function readFilepass() + private function readFilepass(): void { $length = self::getUInt2d($this->data, $this->pos + 2); @@ -1969,7 +1992,7 @@ private function verifyPassword($password, $docid, $salt_data, $hashedsalt_data, * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readCodepage() + private function readCodepage(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -1995,7 +2018,7 @@ private function readCodepage() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readDateMode() + private function readDateMode(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2013,7 +2036,7 @@ private function readDateMode() /** * Read a FONT record. */ - private function readFont() + private function readFont(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2058,39 +2081,11 @@ private function readFont() // offset: 8; size: 2; escapement type $escapement = self::getUInt2d($recordData, 8); - switch ($escapement) { - case 0x0001: - $objFont->setSuperscript(true); - - break; - case 0x0002: - $objFont->setSubscript(true); - - break; - } + CellFont::escapement($objFont, $escapement); // offset: 10; size: 1; underline type $underlineType = ord($recordData[10]); - switch ($underlineType) { - case 0x00: - break; // no underline - case 0x01: - $objFont->setUnderline(Font::UNDERLINE_SINGLE); - - break; - case 0x02: - $objFont->setUnderline(Font::UNDERLINE_DOUBLE); - - break; - case 0x21: - $objFont->setUnderline(Font::UNDERLINE_SINGLEACCOUNTING); - - break; - case 0x22: - $objFont->setUnderline(Font::UNDERLINE_DOUBLEACCOUNTING); - - break; - } + CellFont::underline($objFont, $underlineType); // offset: 11; size: 1; font family // offset: 12; size: 1; character set @@ -2121,7 +2116,7 @@ private function readFont() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readFormat() + private function readFormat(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2140,6 +2135,10 @@ private function readFormat() } $formatString = $string['value']; + // Apache Open Office sets wrong case writing to xls - issue 2239 + if ($formatString === 'GENERAL') { + $formatString = NumberFormat::FORMAT_GENERAL; + } $this->formats[$indexCode] = $formatString; } } @@ -2158,7 +2157,7 @@ private function readFormat() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readXf() + private function readXf(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2189,7 +2188,7 @@ private function readXf() $numberFormat = ['formatCode' => $code]; } else { // we set the general format code - $numberFormat = ['formatCode' => 'General']; + $numberFormat = ['formatCode' => NumberFormat::FORMAT_GENERAL]; } $objStyle->getNumberFormat()->setFormatCode($numberFormat['formatCode']); @@ -2210,68 +2209,15 @@ private function readXf() // offset: 6; size: 1; Alignment and text break // bit 2-0, mask 0x07; horizontal alignment $horAlign = (0x07 & ord($recordData[6])) >> 0; - switch ($horAlign) { - case 0: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_GENERAL); - - break; - case 1: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT); - - break; - case 2: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER); - - break; - case 3: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT); + Xls\Style\CellAlignment::horizontal($objStyle->getAlignment(), $horAlign); - break; - case 4: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_FILL); - - break; - case 5: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_JUSTIFY); - - break; - case 6: - $objStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER_CONTINUOUS); - - break; - } // bit 3, mask 0x08; wrap text $wrapText = (0x08 & ord($recordData[6])) >> 3; - switch ($wrapText) { - case 0: - $objStyle->getAlignment()->setWrapText(false); + Xls\Style\CellAlignment::wrap($objStyle->getAlignment(), $wrapText); - break; - case 1: - $objStyle->getAlignment()->setWrapText(true); - - break; - } // bit 6-4, mask 0x70; vertical alignment $vertAlign = (0x70 & ord($recordData[6])) >> 4; - switch ($vertAlign) { - case 0: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_TOP); - - break; - case 1: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_CENTER); - - break; - case 2: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_BOTTOM); - - break; - case 3: - $objStyle->getAlignment()->setVertical(Alignment::VERTICAL_JUSTIFY); - - break; - } + Xls\Style\CellAlignment::vertical($objStyle->getAlignment(), $vertAlign); if ($this->version == self::XLS_BIFF8) { // offset: 7; size: 1; XF_ROTATION: Text rotation angle @@ -2281,8 +2227,8 @@ private function readXf() $rotation = $angle; } elseif ($angle <= 180) { $rotation = 90 - $angle; - } elseif ($angle == 255) { - $rotation = -165; + } elseif ($angle == Alignment::TEXTROTATION_STACK_EXCEL) { + $rotation = Alignment::TEXTROTATION_STACK_PHPSPREADSHEET; } $objStyle->getAlignment()->setTextRotation($rotation); @@ -2384,7 +2330,7 @@ private function readXf() break; case 1: - $objStyle->getAlignment()->setTextRotation(-165); + $objStyle->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET); break; case 2: @@ -2455,7 +2401,7 @@ private function readXf() } } - private function readXfExt() + private function readXfExt(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2504,7 +2450,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getStartColor()->setRGB($rgb); - unset($fill->startcolorIndex); // normal color index does not apply, discard + $fill->startcolorIndex = null; // normal color index does not apply, discard } } @@ -2520,7 +2466,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $fill = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); $fill->getEndColor()->setRGB($rgb); - unset($fill->endcolorIndex); // normal color index does not apply, discard + $fill->endcolorIndex = null; // normal color index does not apply, discard } } @@ -2536,7 +2482,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $top = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop(); $top->getColor()->setRGB($rgb); - unset($top->colorIndex); // normal color index does not apply, discard + $top->colorIndex = null; // normal color index does not apply, discard } } @@ -2552,7 +2498,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $bottom = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom(); $bottom->getColor()->setRGB($rgb); - unset($bottom->colorIndex); // normal color index does not apply, discard + $bottom->colorIndex = null; // normal color index does not apply, discard } } @@ -2568,7 +2514,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $left = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft(); $left->getColor()->setRGB($rgb); - unset($left->colorIndex); // normal color index does not apply, discard + $left->colorIndex = null; // normal color index does not apply, discard } } @@ -2584,7 +2530,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $right = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight(); $right->getColor()->setRGB($rgb); - unset($right->colorIndex); // normal color index does not apply, discard + $right->colorIndex = null; // normal color index does not apply, discard } } @@ -2600,7 +2546,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $diagonal = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal(); $diagonal->getColor()->setRGB($rgb); - unset($diagonal->colorIndex); // normal color index does not apply, discard + $diagonal->colorIndex = null; // normal color index does not apply, discard } } @@ -2616,7 +2562,7 @@ private function readXfExt() if (isset($this->mapCellXfIndex[$ixfe])) { $font = $this->spreadsheet->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont(); $font->getColor()->setRGB($rgb); - unset($font->colorIndex); // normal color index does not apply, discard + $font->colorIndex = null; // normal color index does not apply, discard } } @@ -2631,7 +2577,7 @@ private function readXfExt() /** * Read STYLE record. */ - private function readStyle() + private function readStyle(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2668,7 +2614,7 @@ private function readStyle() /** * Read PALETTE record. */ - private function readPalette() + private function readPalette(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2700,7 +2646,7 @@ private function readPalette() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readSheet() + private function readSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2736,6 +2682,7 @@ private function readSheet() $sheetType = ord($recordData[5]); // offset: 6; size: var; sheet name + $rec_name = null; if ($this->version == self::XLS_BIFF8) { $string = self::readUnicodeStringShort(substr($recordData, 6)); $rec_name = $string['value']; @@ -2755,7 +2702,7 @@ private function readSheet() /** * Read EXTERNALBOOK record. */ - private function readExternalBook() + private function readExternalBook(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2817,7 +2764,7 @@ private function readExternalBook() /** * Read EXTERNNAME record. */ - private function readExternName() + private function readExternName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2851,7 +2798,7 @@ private function readExternName() /** * Read EXTERNSHEET record. */ - private function readExternSheet() + private function readExternSheet(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2887,7 +2834,7 @@ private function readExternSheet() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readDefinedName() + private function readDefinedName(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -2941,7 +2888,7 @@ private function readDefinedName() /** * Read MSODRAWINGGROUP record. */ - private function readMsoDrawingGroup() + private function readMsoDrawingGroup(): void { $length = self::getUInt2d($this->data, $this->pos + 2); @@ -2963,11 +2910,14 @@ private function readMsoDrawingGroup() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readSst() + private function readSst(): void { // offset within (spliced) record data $pos = 0; + // Limit global SST position, further control for bad SST Length in BIFF8 data + $limitposSST = 0; + // get spliced record data $splicedRecordData = $this->getSplicedRecordData(); @@ -2981,8 +2931,17 @@ private function readSst() $nm = self::getInt4d($recordData, 4); $pos += 4; + // look up limit position + foreach ($spliceOffsets as $spliceOffset) { + // it can happen that the string is empty, therefore we need + // <= and not just < + if ($pos <= $spliceOffset) { + $limitposSST = $spliceOffset; + } + } + // loop through the Unicode strings (16-bit length) - for ($i = 0; $i < $nm; ++$i) { + for ($i = 0; $i < $nm && $pos < $limitposSST; ++$i) { // number of characters in the Unicode string $numChars = self::getUInt2d($recordData, $pos); $pos += 2; @@ -3000,12 +2959,14 @@ private function readSst() // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text $hasRichText = (($optionFlags & 0x08) != 0); + $formattingRuns = 0; if ($hasRichText) { // number of Rich-Text formatting runs $formattingRuns = self::getUInt2d($recordData, $pos); $pos += 2; } + $extendedRunLength = 0; if ($hasAsian) { // size of Asian phonetic setting $extendedRunLength = self::getInt4d($recordData, $pos); @@ -3015,7 +2976,8 @@ private function readSst() // expected byte length of character array if not split $len = ($isCompressed) ? $numChars : $numChars * 2; - // look up limit position + // look up limit position - Check it again to be sure that no error occurs when parsing SST structure + $limitpos = null; foreach ($spliceOffsets as $spliceOffset) { // it can happen that the string is empty, therefore we need // <= and not just < @@ -3144,7 +3106,7 @@ private function readSst() /** * Read PRINTGRIDLINES record. */ - private function readPrintGridlines() + private function readPrintGridlines(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3162,7 +3124,7 @@ private function readPrintGridlines() /** * Read DEFAULTROWHEIGHT record. */ - private function readDefaultRowHeight() + private function readDefaultRowHeight(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3179,7 +3141,7 @@ private function readDefaultRowHeight() /** * Read SHEETPR record. */ - private function readSheetPr() + private function readSheetPr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3205,7 +3167,7 @@ private function readSheetPr() /** * Read HORIZONTALPAGEBREAKS record. */ - private function readHorizontalPageBreaks() + private function readHorizontalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3232,7 +3194,7 @@ private function readHorizontalPageBreaks() /** * Read VERTICALPAGEBREAKS record. */ - private function readVerticalPageBreaks() + private function readVerticalPageBreaks(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3259,7 +3221,7 @@ private function readVerticalPageBreaks() /** * Read HEADER record. */ - private function readHeader() + private function readHeader(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3286,7 +3248,7 @@ private function readHeader() /** * Read FOOTER record. */ - private function readFooter() + private function readFooter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3312,7 +3274,7 @@ private function readFooter() /** * Read HCENTER record. */ - private function readHcenter() + private function readHcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3331,7 +3293,7 @@ private function readHcenter() /** * Read VCENTER record. */ - private function readVcenter() + private function readVcenter(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3350,7 +3312,7 @@ private function readVcenter() /** * Read LEFTMARGIN record. */ - private function readLeftMargin() + private function readLeftMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3367,7 +3329,7 @@ private function readLeftMargin() /** * Read RIGHTMARGIN record. */ - private function readRightMargin() + private function readRightMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3384,7 +3346,7 @@ private function readRightMargin() /** * Read TOPMARGIN record. */ - private function readTopMargin() + private function readTopMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3401,7 +3363,7 @@ private function readTopMargin() /** * Read BOTTOMMARGIN record. */ - private function readBottomMargin() + private function readBottomMargin(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3418,7 +3380,7 @@ private function readBottomMargin() /** * Read PAGESETUP record. */ - private function readPageSetup() + private function readPageSetup(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3441,6 +3403,9 @@ private function readPageSetup() // offset: 10; size: 2; option flags + // bit: 0; mask: 0x0001; 0=down then over, 1=over then down + $isOverThenDown = (0x0001 & self::getUInt2d($recordData, 10)); + // bit: 1; mask: 0x0002; 0=landscape, 1=portrait $isPortrait = (0x0002 & self::getUInt2d($recordData, 10)) >> 1; @@ -3450,16 +3415,8 @@ private function readPageSetup() if (!$isNotInit) { $this->phpSheet->getPageSetup()->setPaperSize($paperSize); - switch ($isPortrait) { - case 0: - $this->phpSheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE); - - break; - case 1: - $this->phpSheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT); - - break; - } + $this->phpSheet->getPageSetup()->setPageOrder(((bool) $isOverThenDown) ? PageSetup::PAGEORDER_OVER_THEN_DOWN : PageSetup::PAGEORDER_DOWN_THEN_OVER); + $this->phpSheet->getPageSetup()->setOrientation(((bool) $isPortrait) ? PageSetup::ORIENTATION_PORTRAIT : PageSetup::ORIENTATION_LANDSCAPE); $this->phpSheet->getPageSetup()->setScale($scale, false); $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages); @@ -3481,7 +3438,7 @@ private function readPageSetup() * PROTECT - Sheet protection (BIFF2 through BIFF8) * if this record is omitted, then it also means no sheet protection. */ - private function readProtect() + private function readProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3503,7 +3460,7 @@ private function readProtect() /** * SCENPROTECT. */ - private function readScenProtect() + private function readScenProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3526,7 +3483,7 @@ private function readScenProtect() /** * OBJECTPROTECT. */ - private function readObjectProtect() + private function readObjectProtect(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3549,7 +3506,7 @@ private function readObjectProtect() /** * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8). */ - private function readPassword() + private function readPassword(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3567,7 +3524,7 @@ private function readPassword() /** * Read DEFCOLWIDTH record. */ - private function readDefColWidth() + private function readDefColWidth(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3585,7 +3542,7 @@ private function readDefColWidth() /** * Read COLINFO record. */ - private function readColInfo() + private function readColInfo(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3614,7 +3571,7 @@ private function readColInfo() $level = (0x0700 & self::getUInt2d($recordData, 8)) >> 8; // bit: 12; mask: 0x1000; 1 = collapsed - $isCollapsed = (0x1000 & self::getUInt2d($recordData, 8)) >> 12; + $isCollapsed = (bool) ((0x1000 & self::getUInt2d($recordData, 8)) >> 12); // offset: 10; size: 2; not used @@ -3628,7 +3585,9 @@ private function readColInfo() $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden); $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level); $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed); - $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]); + if (isset($this->mapCellXfIndex[$xfIndex])) { + $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } } } } @@ -3643,7 +3602,7 @@ private function readColInfo() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readRow() + private function readRow(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3682,7 +3641,7 @@ private function readRow() $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed - $isCollapsed = (0x00000010 & self::getInt4d($recordData, 12)) >> 4; + $isCollapsed = (bool) ((0x00000010 & self::getInt4d($recordData, 12)) >> 4); $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); // bit: 5; mask: 0x00000020; 1 = row is hidden @@ -3712,7 +3671,7 @@ private function readRow() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readRk() + private function readRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3737,7 +3696,7 @@ private function readRk() $numValue = self::getIEEE754($rknum); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style information $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -3756,7 +3715,7 @@ private function readRk() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readLabelSst() + private function readLabelSst(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3803,10 +3762,13 @@ private function readLabelSst() if ($fmtRuns[$i - 1]['fontIndex'] < 4) { $fontIndex = $fmtRuns[$i - 1]['fontIndex']; } else { - // this has to do with that index 4 is omitted in all BIFF versions for some strange reason + // this has to do with that index 4 is omitted in all BIFF versions for some stra nge reason // check the OpenOffice documentation of the FONT record $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1; } + if (array_key_exists($fontIndex, $this->objFonts) === false) { + $fontIndex = count($this->objFonts) - 1; + } $textRun->setFont(clone $this->objFonts[$fontIndex]); } } @@ -3840,7 +3802,7 @@ private function readLabelSst() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readMulRk() + private function readMulRk(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3872,7 +3834,7 @@ private function readMulRk() // offset: var; size: 4; RK value $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -3893,7 +3855,7 @@ private function readMulRk() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readNumber() + private function readNumber(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3916,7 +3878,7 @@ private function readNumber() $numValue = self::extractNumber(substr($recordData, 6, 8)); $cell = $this->phpSheet->getCell($columnString . ($row + 1)); - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -3934,7 +3896,7 @@ private function readNumber() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readFormula() + private function readFormula(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -3999,21 +3961,27 @@ private function readFormula() // read STRING record $value = $this->readString(); - } elseif ((ord($recordData[6]) == 1) + } elseif ( + (ord($recordData[6]) == 1) && (ord($recordData[12]) == 255) - && (ord($recordData[13]) == 255)) { + && (ord($recordData[13]) == 255) + ) { // Boolean formula. Result is in +2; 0=false, 1=true $dataType = DataType::TYPE_BOOL; $value = (bool) ord($recordData[8]); - } elseif ((ord($recordData[6]) == 2) + } elseif ( + (ord($recordData[6]) == 2) && (ord($recordData[12]) == 255) - && (ord($recordData[13]) == 255)) { + && (ord($recordData[13]) == 255) + ) { // Error formula. Error code is in +2 $dataType = DataType::TYPE_ERROR; $value = Xls\ErrorCode::lookup(ord($recordData[8])); - } elseif ((ord($recordData[6]) == 3) + } elseif ( + (ord($recordData[6]) == 3) && (ord($recordData[12]) == 255) - && (ord($recordData[13]) == 255)) { + && (ord($recordData[13]) == 255) + ) { // Formula result is a null string $dataType = DataType::TYPE_NULL; $value = ''; @@ -4024,7 +3992,7 @@ private function readFormula() } $cell = $this->phpSheet->getCell($columnString . ($row + 1)); - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -4060,7 +4028,7 @@ private function readFormula() * which usually contains relative references. * These will be used to construct the formula in each shared formula part after the sheet is read. */ - private function readSharedFmla() + private function readSharedFmla(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4118,7 +4086,7 @@ private function readString() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readBoolErr() + private function readBoolErr(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4162,7 +4130,7 @@ private function readBoolErr() break; } - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -4177,7 +4145,7 @@ private function readBoolErr() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readMulBlank() + private function readMulBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4200,7 +4168,9 @@ private function readMulBlank() // Read cell? if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { $xfIndex = self::getUInt2d($recordData, 4 + 2 * $i); - $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); + if (isset($this->mapCellXfIndex[$xfIndex])) { + $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } } } } @@ -4218,7 +4188,7 @@ private function readMulBlank() * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readLabel() + private function readLabel(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4251,7 +4221,7 @@ private function readLabel() $cell = $this->phpSheet->getCell($columnString . ($row + 1)); $cell->setValueExplicit($value, DataType::TYPE_STRING); - if (!$this->readDataOnly) { + if (!$this->readDataOnly && isset($this->mapCellXfIndex[$xfIndex])) { // add cell style $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); } @@ -4262,7 +4232,7 @@ private function readLabel() /** * Read BLANK record. */ - private function readBlank() + private function readBlank(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4283,7 +4253,7 @@ private function readBlank() $xfIndex = self::getUInt2d($recordData, 4); // add style information - if (!$this->readDataOnly && $this->readEmptyCells) { + if (!$this->readDataOnly && $this->readEmptyCells && isset($this->mapCellXfIndex[$xfIndex])) { $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); } } @@ -4292,7 +4262,7 @@ private function readBlank() /** * Read MSODRAWING record. */ - private function readMsoDrawing() + private function readMsoDrawing(): void { $length = self::getUInt2d($this->data, $this->pos + 2); @@ -4306,7 +4276,7 @@ private function readMsoDrawing() /** * Read OBJ record. */ - private function readObj() + private function readObj(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4346,7 +4316,7 @@ private function readObj() /** * Read WINDOW2 record. */ - private function readWindow2() + private function readWindow2(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4362,16 +4332,29 @@ private function readWindow2() // offset: 4; size: 2; index to first visible colum $firstVisibleColumn = self::getUInt2d($recordData, 4); + $zoomscaleInPageBreakPreview = 0; + $zoomscaleInNormalView = 0; if ($this->version === self::XLS_BIFF8) { // offset: 8; size: 2; not used // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%) // offset: 14; size: 4; not used - $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10); + if (!isset($recordData[10])) { + $zoomscaleInPageBreakPreview = 0; + } else { + $zoomscaleInPageBreakPreview = self::getUInt2d($recordData, 10); + } + if ($zoomscaleInPageBreakPreview === 0) { $zoomscaleInPageBreakPreview = 60; } - $zoomscaleInNormalView = self::getUInt2d($recordData, 12); + + if (!isset($recordData[12])) { + $zoomscaleInNormalView = 0; + } else { + $zoomscaleInNormalView = self::getUInt2d($recordData, 12); + } + if ($zoomscaleInNormalView === 0) { $zoomscaleInNormalView = 100; } @@ -4417,7 +4400,7 @@ private function readWindow2() /** * Read PLV Record(Created by Excel2007 or upper). */ - private function readPageLayoutView() + private function readPageLayoutView(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4454,7 +4437,7 @@ private function readPageLayoutView() /** * Read SCL record. */ - private function readScl() + private function readScl(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4475,7 +4458,7 @@ private function readScl() /** * Read PANE record. */ - private function readPane() + private function readPane(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4509,7 +4492,7 @@ private function readPane() /** * Read SELECTION record. There is one such record for each pane in the sheet. */ - private function readSelection() + private function readSelection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4586,7 +4569,7 @@ private function includeCellRangeFiltered($cellRangeAddress) * -- "OpenOffice.org's Documentation of the Microsoft * Excel File Format" */ - private function readMergedCells() + private function readMergedCells(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4597,8 +4580,10 @@ private function readMergedCells() if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($recordData); foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) { - if ((strpos($cellRangeAddress, ':') !== false) && - ($this->includeCellRangeFiltered($cellRangeAddress))) { + if ( + (strpos($cellRangeAddress, ':') !== false) && + ($this->includeCellRangeFiltered($cellRangeAddress)) + ) { $this->phpSheet->mergeCells($cellRangeAddress); } } @@ -4608,7 +4593,7 @@ private function readMergedCells() /** * Read HYPERLINK record. */ - private function readHyperLink() + private function readHyperLink(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4781,7 +4766,7 @@ private function readHyperLink() /** * Read DATAVALIDATIONS record. */ - private function readDataValidations() + private function readDataValidations(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4793,7 +4778,7 @@ private function readDataValidations() /** * Read DATAVALIDATION record. */ - private function readDataValidation() + private function readDataValidation(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -4810,57 +4795,11 @@ private function readDataValidation() // bit: 0-3; mask: 0x0000000F; type $type = (0x0000000F & $options) >> 0; - switch ($type) { - case 0x00: - $type = DataValidation::TYPE_NONE; - - break; - case 0x01: - $type = DataValidation::TYPE_WHOLE; - - break; - case 0x02: - $type = DataValidation::TYPE_DECIMAL; - - break; - case 0x03: - $type = DataValidation::TYPE_LIST; - - break; - case 0x04: - $type = DataValidation::TYPE_DATE; - - break; - case 0x05: - $type = DataValidation::TYPE_TIME; - - break; - case 0x06: - $type = DataValidation::TYPE_TEXTLENGTH; - - break; - case 0x07: - $type = DataValidation::TYPE_CUSTOM; - - break; - } + $type = Xls\DataValidationHelper::type($type); // bit: 4-6; mask: 0x00000070; error type $errorStyle = (0x00000070 & $options) >> 4; - switch ($errorStyle) { - case 0x00: - $errorStyle = DataValidation::STYLE_STOP; - - break; - case 0x01: - $errorStyle = DataValidation::STYLE_WARNING; - - break; - case 0x02: - $errorStyle = DataValidation::STYLE_INFORMATION; - - break; - } + $errorStyle = Xls\DataValidationHelper::errorStyle($errorStyle); // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list) // I have only seen cases where this is 1 @@ -4880,39 +4819,10 @@ private function readDataValidation() // bit: 20-23; mask: 0x00F00000; condition operator $operator = (0x00F00000 & $options) >> 20; - switch ($operator) { - case 0x00: - $operator = DataValidation::OPERATOR_BETWEEN; - - break; - case 0x01: - $operator = DataValidation::OPERATOR_NOTBETWEEN; - - break; - case 0x02: - $operator = DataValidation::OPERATOR_EQUAL; - - break; - case 0x03: - $operator = DataValidation::OPERATOR_NOTEQUAL; - - break; - case 0x04: - $operator = DataValidation::OPERATOR_GREATERTHAN; - - break; - case 0x05: - $operator = DataValidation::OPERATOR_LESSTHAN; + $operator = Xls\DataValidationHelper::operator($operator); - break; - case 0x06: - $operator = DataValidation::OPERATOR_GREATERTHANOREQUAL; - - break; - case 0x07: - $operator = DataValidation::OPERATOR_LESSTHANOREQUAL; - - break; + if ($type === null || $errorStyle === null || $operator === null) { + return; } // offset: 4; size: var; title of the prompt box @@ -4946,6 +4856,7 @@ private function readDataValidation() // offset: var; size: $sz1; formula data for first condition (without size field) $formula1 = substr($recordData, $offset, $sz1); $formula1 = pack('v', $sz1) . $formula1; // prepend the length + try { $formula1 = $this->getFormulaFromStructure($formula1); @@ -4968,6 +4879,7 @@ private function readDataValidation() // offset: var; size: $sz2; formula data for second condition (without size field) $formula2 = substr($recordData, $offset, $sz2); $formula2 = pack('v', $sz2) . $formula2; // prepend the length + try { $formula2 = $this->getFormulaFromStructure($formula2); } catch (PhpSpreadsheetException $e) { @@ -5003,7 +4915,7 @@ private function readDataValidation() /** * Read SHEETLAYOUT record. Stores sheet tab color information. */ - private function readSheetLayout() + private function readSheetLayout(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -5043,7 +4955,7 @@ private function readSheetLayout() /** * Read SHEETPROTECTION record (FEATHEADR). */ - private function readSheetProtection() + private function readSheetProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -5143,7 +5055,7 @@ private function readSheetProtection() * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, * where it is referred to as FEAT record. */ - private function readRangeProtection() + private function readRangeProtection(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -5205,7 +5117,7 @@ private function readRangeProtection() * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. * In this case, we must treat the CONTINUE record as a MSODRAWING record. */ - private function readContinue() + private function readContinue(): void { $length = self::getUInt2d($this->data, $this->pos + 2); $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); @@ -5325,7 +5237,7 @@ private function getFormulaFromData($formulaData, $additionalData = '', $baseCel // start parsing the formula data $tokens = []; - while (strlen($formulaData) > 0 and $token = $this->getNextToken($formulaData, $baseCell)) { + while (strlen($formulaData) > 0 && $token = $this->getNextToken($formulaData, $baseCell)) { $tokens[] = $token; $formulaData = substr($formulaData, $token['size']); } @@ -5516,8 +5428,6 @@ private function createFormulaFromTokens($tokens, $additionalData) * @param string $formulaData Formula data * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas * - * @throws Exception - * * @return array */ private function getNextToken($formulaData, $baseCell = 'A1') @@ -5767,6 +5677,7 @@ private function getNextToken($formulaData, $baseCell = 'A1') $size = 9; $data = self::extractNumber(substr($formulaData, 1)); $data = str_replace(',', '.', (string) $data); // in case non-English locale + break; case 0x20: // array constant case 0x40: @@ -6970,7 +6881,7 @@ private function getNextToken($formulaData, $baseCell = 'A1') // offset: 1; size: 2; one-based index to definedname record $definedNameIndex = self::getUInt2d($formulaData, 1) - 1; // offset: 2; size: 2; not used - $data = $this->definedname[$definedNameIndex]['name']; + $data = $this->definedname[$definedNameIndex]['name'] ?? ''; break; case 0x24: // single cell reference e.g. A5 @@ -7046,7 +6957,7 @@ private function getNextToken($formulaData, $baseCell = 'A1') // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record $index = self::getUInt2d($formulaData, 3); // assume index is to EXTERNNAME record - $data = $this->externalNames[$index - 1]['name']; + $data = $this->externalNames[$index - 1]['name'] ?? ''; // offset: 5; size: 2; not used break; case 0x3A: // 3d reference to cell @@ -7145,6 +7056,7 @@ private function readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1') { [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; + $baseRow = (int) $baseRow; // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) $rowIndex = self::getUInt2d($cellAddressStructure, 0); @@ -7186,8 +7098,6 @@ private function readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1') * * @param string $subData * - * @throws Exception - * * @return string */ private function readBIFF5CellRangeAddressFixed($subData) @@ -7213,7 +7123,7 @@ private function readBIFF5CellRangeAddressFixed($subData) $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); - if ($fr == $lr and $fc == $lc) { + if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } @@ -7227,8 +7137,6 @@ private function readBIFF5CellRangeAddressFixed($subData) * * @param string $subData * - * @throws Exception - * * @return string */ private function readBIFF8CellRangeAddressFixed($subData) @@ -7254,7 +7162,7 @@ private function readBIFF8CellRangeAddressFixed($subData) $fc = Coordinate::stringFromColumnIndex($fc + 1); $lc = Coordinate::stringFromColumnIndex($lc + 1); - if ($fr == $lr and $fc == $lc) { + if ($fr == $lr && $fc == $lc) { return "$fc$fr"; } @@ -7326,8 +7234,8 @@ private function readBIFF8CellRangeAddress($subData) */ private function readBIFF8CellRangeAddressB($subData, $baseCell = 'A1') { - [$baseCol, $baseRow] = Coordinate::coordinateFromString($baseCell); - $baseCol = Coordinate::columnIndexFromString($baseCol) - 1; + [$baseCol, $baseRow] = Coordinate::indexesFromString($baseCell); + $baseCol = $baseCol - 1; // TODO: if cell range is just a single cell, should this funciton // not just return e.g. 'A1' and not 'A1:A1' ? @@ -7465,8 +7373,6 @@ private function readBIFF5CellRangeAddressList($subData) * * @param int $index * - * @throws Exception - * * @return false|string */ private function readSheetRangeByRefIndex($index) @@ -7477,7 +7383,7 @@ private function readSheetRangeByRefIndex($index) switch ($type) { case 'internal': // check if we have a deleted 3d reference - if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF or $this->ref[$index]['lastSheetIndex'] == 0xFFFF) { + if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF || $this->ref[$index]['lastSheetIndex'] == 0xFFFF) { throw new Exception('Deleted sheet reference'); } @@ -7605,6 +7511,8 @@ private static function readBIFF8Constant($valueData) $size = 9; break; + default: + throw new PhpSpreadsheetException('Unsupported BIFF8 constant'); } return [ @@ -7702,7 +7610,7 @@ private static function readUnicodeStringShort($subData) $string = self::readUnicodeString(substr($subData, 1), $characterCount); // add 1 for the string length - $string['size'] += 1; + ++$string['size']; return $string; } @@ -7795,13 +7703,13 @@ private static function extractNumber($data) $mantissa = (0x100000 | ($rknumhigh & 0x000fffff)); $mantissalow1 = ($rknumlow & 0x80000000) >> 31; $mantissalow2 = ($rknumlow & 0x7fffffff); - $value = $mantissa / pow(2, (20 - $exp)); + $value = $mantissa / 2 ** (20 - $exp); if ($mantissalow1 != 0) { - $value += 1 / pow(2, (21 - $exp)); + $value += 1 / 2 ** (21 - $exp); } - $value += $mantissalow2 / pow(2, (52 - $exp)); + $value += $mantissalow2 / 2 ** (52 - $exp); if ($sign) { $value *= -1; } @@ -7827,7 +7735,7 @@ private static function getIEEE754($rknum) $sign = ($rknum & 0x80000000) >> 31; $exp = ($rknum & 0x7ff00000) >> 20; $mantissa = (0x100000 | ($rknum & 0x000ffffc)); - $value = $mantissa / pow(2, (20 - ($exp - 1023))); + $value = $mantissa / 2 ** (20 - ($exp - 1023)); if ($sign) { $value = -1 * $value; } @@ -7944,4 +7852,243 @@ private function parseRichText($is) return $value; } + + /** + * Phpstan 1.4.4 complains that this property is never read. + * So, we might be able to get rid of it altogether. + * For now, however, this function makes it readable, + * which satisfies Phpstan. + * + * @codeCoverageIgnore + */ + public function getMapCellStyleXfIndex(): array + { + return $this->mapCellStyleXfIndex; + } + + private function readCFHeader(): array + { + $length = self::getUInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer forward to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return []; + } + + // offset: 0; size: 2; Rule Count +// $ruleCount = self::getUInt2d($recordData, 0); + + // offset: var; size: var; cell range address list with + $cellRangeAddressList = ($this->version == self::XLS_BIFF8) + ? $this->readBIFF8CellRangeAddressList(substr($recordData, 12)) + : $this->readBIFF5CellRangeAddressList(substr($recordData, 12)); + $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; + + return $cellRangeAddresses; + } + + private function readCFRule(array $cellRangeAddresses): void + { + $length = self::getUInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer forward to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 2; Options + $cfRule = self::getUInt2d($recordData, 0); + + // bit: 8-15; mask: 0x00FF; type + $type = (0x00FF & $cfRule) >> 0; + $type = ConditionalFormatting::type($type); + + // bit: 0-7; mask: 0xFF00; type + $operator = (0xFF00 & $cfRule) >> 8; + $operator = ConditionalFormatting::operator($operator); + + if ($type === null || $operator === null) { + return; + } + + // offset: 2; size: 2; Size1 + $size1 = self::getUInt2d($recordData, 2); + + // offset: 4; size: 2; Size2 + $size2 = self::getUInt2d($recordData, 4); + + // offset: 6; size: 4; Options + $options = self::getInt4d($recordData, 6); + + $style = new Style(); + $this->getCFStyleOptions($options, $style); + + $hasFontRecord = (bool) ((0x04000000 & $options) >> 26); + $hasAlignmentRecord = (bool) ((0x08000000 & $options) >> 27); + $hasBorderRecord = (bool) ((0x10000000 & $options) >> 28); + $hasFillRecord = (bool) ((0x20000000 & $options) >> 29); + $hasProtectionRecord = (bool) ((0x40000000 & $options) >> 30); + + $offset = 12; + + if ($hasFontRecord === true) { + $fontStyle = substr($recordData, $offset, 118); + $this->getCFFontStyle($fontStyle, $style); + $offset += 118; + } + + if ($hasAlignmentRecord === true) { + $alignmentStyle = substr($recordData, $offset, 8); + $this->getCFAlignmentStyle($alignmentStyle, $style); + $offset += 8; + } + + if ($hasBorderRecord === true) { + $borderStyle = substr($recordData, $offset, 8); + $this->getCFBorderStyle($borderStyle, $style); + $offset += 8; + } + + if ($hasFillRecord === true) { + $fillStyle = substr($recordData, $offset, 4); + $this->getCFFillStyle($fillStyle, $style); + $offset += 4; + } + + if ($hasProtectionRecord === true) { + $protectionStyle = substr($recordData, $offset, 4); + $this->getCFProtectionStyle($protectionStyle, $style); + $offset += 2; + } + + $formula1 = $formula2 = null; + if ($size1 > 0) { + $formula1 = $this->readCFFormula($recordData, $offset, $size1); + if ($formula1 === null) { + return; + } + + $offset += $size1; + } + + if ($size2 > 0) { + $formula2 = $this->readCFFormula($recordData, $offset, $size2); + if ($formula2 === null) { + return; + } + + $offset += $size2; + } + + $this->setCFRules($cellRangeAddresses, $type, $operator, $formula1, $formula2, $style); + } + + private function getCFStyleOptions(int $options, Style $style): void + { + } + + private function getCFFontStyle(string $options, Style $style): void + { + $fontSize = self::getInt4d($options, 64); + if ($fontSize !== -1) { + $style->getFont()->setSize($fontSize / 20); // Convert twips to points + } + + $bold = self::getUInt2d($options, 72) === 700; // 400 = normal, 700 = bold + $style->getFont()->setBold($bold); + + $color = self::getInt4d($options, 80); + + if ($color !== -1) { + $style->getFont()->getColor()->setRGB(Xls\Color::map($color, $this->palette, $this->version)['rgb']); + } + } + + private function getCFAlignmentStyle(string $options, Style $style): void + { + } + + private function getCFBorderStyle(string $options, Style $style): void + { + } + + private function getCFFillStyle(string $options, Style $style): void + { + $fillPattern = self::getUInt2d($options, 0); + // bit: 10-15; mask: 0xFC00; type + $fillPattern = (0xFC00 & $fillPattern) >> 10; + $fillPattern = FillPattern::lookup($fillPattern); + $fillPattern = $fillPattern === Fill::FILL_NONE ? Fill::FILL_SOLID : $fillPattern; + + if ($fillPattern !== Fill::FILL_NONE) { + $style->getFill()->setFillType($fillPattern); + + $fillColors = self::getUInt2d($options, 2); + + // bit: 0-6; mask: 0x007F; type + $color1 = (0x007F & $fillColors) >> 0; + $style->getFill()->getStartColor()->setRGB(Xls\Color::map($color1, $this->palette, $this->version)['rgb']); + + // bit: 7-13; mask: 0x3F80; type + $color2 = (0x3F80 & $fillColors) >> 7; + $style->getFill()->getEndColor()->setRGB(Xls\Color::map($color2, $this->palette, $this->version)['rgb']); + } + } + + private function getCFProtectionStyle(string $options, Style $style): void + { + } + + /** + * @return null|float|int|string + */ + private function readCFFormula(string $recordData, int $offset, int $size) + { + try { + $formula = substr($recordData, $offset, $size); + $formula = pack('v', $size) . $formula; // prepend the length + + $formula = $this->getFormulaFromStructure($formula); + if (is_numeric($formula)) { + return (strpos($formula, '.') !== false) ? (float) $formula : (int) $formula; + } + + return $formula; + } catch (PhpSpreadsheetException $e) { + } + + return null; + } + + /** + * @param null|float|int|string $formula1 + * @param null|float|int|string $formula2 + */ + private function setCFRules(array $cellRanges, string $type, string $operator, $formula1, $formula2, Style $style): void + { + foreach ($cellRanges as $cellRange) { + $conditional = new Conditional(); + $conditional->setConditionType($type); + $conditional->setOperatorType($operator); + if ($formula1 !== null) { + $conditional->addCondition($formula1); + } + if ($formula2 !== null) { + $conditional->addCondition($formula2); + } + $conditional->setStyle($style); + + $conditionalStyles = $this->phpSheet->getStyle($cellRange)->getConditionalStyles(); + $conditionalStyles[] = $conditional; + + $this->phpSheet->getStyle($cellRange)->setConditionalStyles($conditionalStyles); + $this->phpSheet->getStyle($cellRange)->setConditionalStyles($conditionalStyles); + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php index c45f88c7..06c2d0b9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Color.php @@ -20,7 +20,7 @@ public static function map($color, $palette, $version) if ($color <= 0x07 || $color >= 0x40) { // special built-in color return Color\BuiltIn::lookup($color); - } elseif (isset($palette, $palette[$color - 8])) { + } elseif (isset($palette[$color - 8])) { // palette color, color index 0x08 maps to pallete index 0 return $palette[$color - 8]; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php new file mode 100644 index 00000000..8400efb9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/ConditionalFormatting.php @@ -0,0 +1,49 @@ + + */ + private static $types = [ + 0x01 => Conditional::CONDITION_CELLIS, + 0x02 => Conditional::CONDITION_EXPRESSION, + ]; + + /** + * @var array + */ + private static $operators = [ + 0x00 => Conditional::OPERATOR_NONE, + 0x01 => Conditional::OPERATOR_BETWEEN, + 0x02 => Conditional::OPERATOR_NOTBETWEEN, + 0x03 => Conditional::OPERATOR_EQUAL, + 0x04 => Conditional::OPERATOR_NOTEQUAL, + 0x05 => Conditional::OPERATOR_GREATERTHAN, + 0x06 => Conditional::OPERATOR_LESSTHAN, + 0x07 => Conditional::OPERATOR_GREATERTHANOREQUAL, + 0x08 => Conditional::OPERATOR_LESSTHANOREQUAL, + ]; + + public static function type(int $type): ?string + { + if (isset(self::$types[$type])) { + return self::$types[$type]; + } + + return null; + } + + public static function operator(int $operator): ?string + { + if (isset(self::$operators[$operator])) { + return self::$operators[$operator]; + } + + return null; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/DataValidationHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/DataValidationHelper.php new file mode 100644 index 00000000..02f844e3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/DataValidationHelper.php @@ -0,0 +1,72 @@ + + */ + private static $types = [ + 0x00 => DataValidation::TYPE_NONE, + 0x01 => DataValidation::TYPE_WHOLE, + 0x02 => DataValidation::TYPE_DECIMAL, + 0x03 => DataValidation::TYPE_LIST, + 0x04 => DataValidation::TYPE_DATE, + 0x05 => DataValidation::TYPE_TIME, + 0x06 => DataValidation::TYPE_TEXTLENGTH, + 0x07 => DataValidation::TYPE_CUSTOM, + ]; + + /** + * @var array + */ + private static $errorStyles = [ + 0x00 => DataValidation::STYLE_STOP, + 0x01 => DataValidation::STYLE_WARNING, + 0x02 => DataValidation::STYLE_INFORMATION, + ]; + + /** + * @var array + */ + private static $operators = [ + 0x00 => DataValidation::OPERATOR_BETWEEN, + 0x01 => DataValidation::OPERATOR_NOTBETWEEN, + 0x02 => DataValidation::OPERATOR_EQUAL, + 0x03 => DataValidation::OPERATOR_NOTEQUAL, + 0x04 => DataValidation::OPERATOR_GREATERTHAN, + 0x05 => DataValidation::OPERATOR_LESSTHAN, + 0x06 => DataValidation::OPERATOR_GREATERTHANOREQUAL, + 0x07 => DataValidation::OPERATOR_LESSTHANOREQUAL, + ]; + + public static function type(int $type): ?string + { + if (isset(self::$types[$type])) { + return self::$types[$type]; + } + + return null; + } + + public static function errorStyle(int $errorStyle): ?string + { + if (isset(self::$errorStyles[$errorStyle])) { + return self::$errorStyles[$errorStyle]; + } + + return null; + } + + public static function operator(int $operator): ?string + { + if (isset(self::$operators[$operator])) { + return self::$operators[$operator]; + } + + return null; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php index 858d6bbb..e9c95c88 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Escher.php @@ -71,6 +71,27 @@ public function __construct($object) $this->object = $object; } + private const WHICH_ROUTINE = [ + self::DGGCONTAINER => 'readDggContainer', + self::DGG => 'readDgg', + self::BSTORECONTAINER => 'readBstoreContainer', + self::BSE => 'readBSE', + self::BLIPJPEG => 'readBlipJPEG', + self::BLIPPNG => 'readBlipPNG', + self::OPT => 'readOPT', + self::TERTIARYOPT => 'readTertiaryOPT', + self::SPLITMENUCOLORS => 'readSplitMenuColors', + self::DGCONTAINER => 'readDgContainer', + self::DG => 'readDg', + self::SPGRCONTAINER => 'readSpgrContainer', + self::SPCONTAINER => 'readSpContainer', + self::SPGR => 'readSpgr', + self::SP => 'readSp', + self::CLIENTTEXTBOX => 'readClientTextbox', + self::CLIENTANCHOR => 'readClientAnchor', + self::CLIENTDATA => 'readClientData', + ]; + /** * Load Escher stream data. May be a partial Escher stream. * @@ -91,84 +112,9 @@ public function load($data) while ($this->pos < $this->dataSize) { // offset: 2; size: 2: Record Type $fbt = Xls::getUInt2d($this->data, $this->pos + 2); - - switch ($fbt) { - case self::DGGCONTAINER: - $this->readDggContainer(); - - break; - case self::DGG: - $this->readDgg(); - - break; - case self::BSTORECONTAINER: - $this->readBstoreContainer(); - - break; - case self::BSE: - $this->readBSE(); - - break; - case self::BLIPJPEG: - $this->readBlipJPEG(); - - break; - case self::BLIPPNG: - $this->readBlipPNG(); - - break; - case self::OPT: - $this->readOPT(); - - break; - case self::TERTIARYOPT: - $this->readTertiaryOPT(); - - break; - case self::SPLITMENUCOLORS: - $this->readSplitMenuColors(); - - break; - case self::DGCONTAINER: - $this->readDgContainer(); - - break; - case self::DG: - $this->readDg(); - - break; - case self::SPGRCONTAINER: - $this->readSpgrContainer(); - - break; - case self::SPCONTAINER: - $this->readSpContainer(); - - break; - case self::SPGR: - $this->readSpgr(); - - break; - case self::SP: - $this->readSp(); - - break; - case self::CLIENTTEXTBOX: - $this->readClientTextbox(); - - break; - case self::CLIENTANCHOR: - $this->readClientAnchor(); - - break; - case self::CLIENTDATA: - $this->readClientData(); - - break; - default: - $this->readDefault(); - - break; + $routine = self::WHICH_ROUTINE[$fbt] ?? 'readDefault'; + if (method_exists($this, $routine)) { + $this->$routine(); } } @@ -178,19 +124,19 @@ public function load($data) /** * Read a generic record. */ - private function readDefault() + private function readDefault(): void { // offset 0; size: 2; recVer and recInstance - $verInstance = Xls::getUInt2d($this->data, $this->pos); + //$verInstance = Xls::getUInt2d($this->data, $this->pos); // offset: 2; size: 2: Record Type - $fbt = Xls::getUInt2d($this->data, $this->pos + 2); + //$fbt = Xls::getUInt2d($this->data, $this->pos + 2); // bit: 0-3; mask: 0x000F; recVer - $recVer = (0x000F & $verInstance) >> 0; + //$recVer = (0x000F & $verInstance) >> 0; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -199,7 +145,7 @@ private function readDefault() /** * Read DggContainer record (Drawing Group Container). */ - private function readDggContainer() + private function readDggContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); @@ -209,7 +155,7 @@ private function readDggContainer() // record is a container, read contents $dggContainer = new DggContainer(); - $this->object->setDggContainer($dggContainer); + $this->applyAttribute('setDggContainer', $dggContainer); $reader = new self($dggContainer); $reader->load($recordData); } @@ -217,10 +163,10 @@ private function readDggContainer() /** * Read Dgg record (Drawing Group). */ - private function readDgg() + private function readDgg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -229,7 +175,7 @@ private function readDgg() /** * Read BstoreContainer record (Blip Store Container). */ - private function readBstoreContainer() + private function readBstoreContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); @@ -239,7 +185,7 @@ private function readBstoreContainer() // record is a container, read contents $bstoreContainer = new BstoreContainer(); - $this->object->setBstoreContainer($bstoreContainer); + $this->applyAttribute('setBstoreContainer', $bstoreContainer); $reader = new self($bstoreContainer); $reader->load($recordData); } @@ -247,7 +193,7 @@ private function readBstoreContainer() /** * Read BSE record. */ - private function readBSE() + private function readBSE(): void { // offset: 0; size: 2; recVer and recInstance @@ -262,45 +208,45 @@ private function readBSE() // add BSE to BstoreContainer $BSE = new BSE(); - $this->object->addBSE($BSE); + $this->applyAttribute('addBSE', $BSE); $BSE->setBLIPType($recInstance); // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) - $btWin32 = ord($recordData[0]); + //$btWin32 = ord($recordData[0]); // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) - $btMacOS = ord($recordData[1]); + //$btMacOS = ord($recordData[1]); // offset: 2; size: 16; MD4 digest - $rgbUid = substr($recordData, 2, 16); + //$rgbUid = substr($recordData, 2, 16); // offset: 18; size: 2; tag - $tag = Xls::getUInt2d($recordData, 18); + //$tag = Xls::getUInt2d($recordData, 18); // offset: 20; size: 4; size of BLIP in bytes - $size = Xls::getInt4d($recordData, 20); + //$size = Xls::getInt4d($recordData, 20); // offset: 24; size: 4; number of references to this BLIP - $cRef = Xls::getInt4d($recordData, 24); + //$cRef = Xls::getInt4d($recordData, 24); // offset: 28; size: 4; MSOFO file offset - $foDelay = Xls::getInt4d($recordData, 28); + //$foDelay = Xls::getInt4d($recordData, 28); // offset: 32; size: 1; unused1 - $unused1 = ord($recordData[32]); + //$unused1 = ord($recordData[32]); // offset: 33; size: 1; size of nameData in bytes (including null terminator) $cbName = ord($recordData[33]); // offset: 34; size: 1; unused2 - $unused2 = ord($recordData[34]); + //$unused2 = ord($recordData[34]); // offset: 35; size: 1; unused3 - $unused3 = ord($recordData[35]); + //$unused3 = ord($recordData[35]); // offset: 36; size: $cbName; nameData - $nameData = substr($recordData, 36, $cbName); + //$nameData = substr($recordData, 36, $cbName); // offset: 36 + $cbName, size: var; the BLIP data $blipData = substr($recordData, 36 + $cbName); @@ -313,7 +259,7 @@ private function readBSE() /** * Read BlipJPEG record. Holds raw JPEG image data. */ - private function readBlipJPEG() + private function readBlipJPEG(): void { // offset: 0; size: 2; recVer and recInstance @@ -329,18 +275,18 @@ private function readBlipJPEG() $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) - $rgbUid1 = substr($recordData, 0, 16); + //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if (in_array($recInstance, [0x046B, 0x06E3])) { - $rgbUid2 = substr($recordData, 16, 16); + //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag - $tag = ord($recordData[$pos]); - $pos += 1; + //$tag = ord($recordData[$pos]); + ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); @@ -348,13 +294,13 @@ private function readBlipJPEG() $blip = new Blip(); $blip->setData($data); - $this->object->setBlip($blip); + $this->applyAttribute('setBlip', $blip); } /** * Read BlipPNG record. Holds raw PNG image data. */ - private function readBlipPNG() + private function readBlipPNG(): void { // offset: 0; size: 2; recVer and recInstance @@ -370,18 +316,18 @@ private function readBlipPNG() $pos = 0; // offset: 0; size: 16; rgbUid1 (MD4 digest of) - $rgbUid1 = substr($recordData, 0, 16); + //$rgbUid1 = substr($recordData, 0, 16); $pos += 16; // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 if ($recInstance == 0x06E1) { - $rgbUid2 = substr($recordData, 16, 16); + //$rgbUid2 = substr($recordData, 16, 16); $pos += 16; } // offset: var; size: 1; tag - $tag = ord($recordData[$pos]); - $pos += 1; + //$tag = ord($recordData[$pos]); + ++$pos; // offset: var; size: var; the raw image data $data = substr($recordData, $pos); @@ -389,13 +335,13 @@ private function readBlipPNG() $blip = new Blip(); $blip->setData($data); - $this->object->setBlip($blip); + $this->applyAttribute('setBlip', $blip); } /** * Read OPT record. This record may occur within DggContainer record or SpContainer. */ - private function readOPT() + private function readOPT(): void { // offset: 0; size: 2; recVer and recInstance @@ -414,15 +360,15 @@ private function readOPT() /** * Read TertiaryOPT record. */ - private function readTertiaryOPT() + private function readTertiaryOPT(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -431,10 +377,10 @@ private function readTertiaryOPT() /** * Read SplitMenuColors record. */ - private function readSplitMenuColors() + private function readSplitMenuColors(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -443,7 +389,7 @@ private function readSplitMenuColors() /** * Read DgContainer record (Drawing Container). */ - private function readDgContainer() + private function readDgContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); @@ -453,18 +399,18 @@ private function readDgContainer() // record is a container, read contents $dgContainer = new DgContainer(); - $this->object->setDgContainer($dgContainer); + $this->applyAttribute('setDgContainer', $dgContainer); $reader = new self($dgContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** * Read Dg record (Drawing). */ - private function readDg() + private function readDg(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -473,7 +419,7 @@ private function readDg() /** * Read SpgrContainer record (Shape Group Container). */ - private function readSpgrContainer() + private function readSpgrContainer(): void { // context is either context DgContainer or SpgrContainer @@ -489,42 +435,42 @@ private function readSpgrContainer() if ($this->object instanceof DgContainer) { // DgContainer $this->object->setSpgrContainer($spgrContainer); - } else { + } elseif ($this->object instanceof SpgrContainer) { // SpgrContainer $this->object->addChild($spgrContainer); } $reader = new self($spgrContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** * Read SpContainer record (Shape Container). */ - private function readSpContainer() + private function readSpContainer(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); // add spContainer to spgrContainer $spContainer = new SpContainer(); - $this->object->addChild($spContainer); + $this->applyAttribute('addChild', $spContainer); // move stream pointer to next record $this->pos += 8 + $length; // record is a container, read contents $reader = new self($spContainer); - $escher = $reader->load($recordData); + $reader->load($recordData); } /** * Read Spgr record (Shape Group). */ - private function readSpgr() + private function readSpgr(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -533,15 +479,15 @@ private function readSpgr() /** * Read Sp record (Shape). */ - private function readSp() + private function readSp(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -550,15 +496,15 @@ private function readSp() /** * Read ClientTextbox record. */ - private function readClientTextbox() + private function readClientTextbox(): void { // offset: 0; size: 2; recVer and recInstance // bit: 4-15; mask: 0xFFF0; recInstance - $recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; + //$recInstance = (0xFFF0 & Xls::getUInt2d($this->data, $this->pos)) >> 4; $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -567,7 +513,7 @@ private function readClientTextbox() /** * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet. */ - private function readClientAnchor() + private function readClientAnchor(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); $recordData = substr($this->data, $this->pos + 8, $length); @@ -599,32 +545,31 @@ private function readClientAnchor() // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height $endOffsetY = Xls::getUInt2d($recordData, 16); - // set the start coordinates - $this->object->setStartCoordinates(Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); - - // set the start offsetX - $this->object->setStartOffsetX($startOffsetX); - - // set the start offsetY - $this->object->setStartOffsetY($startOffsetY); - - // set the end coordinates - $this->object->setEndCoordinates(Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); - - // set the end offsetX - $this->object->setEndOffsetX($endOffsetX); + $this->applyAttribute('setStartCoordinates', Coordinate::stringFromColumnIndex($c1 + 1) . ($r1 + 1)); + $this->applyAttribute('setStartOffsetX', $startOffsetX); + $this->applyAttribute('setStartOffsetY', $startOffsetY); + $this->applyAttribute('setEndCoordinates', Coordinate::stringFromColumnIndex($c2 + 1) . ($r2 + 1)); + $this->applyAttribute('setEndOffsetX', $endOffsetX); + $this->applyAttribute('setEndOffsetY', $endOffsetY); + } - // set the end offsetY - $this->object->setEndOffsetY($endOffsetY); + /** + * @param mixed $value + */ + private function applyAttribute(string $name, $value): void + { + if (method_exists($this->object, $name)) { + $this->object->$name($value); + } } /** * Read ClientData record. */ - private function readClientData() + private function readClientData(): void { $length = Xls::getInt4d($this->data, $this->pos + 4); - $recordData = substr($this->data, $this->pos + 8, $length); + //$recordData = substr($this->data, $this->pos + 8, $length); // move stream pointer to next record $this->pos += 8 + $length; @@ -636,7 +581,7 @@ private function readClientData() * @param string $data Binary data * @param int $n Number of properties */ - private function readOfficeArtRGFOPTE($data, $n) + private function readOfficeArtRGFOPTE($data, $n): void { $splicedComplexData = substr($data, 6 * $n); @@ -652,7 +597,7 @@ private function readOfficeArtRGFOPTE($data, $n) $opidOpid = (0x3FFF & $opid) >> 0; // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier - $opidFBid = (0x4000 & $opid) >> 14; + //$opidFBid = (0x4000 & $opid) >> 14; // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data $opidFComplex = (0x8000 & $opid) >> 15; @@ -671,7 +616,9 @@ private function readOfficeArtRGFOPTE($data, $n) $value = $op; } - $this->object->setOPT($opidOpid, $value); + if (method_exists($this->object, 'setOPT')) { + $this->object->setOPT($opidOpid, $value); + } } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php index 6a10e591..14b6bc54 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/MD5.php @@ -5,12 +5,25 @@ class MD5 { // Context + + /** + * @var int + */ private $a; + /** + * @var int + */ private $b; + /** + * @var int + */ private $c; + /** + * @var int + */ private $d; /** @@ -24,7 +37,7 @@ public function __construct() /** * Reset the MD5 stream context. */ - public function reset() + public function reset(): void { $this->a = 0x67452301; $this->b = 0xEFCDAB89; @@ -56,8 +69,9 @@ public function getContext() * * @param string $data Data to add */ - public function add($data) + public function add(string $data): void { + // @phpstan-ignore-next-line $words = array_values(unpack('V16', $data)); $A = $this->a; @@ -148,34 +162,34 @@ public function add($data) $this->d = ($this->d + $D) & 0xffffffff; } - private static function f($X, $Y, $Z) + private static function f(int $X, int $Y, int $Z) { return ($X & $Y) | ((~$X) & $Z); // X AND Y OR NOT X AND Z } - private static function g($X, $Y, $Z) + private static function g(int $X, int $Y, int $Z) { return ($X & $Z) | ($Y & (~$Z)); // X AND Z OR Y AND NOT Z } - private static function h($X, $Y, $Z) + private static function h(int $X, int $Y, int $Z) { return $X ^ $Y ^ $Z; // X XOR Y XOR Z } - private static function i($X, $Y, $Z) + private static function i(int $X, int $Y, int $Z) { return $Y ^ ($X | (~$Z)); // Y XOR (X OR NOT Z) } - private static function step($func, &$A, $B, $C, $D, $M, $s, $t) + private static function step($func, int &$A, int $B, int $C, int $D, int $M, int $s, int $t): void { $A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff; $A = self::rotate($A, $s); $A = ($B + $A) & 0xffffffff; } - private static function rotate($decimal, $bits) + private static function rotate(int $decimal, int $bits) { $binary = str_pad(decbin($decimal), 32, '0', STR_PAD_LEFT); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php index 91cbe36f..d832eb02 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/Border.php @@ -6,7 +6,10 @@ class Border { - protected static $map = [ + /** + * @var array + */ + protected static $borderStyleMap = [ 0x00 => StyleBorder::BORDER_NONE, 0x01 => StyleBorder::BORDER_THIN, 0x02 => StyleBorder::BORDER_MEDIUM, @@ -23,18 +26,10 @@ class Border 0x0D => StyleBorder::BORDER_SLANTDASHDOT, ]; - /** - * Map border style - * OpenOffice documentation: 2.5.11. - * - * @param int $index - * - * @return string - */ - public static function lookup($index) + public static function lookup(int $index): string { - if (isset(self::$map[$index])) { - return self::$map[$index]; + if (isset(self::$borderStyleMap[$index])) { + return self::$borderStyleMap[$index]; } return StyleBorder::BORDER_NONE; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php new file mode 100644 index 00000000..f03d47fa --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellAlignment.php @@ -0,0 +1,50 @@ + + */ + protected static $horizontalAlignmentMap = [ + 0 => Alignment::HORIZONTAL_GENERAL, + 1 => Alignment::HORIZONTAL_LEFT, + 2 => Alignment::HORIZONTAL_CENTER, + 3 => Alignment::HORIZONTAL_RIGHT, + 4 => Alignment::HORIZONTAL_FILL, + 5 => Alignment::HORIZONTAL_JUSTIFY, + 6 => Alignment::HORIZONTAL_CENTER_CONTINUOUS, + ]; + + /** + * @var array + */ + protected static $verticalAlignmentMap = [ + 0 => Alignment::VERTICAL_TOP, + 1 => Alignment::VERTICAL_CENTER, + 2 => Alignment::VERTICAL_BOTTOM, + 3 => Alignment::VERTICAL_JUSTIFY, + ]; + + public static function horizontal(Alignment $alignment, int $horizontal): void + { + if (array_key_exists($horizontal, self::$horizontalAlignmentMap)) { + $alignment->setHorizontal(self::$horizontalAlignmentMap[$horizontal]); + } + } + + public static function vertical(Alignment $alignment, int $vertical): void + { + if (array_key_exists($vertical, self::$verticalAlignmentMap)) { + $alignment->setVertical(self::$verticalAlignmentMap[$vertical]); + } + } + + public static function wrap(Alignment $alignment, int $wrap): void + { + $alignment->setWrapText((bool) $wrap); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php new file mode 100644 index 00000000..e975be4d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/CellFont.php @@ -0,0 +1,39 @@ +setSuperscript(true); + + break; + case 0x0002: + $font->setSubscript(true); + + break; + } + } + + /** + * @var array + */ + protected static $underlineMap = [ + 0x01 => Font::UNDERLINE_SINGLE, + 0x02 => Font::UNDERLINE_DOUBLE, + 0x21 => Font::UNDERLINE_SINGLEACCOUNTING, + 0x22 => Font::UNDERLINE_DOUBLEACCOUNTING, + ]; + + public static function underline(Font $font, int $underline): void + { + if (array_key_exists($underline, self::$underlineMap)) { + $font->setUnderline(self::$underlineMap[$underline]); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php index 7b85c088..32ab5c85 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xls/Style/FillPattern.php @@ -6,7 +6,10 @@ class FillPattern { - protected static $map = [ + /** + * @var array + */ + protected static $fillPatternMap = [ 0x00 => Fill::FILL_NONE, 0x01 => Fill::FILL_SOLID, 0x02 => Fill::FILL_PATTERN_MEDIUMGRAY, @@ -38,8 +41,8 @@ class FillPattern */ public static function lookup($index) { - if (isset(self::$map[$index])) { - return self::$map[$index]; + if (isset(self::$fillPatternMap[$index])) { + return self::$fillPatternMap[$index]; } return Fill::FILL_NONE; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php index 566e9fbb..a6e7fe03 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx.php @@ -3,8 +3,9 @@ namespace PhpOffice\PhpSpreadsheet\Reader; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\Hyperlink; -use PhpOffice\PhpSpreadsheet\NamedRange; +use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\AutoFilter; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Chart; @@ -12,11 +13,14 @@ use PhpOffice\PhpSpreadsheet\Reader\Xlsx\ConditionalStyles; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\DataValidations; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Hyperlinks; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Namespaces; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\PageSetup; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Properties as PropertyReader; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViewOptions; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\SheetViews; use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Theme; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx\WorkbookView; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; @@ -26,20 +30,20 @@ use PhpOffice\PhpSpreadsheet\Shared\Font; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; -use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use SimpleXMLElement; +use Throwable; use XMLReader; use ZipArchive; class Xlsx extends BaseReader { + const INITIAL_FILE = '_rels/.rels'; + /** * ReferenceHelper instance. * @@ -48,11 +52,12 @@ class Xlsx extends BaseReader private $referenceHelper; /** - * Xlsx\Theme instance. - * - * @var Xlsx\Theme + * @var ZipArchive */ - private static $theme = null; + private $zip; + + /** @var Styles */ + private $styleReader; /** * Create a new Xlsx Reader instance. @@ -66,22 +71,18 @@ public function __construct() /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @throws Exception - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { - File::assertFile($pFilename); + if (!File::testFileNoThrow($filename, self::INITIAL_FILE)) { + return false; + } $result = false; - $zip = new ZipArchive(); + $this->zip = $zip = new ZipArchive(); - if ($zip->open($pFilename) === true) { - $workbookBasename = $this->getWorkbookBaseName($zip); + if ($zip->open($filename) === true) { + [$workbookBasename] = $this->getWorkbookBaseName(); $result = !empty($workbookBasename); $zip->close(); @@ -90,43 +91,103 @@ public function canRead($pFilename) return $result; } + /** + * @param mixed $value + */ + public static function testSimpleXml($value): SimpleXMLElement + { + return ($value instanceof SimpleXMLElement) ? $value : new SimpleXMLElement(''); + } + + public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement + { + return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); + } + + // Phpstan thinks, correctly, that xpath can return false. + // Scrutinizer thinks it can't. + // Sigh. + private static function xpathNoFalse(SimpleXmlElement $sxml, string $path): array + { + return self::falseToArray($sxml->xpath($path)); + } + + /** + * @param mixed $value + */ + public static function falseToArray($value): array + { + return is_array($value) ? $value : []; + } + + private function loadZip(string $filename, string $ns = ''): SimpleXMLElement + { + $contents = $this->getFromZipArchive($this->zip, $filename); + $rels = simplexml_load_string( + $this->securityScanner->scan($contents), + 'SimpleXMLElement', + Settings::getLibXmlLoaderOptions(), + $ns + ); + + return self::testSimpleXml($rels); + } + + // This function is just to identify cases where I'm not sure + // why empty namespace is required. + private function loadZipNonamespace(string $filename, string $ns): SimpleXMLElement + { + $contents = $this->getFromZipArchive($this->zip, $filename); + $rels = simplexml_load_string( + $this->securityScanner->scan($contents), + 'SimpleXMLElement', + Settings::getLibXmlLoaderOptions(), + ($ns === '' ? $ns : '') + ); + + return self::testSimpleXml($rels); + } + + private const REL_TO_MAIN = [ + Namespaces::PURL_OFFICE_DOCUMENT => Namespaces::PURL_MAIN, + Namespaces::THUMBNAIL => '', + ]; + + private const REL_TO_DRAWING = [ + Namespaces::PURL_RELATIONSHIPS => Namespaces::PURL_DRAWING, + ]; + /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); $worksheetNames = []; - $zip = new ZipArchive(); - $zip->open($pFilename); + $this->zip = $zip = new ZipArchive(); + $zip->open($filename); // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader - //~ http://schemas.openxmlformats.org/package/2006/relationships"); - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')) - ); - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")) - ); - - if ($xmlWorkbook->sheets) { - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { - // Check if sheet should be skipped - $worksheetNames[] = (string) $eleSheet['name']; - } + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + if ($mainNS !== '') { + $xmlWorkbook = $this->loadZip((string) $rel['Target'], $mainNS); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + // Check if sheet should be skipped + $worksheetNames[] = (string) self::getAttributes($eleSheet)['name']; } + } } } @@ -138,74 +199,58 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); $worksheetInfo = []; - $zip = new ZipArchive(); - $zip->open($pFilename); + $this->zip = $zip = new ZipArchive(); + $zip->open($filename); - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($rels->Relationship as $rel) { - if ($rel['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument') { - $dir = dirname($rel['Target']); - - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorkbook = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + if ($mainNS !== '') { + $relTarget = (string) $rel['Target']; + $dir = dirname($relTarget); + $namespace = dirname($relType); + $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); $worksheets = []; - foreach ($relsWorkbook->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet') { + foreach ($relsWorkbook->Relationship as $elex) { + $ele = self::getAttributes($elex); + if ((string) $ele['Type'] === "$namespace/worksheet") { $worksheets[(string) $ele['Id']] = $ele['Target']; } } - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, "{$rel['Target']}") - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $xmlWorkbook = $this->loadZip($relTarget, $mainNS); if ($xmlWorkbook->sheets) { - $dir = dirname($rel['Target']); + $dir = dirname($relTarget); /** @var SimpleXMLElement $eleSheet */ foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { $tmpInfo = [ - 'worksheetName' => (string) $eleSheet['name'], + 'worksheetName' => (string) self::getAttributes($eleSheet)['name'], 'lastColumnLetter' => 'A', 'lastColumnIndex' => 0, 'totalRows' => 0, 'totalColumns' => 0, ]; - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; + $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $namespace), 'id')]; + $fileWorksheetPath = strpos($fileWorksheet, '/') === 0 ? substr($fileWorksheet, 1) : "$dir/$fileWorksheet"; $xml = new XMLReader(); $xml->xml( $this->securityScanner->scanFile( - 'zip://' . File::realpath($pFilename) . '#' . "$dir/$fileWorksheet" + 'zip://' . File::realpath($filename) . '#' . $fileWorksheetPath ), null, Settings::getLibXmlLoaderOptions() @@ -214,13 +259,14 @@ public function listWorksheetInfo($pFilename) $currCells = 0; while ($xml->read()) { - if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { + if ($xml->localName == 'row' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { $row = $xml->getAttribute('r'); $tmpInfo['totalRows'] = $row; $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); $currCells = 0; - } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { - ++$currCells; + } elseif ($xml->localName == 'c' && $xml->nodeType == XMLReader::ELEMENT && $xml->namespaceURI === $mainNS) { + $cell = $xml->getAttribute('r'); + $currCells = $cell ? max($currCells, Coordinate::indexesFromString($cell)[0]) : ($currCells + 1); } } $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); @@ -262,24 +308,25 @@ private static function castToString($c) return isset($c->v) ? (string) $c->v : null; } - private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType) + private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType): void { + $attr = $c->f->attributes(); $cellDataType = 'f'; $value = "={$c->f}"; $calculatedValue = self::$castBaseType($c); // Shared formula? - if (isset($c->f['t']) && strtolower((string) $c->f['t']) == 'shared') { - $instance = (string) $c->f['si']; + if (isset($attr['t']) && strtolower((string) $attr['t']) == 'shared') { + $instance = (string) $attr['si']; - if (!isset($sharedFormulas[(string) $c->f['si']])) { + if (!isset($sharedFormulas[(string) $attr['si']])) { $sharedFormulas[$instance] = ['master' => $r, 'formula' => $value]; } else { - $master = Coordinate::coordinateFromString($sharedFormulas[$instance]['master']); - $current = Coordinate::coordinateFromString($r); + $master = Coordinate::indexesFromString($sharedFormulas[$instance]['master']); + $current = Coordinate::indexesFromString($r); $difference = [0, 0]; - $difference[0] = Coordinate::columnIndexFromString($current[0]) - Coordinate::columnIndexFromString($master[0]); + $difference[0] = $current[0] - $master[0]; $difference[1] = $current[1] - $master[1]; $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]); @@ -288,7 +335,29 @@ private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValu } /** - * @param ZipArchive $archive + * @param string $fileName + */ + private function fileExistsInArchive(ZipArchive $archive, $fileName = ''): bool + { + // Root-relative paths + if (strpos($fileName, '//') !== false) { + $fileName = substr($fileName, strpos($fileName, '//') + 1); + } + $fileName = File::realpath($fileName); + + // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming + // so we need to load case-insensitively from the zip file + + // Apache POI fixes + $contents = $archive->locateName($fileName, ZipArchive::FL_NOCASE); + if ($contents === false) { + $contents = $archive->locateName(substr($fileName, 1), ZipArchive::FL_NOCASE); + } + + return $contents !== false; + } + + /** * @param string $fileName * * @return string @@ -299,6 +368,9 @@ private function getFromZipArchive(ZipArchive $archive, $fileName = '') if (strpos($fileName, '//') !== false) { $fileName = substr($fileName, strpos($fileName, '//') + 1); } + // Relative paths generated by dirname($filename) when $filename + // has no path (i.e.files in root of the zip archive) + $fileName = (string) preg_replace('/^\.\//', '', $fileName); $fileName = File::realpath($fileName); // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming @@ -315,128 +387,112 @@ private function getFromZipArchive(ZipArchive $archive, $fileName = '') /** * Loads Spreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { - File::assertFile($pFilename); + File::assertFile($filename, self::INITIAL_FILE); // Initialisations $excel = new Spreadsheet(); $excel->removeSheetByIndex(0); - if (!$this->readDataOnly) { - $excel->removeCellStyleXfByIndex(0); // remove the default style - $excel->removeCellXfByIndex(0); // remove the default style - } + $addingFirstCellStyleXf = true; + $addingFirstCellXf = true; + $unparsedLoadedData = []; - $zip = new ZipArchive(); - $zip->open($pFilename); + $this->zip = $zip = new ZipArchive(); + $zip->open($filename); // Read the theme first, because we need the colour scheme when reading the styles - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $workbookBasename = $this->getWorkbookBaseName($zip); - $wbRels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/_rels/${workbookBasename}.rels")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($wbRels->Relationship as $rel) { + [$workbookBasename, $xmlNamespaceBase] = $this->getWorkbookBaseName(); + $wbRels = $this->loadZip("xl/_rels/${workbookBasename}.rels", Namespaces::RELATIONSHIPS); + $theme = null; + $this->styleReader = new Styles(); + foreach ($wbRels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relTarget = (string) $rel['Target']; switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme': + case "$xmlNamespaceBase/theme": $themeOrderArray = ['lt1', 'dk1', 'lt2', 'dk2']; $themeOrderAdditional = count($themeOrderArray); - - $xmlTheme = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if (is_object($xmlTheme)) { - $xmlThemeName = $xmlTheme->attributes(); - $xmlTheme = $xmlTheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); - $themeName = (string) $xmlThemeName['name']; - - $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); - $colourSchemeName = (string) $colourScheme['name']; - $colourScheme = $xmlTheme->themeElements->clrScheme->children('http://schemas.openxmlformats.org/drawingml/2006/main'); - - $themeColours = []; - foreach ($colourScheme as $k => $xmlColour) { - $themePos = array_search($k, $themeOrderArray); - if ($themePos === false) { - $themePos = $themeOrderAdditional++; - } - if (isset($xmlColour->sysClr)) { - $xmlColourData = $xmlColour->sysClr->attributes(); - $themeColours[$themePos] = $xmlColourData['lastClr']; - } elseif (isset($xmlColour->srgbClr)) { - $xmlColourData = $xmlColour->srgbClr->attributes(); - $themeColours[$themePos] = $xmlColourData['val']; - } + $drawingNS = self::REL_TO_DRAWING[$xmlNamespaceBase] ?? Namespaces::DRAWINGML; + + $xmlTheme = $this->loadZip("xl/{$relTarget}", $drawingNS); + $xmlThemeName = self::getAttributes($xmlTheme); + $xmlTheme = $xmlTheme->children($drawingNS); + $themeName = (string) $xmlThemeName['name']; + + $colourScheme = self::getAttributes($xmlTheme->themeElements->clrScheme); + $colourSchemeName = (string) $colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children($drawingNS); + + $themeColours = []; + foreach ($colourScheme as $k => $xmlColour) { + $themePos = array_search($k, $themeOrderArray); + if ($themePos === false) { + $themePos = $themeOrderAdditional++; + } + if (isset($xmlColour->sysClr)) { + $xmlColourData = self::getAttributes($xmlColour->sysClr); + $themeColours[$themePos] = (string) $xmlColourData['lastClr']; + } elseif (isset($xmlColour->srgbClr)) { + $xmlColourData = self::getAttributes($xmlColour->srgbClr); + $themeColours[$themePos] = (string) $xmlColourData['val']; } - self::$theme = new Xlsx\Theme($themeName, $colourSchemeName, $themeColours); } + $theme = new Theme($themeName, $colourSchemeName, $themeColours); + $this->styleReader->setTheme($theme); break; } } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $rels = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, '_rels/.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS); $propertyReader = new PropertyReader($this->securityScanner, $excel->getProperties()); - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties': - $propertyReader->readCoreProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + foreach ($rels->Relationship as $relx) { + $rel = self::getAttributes($relx); + $relTarget = (string) $rel['Target']; + $relType = (string) $rel['Type']; + $mainNS = self::REL_TO_MAIN[$relType] ?? Namespaces::MAIN; + switch ($relType) { + case Namespaces::CORE_PROPERTIES: + $propertyReader->readCoreProperties($this->getFromZipArchive($zip, $relTarget)); break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties': - $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + case "$xmlNamespaceBase/extended-properties": + $propertyReader->readExtendedProperties($this->getFromZipArchive($zip, $relTarget)); break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties': - $propertyReader->readCustomProperties($this->getFromZipArchive($zip, "{$rel['Target']}")); + case "$xmlNamespaceBase/custom-properties": + $propertyReader->readCustomProperties($this->getFromZipArchive($zip, $relTarget)); break; //Ribbon - case 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility': - $customUI = $rel['Target']; - if ($customUI !== null) { + case Namespaces::EXTENSIBILITY: + $customUI = $relTarget; + if ($customUI) { $this->readRibbon($excel, $customUI, $zip); } break; - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - $dir = dirname($rel['Target']); - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel['Target']) . '.rels')), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $relsWorkbook->registerXPathNamespace('rel', 'http://schemas.openxmlformats.org/package/2006/relationships'); + case "$xmlNamespaceBase/officeDocument": + $dir = dirname($relTarget); + + // Do not specify namespace in next stmt - do it in Xpath + $relsWorkbook = $this->loadZip("$dir/_rels/" . basename($relTarget) . '.rels', ''); + $relsWorkbook->registerXPathNamespace('rel', Namespaces::RELATIONSHIPS); $sharedStrings = []; - $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); + $relType = "rel:Relationship[@Type='" + //. Namespaces::SHARED_STRINGS + . "$xmlNamespaceBase/sharedStrings" + . "']"; + $xpath = self::getArrayItem($relsWorkbook->xpath($relType)); + if ($xpath) { - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlStrings = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if (isset($xmlStrings, $xmlStrings->si)) { + $xmlStrings = $this->loadZip("$dir/$xpath[Target]", $mainNS); + if (isset($xmlStrings->si)) { foreach ($xmlStrings->si as $val) { if (isset($val->t)) { $sharedStrings[] = StringHelper::controlCharacterOOXML2PHP((string) $val->t); @@ -449,14 +505,16 @@ public function load($pFilename) $worksheets = []; $macros = $customUI = null; - foreach ($relsWorkbook->Relationship as $ele) { + foreach ($relsWorkbook->Relationship as $elex) { + $ele = self::getAttributes($elex); switch ($ele['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet': + case Namespaces::WORKSHEET: + case Namespaces::PURL_WORKSHEET: $worksheets[(string) $ele['Id']] = $ele['Target']; break; // a vbaProject ? (: some macros) - case 'http://schemas.microsoft.com/office/2006/relationships/vbaProject': + case Namespaces::VBA: $macros = $ele['Target']; break; @@ -476,26 +534,39 @@ public function load($pFilename) } } - $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlStyles = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relType = "rel:Relationship[@Type='" + . "$xmlNamespaceBase/styles" + . "']"; + $xpath = self::getArrayItem(self::xpathNoFalse($relsWorkbook, $relType)); + + if ($xpath === null) { + $xmlStyles = self::testSimpleXml(null); + } else { + $xmlStyles = $this->loadZip("$dir/$xpath[Target]", $mainNS); + } + + $palette = self::extractPalette($xmlStyles); + $this->styleReader->setWorkbookPalette($palette); + $fills = self::extractStyles($xmlStyles, 'fills', 'fill'); + $fonts = self::extractStyles($xmlStyles, 'fonts', 'font'); + $borders = self::extractStyles($xmlStyles, 'borders', 'border'); + $xfTags = self::extractStyles($xmlStyles, 'cellXfs', 'xf'); + $cellXfTags = self::extractStyles($xmlStyles, 'cellStyleXfs', 'xf'); $styles = []; $cellStyles = []; $numFmts = null; - if ($xmlStyles && $xmlStyles->numFmts[0]) { + if (/*$xmlStyles && */ $xmlStyles->numFmts[0]) { $numFmts = $xmlStyles->numFmts[0]; } if (isset($numFmts) && ($numFmts !== null)) { - $numFmts->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $numFmts->registerXPathNamespace('sml', $mainNS); } - if (!$this->readDataOnly && $xmlStyles) { - foreach ($xmlStyles->cellXfs->xf as $xf) { - $numFmt = NumberFormat::FORMAT_GENERAL; + $this->styleReader->setNamespace($mainNS); + if (!$this->readDataOnly/* && $xmlStyles*/) { + foreach ($xfTags as $xfTag) { + $xf = self::getAttributes($xfTag); + $numFmt = null; if ($xf['numFmtId']) { if (isset($numFmts)) { @@ -509,34 +580,39 @@ public function load($pFilename) // We shouldn't override any of the built-in MS Excel values (values below id 164) // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used // So we make allowance for them rather than lose formatting masks - if ((int) $xf['numFmtId'] < 164 && - NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '') { + if ( + $numFmt === null && + (int) $xf['numFmtId'] < 164 && + NumberFormat::builtInFormatCode((int) $xf['numFmtId']) !== '' + ) { $numFmt = NumberFormat::builtInFormatCode((int) $xf['numFmtId']); } } - $quotePrefix = false; - if (isset($xf['quotePrefix'])) { - $quotePrefix = (bool) $xf['quotePrefix']; - } + $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); $style = (object) [ - 'numFmt' => $numFmt, - 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])], - 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])], - 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])], - 'alignment' => $xf->alignment, - 'protection' => $xf->protection, + 'numFmt' => $numFmt ?? NumberFormat::FORMAT_GENERAL, + 'font' => $fonts[(int) ($xf['fontId'])], + 'fill' => $fills[(int) ($xf['fillId'])], + 'border' => $borders[(int) ($xf['borderId'])], + 'alignment' => $xfTag->alignment, + 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $styles[] = $style; // add style to cellXf collection $objStyle = new Style(); - self::readStyle($objStyle, $style); + $this->styleReader->readStyle($objStyle, $style); + if ($addingFirstCellXf) { + $excel->removeCellXfByIndex(0); // remove the default style + $addingFirstCellXf = false; + } $excel->addCellXf($objStyle); } - foreach (isset($xmlStyles->cellStyleXfs->xf) ? $xmlStyles->cellStyleXfs->xf : [] as $xf) { + foreach ($cellXfTags as $xfTag) { + $xf = self::getAttributes($xfTag); $numFmt = NumberFormat::FORMAT_GENERAL; if ($numFmts && $xf['numFmtId']) { $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); @@ -547,41 +623,44 @@ public function load($pFilename) } } + $quotePrefix = (bool) ($xf['quotePrefix'] ?? false); + $cellStyle = (object) [ 'numFmt' => $numFmt, - 'font' => $xmlStyles->fonts->font[(int) ($xf['fontId'])], - 'fill' => $xmlStyles->fills->fill[(int) ($xf['fillId'])], - 'border' => $xmlStyles->borders->border[(int) ($xf['borderId'])], - 'alignment' => $xf->alignment, - 'protection' => $xf->protection, + 'font' => $fonts[(int) ($xf['fontId'])], + 'fill' => $fills[((int) $xf['fillId'])], + 'border' => $borders[(int) ($xf['borderId'])], + 'alignment' => $xfTag->alignment, + 'protection' => $xfTag->protection, 'quotePrefix' => $quotePrefix, ]; $cellStyles[] = $cellStyle; // add style to cellStyleXf collection $objStyle = new Style(); - self::readStyle($objStyle, $cellStyle); + $this->styleReader->readStyle($objStyle, $cellStyle); + if ($addingFirstCellStyleXf) { + $excel->removeCellStyleXfByIndex(0); // remove the default style + $addingFirstCellStyleXf = false; + } $excel->addCellStyleXf($objStyle); } } + $this->styleReader->setStyleXml($xmlStyles); + $this->styleReader->setNamespace($mainNS); + $this->styleReader->setStyleBaseData($theme, $styles, $cellStyles); + $dxfs = $this->styleReader->dxfs($this->readDataOnly); + $styles = $this->styleReader->styles(); - $styleReader = new Styles($xmlStyles); - $styleReader->setStyleBaseData(self::$theme, $styles, $cellStyles); - $dxfs = $styleReader->dxfs($this->readDataOnly); - $styles = $styleReader->styles(); - - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlWorkbook = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "{$rel['Target']}")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $xmlWorkbook = $this->loadZipNoNamespace($relTarget, $mainNS); + $xmlWorkbookNS = $this->loadZip($relTarget, $mainNS); // Set base date - if ($xmlWorkbook->workbookPr) { + if ($xmlWorkbookNS->workbookPr) { Date::setExcelCalendar(Date::CALENDAR_WINDOWS_1900); - if (isset($xmlWorkbook->workbookPr['date1904'])) { - if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { + $attrs1904 = self::getAttributes($xmlWorkbookNS->workbookPr); + if (isset($attrs1904['date1904'])) { + if (self::boolean((string) $attrs1904['date1904'])) { Date::setExcelCalendar(Date::CALENDAR_MAC_1904); } } @@ -597,13 +676,14 @@ public function load($pFilename) $charts = $chartDetails = []; - if ($xmlWorkbook->sheets) { + if ($xmlWorkbookNS->sheets) { /** @var SimpleXMLElement $eleSheet */ - foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + foreach ($xmlWorkbookNS->sheets->sheet as $eleSheet) { + $eleSheetAttr = self::getAttributes($eleSheet); ++$oldSheetId; // Check if sheet should be skipped - if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet['name'], $this->loadSheetsOnly)) { + if (is_array($this->loadSheetsOnly) && !in_array((string) $eleSheetAttr['name'], $this->loadSheetsOnly)) { ++$countSkippedSheets; $mapSheetId[$oldSheetId] = null; @@ -620,44 +700,49 @@ public function load($pFilename) // references in formula cells... during the load, all formulae should be correct, // and we're simply bringing the worksheet name in line with the formula, not the // reverse - $docSheet->setTitle((string) $eleSheet['name'], false, false); - $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id')]; - //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main" - $xmlSheet = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $docSheet->setTitle((string) $eleSheetAttr['name'], false, false); + $fileWorksheet = (string) $worksheets[(string) self::getArrayItem(self::getAttributes($eleSheet, $xmlNamespaceBase), 'id')]; + $xmlSheet = $this->loadZipNoNamespace("$dir/$fileWorksheet", $mainNS); + $xmlSheetNS = $this->loadZip("$dir/$fileWorksheet", $mainNS); $sharedFormulas = []; - if (isset($eleSheet['state']) && (string) $eleSheet['state'] != '') { - $docSheet->setSheetState((string) $eleSheet['state']); + if (isset($eleSheetAttr['state']) && (string) $eleSheetAttr['state'] != '') { + $docSheet->setSheetState((string) $eleSheetAttr['state']); } - - if ($xmlSheet) { - if (isset($xmlSheet->sheetViews, $xmlSheet->sheetViews->sheetView)) { - $sheetViews = new SheetViews($xmlSheet->sheetViews->sheetView, $docSheet); + if ($xmlSheetNS) { + $xmlSheetMain = $xmlSheetNS->children($mainNS); + // Setting Conditional Styles adjusts selected cells, so we need to execute this + // before reading the sheet view data to get the actual selected cells + if (!$this->readDataOnly && ($xmlSheet->conditionalFormatting)) { + (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load(); + } + if (!$this->readDataOnly && $xmlSheet->extLst) { + (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->loadFromExt($this->styleReader); + } + if (isset($xmlSheetMain->sheetViews, $xmlSheetMain->sheetViews->sheetView)) { + $sheetViews = new SheetViews($xmlSheetMain->sheetViews->sheetView, $docSheet); $sheetViews->load(); } $sheetViewOptions = new SheetViewOptions($docSheet, $xmlSheet); - $sheetViewOptions->load($this->getReadDataOnly()); + $sheetViewOptions->load($this->getReadDataOnly(), $this->styleReader); (new ColumnAndRowAttributes($docSheet, $xmlSheet)) ->load($this->getReadFilter(), $this->getReadDataOnly()); } - if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { + if ($xmlSheetNS && $xmlSheetNS->sheetData && $xmlSheetNS->sheetData->row) { $cIndex = 1; // Cell Start from 1 - foreach ($xmlSheet->sheetData->row as $row) { + foreach ($xmlSheetNS->sheetData->row as $row) { $rowIndex = 1; foreach ($row->c as $c) { - $r = (string) $c['r']; + $cAttr = self::getAttributes($c); + $r = (string) $cAttr['r']; if ($r == '') { $r = Coordinate::stringFromColumnIndex($rowIndex) . $cIndex; } - $cellDataType = (string) $c['t']; + $cellDataType = (string) $cAttr['t']; $value = null; $calculatedValue = null; @@ -666,7 +751,10 @@ public function load($pFilename) $coordinates = Coordinate::coordinateFromString($r); if (!$this->getReadFilter()->readCell($coordinates[0], (int) $coordinates[1], $docSheet->getTitle())) { - $rowIndex += 1; + if (isset($cAttr->f)) { + $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError'); + } + ++$rowIndex; continue; } @@ -688,7 +776,12 @@ public function load($pFilename) break; case 'b': if (!isset($c->f)) { - $value = self::castToBoolean($c); + if (isset($c->v)) { + $value = self::castToBoolean($c); + } else { + $value = null; + $cellDataType = DATATYPE::TYPE_NULL; + } } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean'); @@ -722,6 +815,10 @@ public function load($pFilename) } else { // Formula $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString'); + if (isset($c->f['t'])) { + $attributes = $c->f['t']; + $docSheet->getCell($r)->setFormulaAttributes(['t' => (string) $attributes]); + } } break; @@ -737,7 +834,13 @@ public function load($pFilename) $cell = $docSheet->getCell($r); // Assign value if ($cellDataType != '') { - $cell->setValueExplicit($value, $cellDataType); + // it is possible, that datatype is numeric but with an empty string, which result in an error + if ($cellDataType === DataType::TYPE_NUMERIC && ($value === '' || $value === null)) { + $cellDataType = DataType::TYPE_NULL; + } + if ($cellDataType !== DataType::TYPE_NULL) { + $cell->setValueExplicit($value, $cellDataType); + } } else { $cell->setValue($value); } @@ -746,22 +849,18 @@ public function load($pFilename) } // Style information? - if ($c['s'] && !$this->readDataOnly) { + if ($cAttr['s'] && !$this->readDataOnly) { // no style index means 0, it seems - $cell->setXfIndex(isset($styles[(int) ($c['s'])]) ? - (int) ($c['s']) : 0); + $cell->setXfIndex(isset($styles[(int) ($cAttr['s'])]) ? + (int) ($cAttr['s']) : 0); } } - $rowIndex += 1; + ++$rowIndex; } - $cIndex += 1; + ++$cIndex; } } - if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { - (new ConditionalStyles($docSheet, $xmlSheet, $dxfs))->load(); - } - $aKeys = ['sheet', 'objects', 'scenarios', 'formatCells', 'formatColumns', 'formatRows', 'insertColumns', 'insertRows', 'insertHyperlinks', 'deleteColumns', 'deleteRows', 'selectLockedCells', 'sort', 'autoFilter', 'pivotTables', 'selectUnlockedCells']; if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { foreach ($aKeys as $key) { @@ -770,17 +869,12 @@ public function load($pFilename) } } - if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { - $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection['password'], true); - if ($xmlSheet->protectedRanges->protectedRange) { - foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { - $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true); - } - } + if ($xmlSheet) { + $this->readSheetProtection($docSheet, $xmlSheet); } - if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) { - (new AutoFilter($docSheet, $xmlSheet))->load(); + if ($this->readDataOnly === false) { + $this->readAutoFilterTables($xmlSheet, $docSheet, $dir, $fileWorksheet, $zip); } if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) { @@ -796,15 +890,32 @@ public function load($pFilename) $unparsedLoadedData = (new PageSetup($docSheet, $xmlSheet))->load($unparsedLoadedData); } + if ($xmlSheet !== false && isset($xmlSheet->extLst, $xmlSheet->extLst->ext, $xmlSheet->extLst->ext['uri']) && ($xmlSheet->extLst->ext['uri'] == '{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}')) { + // Create dataValidations node if does not exists, maybe is better inside the foreach ? + if (!$xmlSheet->dataValidations) { + $xmlSheet->addChild('dataValidations'); + } + + foreach ($xmlSheet->extLst->ext->children('x14', true)->dataValidations->dataValidation as $item) { + $node = self::testSimpleXml($xmlSheet->dataValidations)->addChild('dataValidation'); + foreach ($item->attributes() ?? [] as $attr) { + $node->addAttribute($attr->getName(), $attr); + } + $node->addAttribute('sqref', $item->children('xm', true)->sqref); + $node->addChild('formula1', $item->formula1->children('xm', true)->f); + } + } + if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { (new DataValidations($docSheet, $xmlSheet))->load(); } // unparsed sheet AlternateContent if ($xmlSheet && !$this->readDataOnly) { - $mc = $xmlSheet->children('http://schemas.openxmlformats.org/markup-compatibility/2006'); + $mc = $xmlSheet->children(Namespaces::COMPATIBILITY); if ($mc->AlternateContent) { foreach ($mc->AlternateContent as $alternateContent) { + $alternateContent = self::testSimpleXml($alternateContent); $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['AlternateContents'][] = $alternateContent->asXML(); } } @@ -816,20 +927,13 @@ public function load($pFilename) // Locate hyperlink relations $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; if ($zip->locateName($relationsFileName)) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, $relationsFileName) - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsWorksheet = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); $hyperlinkReader->readHyperlinks($relsWorksheet); } // Loop through hyperlinks - if ($xmlSheet && $xmlSheet->hyperlinks) { - $hyperlinkReader->setHyperlinks($xmlSheet->hyperlinks); + if ($xmlSheetNS && $xmlSheetNS->children($mainNS)->hyperlinks) { + $hyperlinkReader->setHyperlinks($xmlSheetNS->children($mainNS)->hyperlinks); } } @@ -838,20 +942,15 @@ public function load($pFilename) $vmlComments = []; if (!$this->readDataOnly) { // Locate comment relations - if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments') { + $commentRelations = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + if ($zip->locateName($commentRelations)) { + $relsWorksheet = $this->loadZip($commentRelations, Namespaces::RELATIONSHIPS); + foreach ($relsWorksheet->Relationship as $elex) { + $ele = self::getAttributes($elex); + if ($ele['Type'] == Namespaces::COMMENTS) { $comments[(string) $ele['Id']] = (string) $ele['Target']; } - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + if ($ele['Type'] == Namespaces::VML) { $vmlComments[(string) $ele['Id']] = (string) $ele['Target']; } } @@ -861,26 +960,26 @@ public function load($pFilename) foreach ($comments as $relName => $relPath) { // Load comments file $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); - $commentsFile = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + // okay to ignore namespace - using xpath + $commentsFile = $this->loadZip($relPath, ''); // Utility variables $authors = []; - - // Loop through authors - foreach ($commentsFile->authors->author as $author) { + $commentsFile->registerXpathNamespace('com', $mainNS); + $authorPath = self::xpathNoFalse($commentsFile, 'com:authors/com:author'); + foreach ($authorPath as $author) { $authors[] = (string) $author; } // Loop through contents - foreach ($commentsFile->commentList->comment as $comment) { - if (!empty($comment['authorId'])) { - $docSheet->getComment((string) $comment['ref'])->setAuthor($authors[(string) $comment['authorId']]); + $contentPath = self::xpathNoFalse($commentsFile, 'com:commentList/com:comment'); + foreach ($contentPath as $comment) { + $commentx = $comment->attributes(); + $commentModel = $docSheet->getComment((string) $commentx['ref']); + if (isset($commentx['authorId'])) { + $commentModel->setAuthor($authors[(int) $commentx['authorId']]); } - $docSheet->getComment((string) $comment['ref'])->setText($this->parseRichText($comment->text)); + $commentModel->setText($this->parseRichText($comment->children($mainNS)->text)); } } @@ -893,26 +992,38 @@ public function load($pFilename) $relPath = File::realpath(dirname("$dir/$fileWorksheet") . '/' . $relPath); try { - $vmlCommentsFile = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $relPath)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); - } catch (\Throwable $ex) { + // no namespace okay - processed with Xpath + $vmlCommentsFile = $this->loadZip($relPath, ''); + $vmlCommentsFile->registerXPathNamespace('v', Namespaces::URN_VML); + } catch (Throwable $ex) { //Ignore unparsable vmlDrawings. Later they will be moved from $unparsedVmlDrawings to $unparsedLoadedData continue; } - $shapes = $vmlCommentsFile->xpath('//v:shape'); + // Locate VML drawings image relations + $drowingImages = []; + $VMLDrawingsRelations = dirname($relPath) . '/_rels/' . basename($relPath) . '.rels'; + if ($zip->locateName($VMLDrawingsRelations)) { + $relsVMLDrawing = $this->loadZip($VMLDrawingsRelations, Namespaces::RELATIONSHIPS); + foreach ($relsVMLDrawing->Relationship as $elex) { + $ele = self::getAttributes($elex); + if ($ele['Type'] == Namespaces::IMAGE) { + $drowingImages[(string) $ele['Id']] = (string) $ele['Target']; + } + } + } + + $shapes = self::xpathNoFalse($vmlCommentsFile, '//v:shape'); foreach ($shapes as $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $shape->registerXPathNamespace('v', Namespaces::URN_VML); if (isset($shape['style'])) { $style = (string) $shape['style']; $fillColor = strtoupper(substr((string) $shape['fillcolor'], 1)); $column = null; $row = null; + $fillImageRelId = null; + $fillImageTitle = ''; $clientData = $shape->xpath('.//x:ClientData'); if (is_array($clientData) && !empty($clientData)) { @@ -931,10 +1042,39 @@ public function load($pFilename) } } + $fillImageRelNode = $shape->xpath('.//v:fill/@o:relid'); + if (is_array($fillImageRelNode) && !empty($fillImageRelNode)) { + $fillImageRelNode = $fillImageRelNode[0]; + + if (isset($fillImageRelNode['relid'])) { + $fillImageRelId = (string) $fillImageRelNode['relid']; + } + } + + $fillImageTitleNode = $shape->xpath('.//v:fill/@o:title'); + if (is_array($fillImageTitleNode) && !empty($fillImageTitleNode)) { + $fillImageTitleNode = $fillImageTitleNode[0]; + + if (isset($fillImageTitleNode['title'])) { + $fillImageTitle = (string) $fillImageTitleNode['title']; + } + } + if (($column !== null) && ($row !== null)) { // Set comment properties $comment = $docSheet->getCommentByColumnAndRow($column + 1, $row + 1); $comment->getFillColor()->setRGB($fillColor); + if (isset($drowingImages[$fillImageRelId])) { + $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); + $objDrawing->setName($fillImageTitle); + $imagePath = str_replace('../', 'xl/', $drowingImages[$fillImageRelId]); + $objDrawing->setPath( + 'zip://' . File::realpath($filename) . '#' . $imagePath, + true, + $zip + ); + $comment->setBackgroundImage($objDrawing); + } // Parse style $styleArray = explode(';', str_replace(' ', '', $style)); @@ -980,61 +1120,44 @@ public function load($pFilename) // Header/footer images if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) { if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsWorksheet = $this->loadZipNoNamespace(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels', Namespaces::RELATIONSHIPS); $vmlRelationship = ''; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing') { + if ($ele['Type'] == Namespaces::VML) { $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } if ($vmlRelationship != '') { // Fetch linked images - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsVML = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $relsVML = $this->loadZipNoNamespace(dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels', Namespaces::RELATIONSHIPS); $drawings = []; - foreach ($relsVML->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { - $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); + if (isset($relsVML->Relationship)) { + foreach ($relsVML->Relationship as $ele) { + if ($ele['Type'] == Namespaces::IMAGE) { + $drawings[(string) $ele['Id']] = self::dirAdd($vmlRelationship, $ele['Target']); + } } } - // Fetch VML document - $vmlDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $vmlRelationship)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $vmlDrawing = $this->loadZipNoNamespace($vmlRelationship, ''); + $vmlDrawing->registerXPathNamespace('v', Namespaces::URN_VML); $hfImages = []; - $shapes = $vmlDrawing->xpath('//v:shape'); + $shapes = self::xpathNoFalse($vmlDrawing, '//v:shape'); foreach ($shapes as $idx => $shape) { - $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $shape->registerXPathNamespace('v', Namespaces::URN_VML); $imageData = $shape->xpath('//v:imagedata'); - if (!$imageData) { + if (empty($imageData)) { continue; } $imageData = $imageData[$idx]; - $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); + $imageData = self::getAttributes($imageData, Namespaces::URN_MSOFFICE); $style = self::toCSSArray((string) $shape['style']); $hfImages[(string) $shape['id']] = new HeaderFooterDrawing(); @@ -1042,7 +1165,7 @@ public function load($pFilename) $hfImages[(string) $shape['id']]->setName((string) $imageData['title']); } - $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($pFilename) . '#' . $drawings[(string) $imageData['relid']], false); + $hfImages[(string) $shape['id']]->setPath('zip://' . File::realpath($filename) . '#' . $drawings[(string) $imageData['relid']], false); $hfImages[(string) $shape['id']]->setResizeProportional(false); $hfImages[(string) $shape['id']]->setWidth($style['width']); $hfImages[(string) $shape['id']]->setHeight($style['height']); @@ -1060,44 +1183,37 @@ public function load($pFilename) } // TODO: Autoshapes from twoCellAnchors! - if ($zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $drawingFilename = dirname("$dir/$fileWorksheet") + . '/_rels/' + . basename($fileWorksheet) + . '.rels'; + if ($zip->locateName($drawingFilename)) { + $relsWorksheet = $this->loadZipNoNamespace($drawingFilename, Namespaces::RELATIONSHIPS); $drawings = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') { + if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawings[(string) $ele['Id']] = self::dirAdd("$dir/$fileWorksheet", $ele['Target']); } } if ($xmlSheet->drawing && !$this->readDataOnly) { $unparsedDrawings = []; + $fileDrawing = null; foreach ($xmlSheet->drawing as $drawing) { - $drawingRelId = (string) self::getArrayItem($drawing->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), 'id'); + $drawingRelId = (string) self::getArrayItem(self::getAttributes($drawing, $xmlNamespaceBase), 'id'); $fileDrawing = $drawings[$drawingRelId]; - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsDrawing = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $drawingFilename = dirname($fileDrawing) . '/_rels/' . basename($fileDrawing) . '.rels'; + $relsDrawing = $this->loadZipNoNamespace($drawingFilename, $xmlNamespaceBase); $images = []; $hyperlinks = []; if ($relsDrawing && $relsDrawing->Relationship) { foreach ($relsDrawing->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') { + $eleType = (string) $ele['Type']; + if ($eleType === Namespaces::HYPERLINK) { $hyperlinks[(string) $ele['Id']] = (string) $ele['Target']; } - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ($eleType === "$xmlNamespaceBase/image") { $images[(string) $ele['Id']] = self::dirAdd($fileDrawing, $ele['Target']); - } elseif ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart') { + } elseif ($eleType === "$xmlNamespaceBase/chart") { if ($this->includeCharts) { $charts[self::dirAdd($fileDrawing, $ele['Target'])] = [ 'id' => (string) $ele['Id'], @@ -1107,124 +1223,171 @@ public function load($pFilename) } } } - $xmlDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - $xmlDrawingChildren = $xmlDrawing->children('http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); + $xmlDrawing = $this->loadZipNoNamespace($fileDrawing, ''); + $xmlDrawingChildren = $xmlDrawing->children(Namespaces::SPREADSHEET_DRAWING); if ($xmlDrawingChildren->oneCellAnchor) { foreach ($xmlDrawingChildren->oneCellAnchor as $oneCellAnchor) { if ($oneCellAnchor->pic->blipFill) { /** @var SimpleXMLElement $blip */ - $blip = $oneCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; + $blip = $oneCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; /** @var SimpleXMLElement $xfrm */ - $xfrm = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; + $xfrm = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; /** @var SimpleXMLElement $outerShdw */ - $outerShdw = $oneCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; - /** @var \SimpleXMLElement $hlinkClick */ - $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $outerShdw = $oneCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; + /** @var SimpleXMLElement $hlinkClick */ + $hlinkClick = $oneCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); - $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); - $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); - $objDrawing->setPath( - 'zip://' . File::realpath($pFilename) . '#' . - $images[(string) self::getArrayItem( - $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), - 'embed' - )], - false + $objDrawing->setName((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'name')); + $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($oneCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $embedImageKey = (string) self::getArrayItem( + self::getAttributes($blip, $xmlNamespaceBase), + 'embed' ); - $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1)); - $objDrawing->setOffsetX(Drawing::EMUToPixels($oneCellAnchor->from->colOff)); + if (isset($images[$embedImageKey])) { + $objDrawing->setPath( + 'zip://' . File::realpath($filename) . '#' . + $images[$embedImageKey], + false + ); + } else { + $linkImageKey = (string) self::getArrayItem( + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'link' + ); + if (isset($images[$linkImageKey])) { + $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); + $objDrawing->setPath($url); + } + } + $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1)); + + $objDrawing->setOffsetX((int) Drawing::EMUToPixels($oneCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); $objDrawing->setResizeProportional(false); - $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx'))); - $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy'))); + $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx'))); + $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy'))); if ($xfrm) { - $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot'))); + $objDrawing->setRotation((int) Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad'))); - $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist'))); - $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir'))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); - $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr; - $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val')); - $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000); + $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad'))); + $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist'))); + $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn')); + $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; + $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val')); + $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000); } $this->readHyperLinkDrawing($objDrawing, $oneCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); - } else { - // ? Can charts be positioned with a oneCellAnchor ? - $coordinates = Coordinate::stringFromColumnIndex(((string) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1); + } elseif ($this->includeCharts && $oneCellAnchor->graphicFrame) { + // Exported XLSX from Google Sheets positions charts with a oneCellAnchor + $coordinates = Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1); $offsetX = Drawing::EMUToPixels($oneCellAnchor->from->colOff); $offsetY = Drawing::EMUToPixels($oneCellAnchor->from->rowOff); - $width = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cx')); - $height = Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), 'cy')); + $width = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cx')); + $height = Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($oneCellAnchor->ext), 'cy')); + + $graphic = $oneCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; + /** @var SimpleXMLElement $chartRef */ + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); + + $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ + 'fromCoordinate' => $coordinates, + 'fromOffsetX' => $offsetX, + 'fromOffsetY' => $offsetY, + 'width' => $width, + 'height' => $height, + 'worksheetTitle' => $docSheet->getTitle(), + ]; } } } if ($xmlDrawingChildren->twoCellAnchor) { foreach ($xmlDrawingChildren->twoCellAnchor as $twoCellAnchor) { if ($twoCellAnchor->pic->blipFill) { - $blip = $twoCellAnchor->pic->blipFill->children('http://schemas.openxmlformats.org/drawingml/2006/main')->blip; - $xfrm = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->xfrm; - $outerShdw = $twoCellAnchor->pic->spPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->effectLst->outerShdw; - $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $blip = $twoCellAnchor->pic->blipFill->children(Namespaces::DRAWINGML)->blip; + $xfrm = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children(Namespaces::DRAWINGML)->effectLst->outerShdw; + $hlinkClick = $twoCellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; $objDrawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); - $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name')); - $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), 'descr')); - $objDrawing->setPath( - 'zip://' . File::realpath($pFilename) . '#' . - $images[(string) self::getArrayItem( - $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), - 'embed' - )], - false + /** @scrutinizer ignore-call */ + $editAs = $twoCellAnchor->attributes(); + if (isset($editAs, $editAs['editAs'])) { + $objDrawing->setEditAs($editAs['editAs']); + } + $objDrawing->setName((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'name')); + $objDrawing->setDescription((string) self::getArrayItem(self::getAttributes($twoCellAnchor->pic->nvPicPr->cNvPr), 'descr')); + $embedImageKey = (string) self::getArrayItem( + self::getAttributes($blip, $xmlNamespaceBase), + 'embed' ); - $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1)); + if (isset($images[$embedImageKey])) { + $objDrawing->setPath( + 'zip://' . File::realpath($filename) . '#' . + $images[$embedImageKey], + false + ); + } else { + $linkImageKey = (string) self::getArrayItem( + $blip->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'), + 'link' + ); + if (isset($images[$linkImageKey])) { + $url = str_replace('xl/drawings/', '', $images[$linkImageKey]); + $objDrawing->setPath($url); + } + } + $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(Drawing::EMUToPixels($twoCellAnchor->from->colOff)); $objDrawing->setOffsetY(Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); + + $objDrawing->setCoordinates2(Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1)); + + $objDrawing->setOffsetX2(Drawing::EMUToPixels($twoCellAnchor->to->colOff)); + $objDrawing->setOffsetY2(Drawing::EMUToPixels($twoCellAnchor->to->rowOff)); + $objDrawing->setResizeProportional(false); if ($xfrm) { - $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cx'))); - $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), 'cy'))); - $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), 'rot'))); + $objDrawing->setWidth(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cx'))); + $objDrawing->setHeight(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($xfrm->ext), 'cy'))); + $objDrawing->setRotation(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($xfrm), 'rot'))); } if ($outerShdw) { $shadow = $objDrawing->getShadow(); $shadow->setVisible(true); - $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'blurRad'))); - $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem($outerShdw->attributes(), 'dist'))); - $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), 'dir'))); - $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), 'algn')); - $clr = isset($outerShdw->srgbClr) ? $outerShdw->srgbClr : $outerShdw->prstClr; - $shadow->getColor()->setRGB(self::getArrayItem($clr->attributes(), 'val')); - $shadow->setAlpha(self::getArrayItem($clr->alpha->attributes(), 'val') / 1000); + $shadow->setBlurRadius(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'blurRad'))); + $shadow->setDistance(Drawing::EMUToPixels(self::getArrayItem(self::getAttributes($outerShdw), 'dist'))); + $shadow->setDirection(Drawing::angleToDegrees(self::getArrayItem(self::getAttributes($outerShdw), 'dir'))); + $shadow->setAlignment((string) self::getArrayItem(self::getAttributes($outerShdw), 'algn')); + $clr = $outerShdw->srgbClr ?? $outerShdw->prstClr; + $shadow->getColor()->setRGB(self::getArrayItem(self::getAttributes($clr), 'val')); + $shadow->setAlpha(self::getArrayItem(self::getAttributes($clr->alpha), 'val') / 1000); } $this->readHyperLinkDrawing($objDrawing, $twoCellAnchor, $hyperlinks); $objDrawing->setWorksheet($docSheet); } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) { - $fromCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); + $fromCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->from->col) + 1) . ($twoCellAnchor->from->row + 1); $fromOffsetX = Drawing::EMUToPixels($twoCellAnchor->from->colOff); $fromOffsetY = Drawing::EMUToPixels($twoCellAnchor->from->rowOff); - $toCoordinate = Coordinate::stringFromColumnIndex(((string) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1); + $toCoordinate = Coordinate::stringFromColumnIndex(((int) $twoCellAnchor->to->col) + 1) . ($twoCellAnchor->to->row + 1); $toOffsetX = Drawing::EMUToPixels($twoCellAnchor->to->colOff); $toOffsetY = Drawing::EMUToPixels($twoCellAnchor->to->rowOff); - $graphic = $twoCellAnchor->graphicFrame->children('http://schemas.openxmlformats.org/drawingml/2006/main')->graphic; + $graphic = $twoCellAnchor->graphicFrame->children(Namespaces::DRAWINGML)->graphic; /** @var SimpleXMLElement $chartRef */ - $chartRef = $graphic->graphicData->children('http://schemas.openxmlformats.org/drawingml/2006/chart')->chart; - $thisChart = (string) $chartRef->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $chartRef = $graphic->graphicData->children(Namespaces::CHART)->chart; + $thisChart = (string) self::getAttributes($chartRef, $xmlNamespaceBase); $chartDetails[$docSheet->getTitle() . '!' . $thisChart] = [ 'fromCoordinate' => $fromCoordinate, @@ -1238,7 +1401,7 @@ public function load($pFilename) } } } - if ($relsDrawing === false && $xmlDrawing->count() == 0) { + if (empty($relsDrawing) && $xmlDrawing->count() == 0) { // Save Drawing without rels and children as unparsed $unparsedDrawings[$drawingRelId] = $xmlDrawing->asXML(); } @@ -1247,7 +1410,7 @@ public function load($pFilename) // store original rId of drawing files $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'] = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing') { + if ((string) $ele['Type'] === "$xmlNamespaceBase/drawing") { $drawingRelId = (string) $ele['Id']; $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingOriginalIds'][(string) $ele['Target']] = $drawingRelId; if (isset($unparsedDrawings[$drawingRelId])) { @@ -1257,22 +1420,19 @@ public function load($pFilename) } // unparsed drawing AlternateContent - $xmlAltDrawing = simplexml_load_string( - $this->securityScanner->scan($this->getFromZipArchive($zip, $fileDrawing)), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - )->children('http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlAltDrawing = $this->loadZip($fileDrawing, Namespaces::COMPATIBILITY); if ($xmlAltDrawing->AlternateContent) { foreach ($xmlAltDrawing->AlternateContent as $alternateContent) { + $alternateContent = self::testSimpleXml($alternateContent); $unparsedLoadedData['sheets'][$docSheet->getCodeName()]['drawingAlternateContents'][] = $alternateContent->asXML(); } } } } - $this->readFormControlProperties($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); - $this->readPrinterSettings($excel, $zip, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readFormControlProperties($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); + $this->readPrinterSettings($excel, $dir, $fileWorksheet, $docSheet, $unparsedLoadedData); // Loop through definedNames if ($xmlWorkbook->definedNames) { @@ -1286,7 +1446,7 @@ public function load($pFilename) } // Valid range? - if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') { + if ($extractedRange == '') { continue; } @@ -1354,14 +1514,9 @@ public function load($pFilename) foreach ($xmlWorkbook->definedNames->definedName as $definedName) { // Extract range $extractedRange = (string) $definedName; - if (($spos = strpos($extractedRange, '!')) !== false) { - $extractedRange = substr($extractedRange, 0, $spos) . str_replace('$', '', substr($extractedRange, $spos)); - } else { - $extractedRange = str_replace('$', '', $extractedRange); - } // Valid range? - if (stripos((string) $definedName, '#REF!') !== false || $extractedRange == '') { + if ($extractedRange == '') { continue; } @@ -1376,113 +1531,56 @@ public function load($pFilename) break; default: if ($mapSheetId[(int) $definedName['localSheetId']] !== null) { + $range = Worksheet::extractSheetTitle((string) $definedName, true); + $scope = $excel->getSheet($mapSheetId[(int) $definedName['localSheetId']]); if (strpos((string) $definedName, '!') !== false) { - $range = Worksheet::extractSheetTitle((string) $definedName, true); $range[0] = str_replace("''", "'", $range[0]); $range[0] = str_replace("'", '', $range[0]); - if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { - $extractedRange = str_replace('$', '', $range[1]); - $scope = $docSheet->getParent()->getSheet($mapSheetId[(int) $definedName['localSheetId']]); - $excel->addNamedRange(new NamedRange((string) $definedName['name'], $worksheet, $extractedRange, true, $scope)); + if ($worksheet = $excel->getSheetByName($range[0])) { + $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $worksheet, $extractedRange, true, $scope)); + } else { + $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true, $scope)); } + } else { + $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $scope, $extractedRange, true)); } } break; } } elseif (!isset($definedName['localSheetId'])) { + $definedRange = (string) $definedName; // "Global" definedNames $locatedSheet = null; - $extractedSheetName = ''; if (strpos((string) $definedName, '!') !== false) { + // Modify range, and extract the first worksheet reference + // Need to split on a comma or a space if not in quotes, and extract the first part. + $definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $definedRange); // Extract sheet name - $extractedSheetName = Worksheet::extractSheetTitle((string) $definedName, true); - $extractedSheetName = trim($extractedSheetName[0], "'"); + [$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true); + $extractedSheetName = trim($extractedSheetName, "'"); // Locate sheet $locatedSheet = $excel->getSheetByName($extractedSheetName); - - // Modify range - [$worksheetName, $extractedRange] = Worksheet::extractSheetTitle($extractedRange, true); } - if ($locatedSheet !== null) { - $excel->addNamedRange(new NamedRange((string) $definedName['name'], $locatedSheet, $extractedRange, false)); + if ($locatedSheet === null && !DefinedName::testIfFormula($definedRange)) { + $definedRange = '#REF!'; } + $excel->addDefinedName(DefinedName::createInstance((string) $definedName['name'], $locatedSheet, $definedRange, false)); } } } } - if ((!$this->readDataOnly || !empty($this->loadSheetsOnly)) && isset($xmlWorkbook->bookViews->workbookView)) { - $workbookView = $xmlWorkbook->bookViews->workbookView; - - // active sheet index - $activeTab = (int) ($workbookView['activeTab']); // refers to old sheet index - - // keep active sheet index if sheet is still loaded, else first sheet is set as the active - if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { - $excel->setActiveSheetIndex($mapSheetId[$activeTab]); - } else { - if ($excel->getSheetCount() == 0) { - $excel->createSheet(); - } - $excel->setActiveSheetIndex(0); - } - - if (isset($workbookView['showHorizontalScroll'])) { - $showHorizontalScroll = (string) $workbookView['showHorizontalScroll']; - $excel->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll)); - } - - if (isset($workbookView['showVerticalScroll'])) { - $showVerticalScroll = (string) $workbookView['showVerticalScroll']; - $excel->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll)); - } - - if (isset($workbookView['showSheetTabs'])) { - $showSheetTabs = (string) $workbookView['showSheetTabs']; - $excel->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs)); - } - - if (isset($workbookView['minimized'])) { - $minimized = (string) $workbookView['minimized']; - $excel->setMinimized($this->castXsdBooleanToBool($minimized)); - } - - if (isset($workbookView['autoFilterDateGrouping'])) { - $autoFilterDateGrouping = (string) $workbookView['autoFilterDateGrouping']; - $excel->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping)); - } - - if (isset($workbookView['firstSheet'])) { - $firstSheet = (string) $workbookView['firstSheet']; - $excel->setFirstSheetIndex((int) $firstSheet); - } - - if (isset($workbookView['visibility'])) { - $visibility = (string) $workbookView['visibility']; - $excel->setVisibility($visibility); - } - - if (isset($workbookView['tabRatio'])) { - $tabRatio = (string) $workbookView['tabRatio']; - $excel->setTabRatio((int) $tabRatio); - } - } + (new WorkbookView($excel))->viewSettings($xmlWorkbook, $mainNS, $mapSheetId, $this->readDataOnly); break; } } if (!$this->readDataOnly) { - $contentTypes = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, '[Content_Types].xml') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $contentTypes = $this->loadZip('[Content_Types].xml'); // Default content types foreach ($contentTypes->Default as $contentType) { @@ -1499,14 +1597,8 @@ public function load($pFilename) switch ($contentType['ContentType']) { case 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml': if ($this->includeCharts) { - $chartEntryRef = ltrim($contentType['PartName'], '/'); - $chartElements = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, $chartEntryRef) - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $chartEntryRef = ltrim((string) $contentType['PartName'], '/'); + $chartElements = $this->loadZip($chartEntryRef); $objChart = Chart::readChart($chartElements, basename($chartEntryRef, '.xml')); if (isset($charts[$chartEntryRef])) { @@ -1515,7 +1607,10 @@ public function load($pFilename) $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); - $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); + if (array_key_exists('toCoordinate', $chartDetails[$chartPositionRef])) { + // For oneCellAnchor positioned charts, toCoordinate is not in the data. Does it need to be calculated? + $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); + } } } } @@ -1538,179 +1633,10 @@ public function load($pFilename) return $excel; } - private static function readColor($color, $background = false) - { - if (isset($color['rgb'])) { - return (string) $color['rgb']; - } elseif (isset($color['indexed'])) { - return Color::indexedColor($color['indexed'] - 7, $background)->getARGB(); - } elseif (isset($color['theme'])) { - if (self::$theme !== null) { - $returnColour = self::$theme->getColourByIndex((int) $color['theme']); - if (isset($color['tint'])) { - $tintAdjust = (float) $color['tint']; - $returnColour = Color::changeBrightness($returnColour, $tintAdjust); - } - - return 'FF' . $returnColour; - } - } - - if ($background) { - return 'FFFFFFFF'; - } - - return 'FF000000'; - } - /** - * @param Style $docStyle - * @param SimpleXMLElement|\stdClass $style - */ - private static function readStyle(Style $docStyle, $style) - { - $docStyle->getNumberFormat()->setFormatCode($style->numFmt); - - // font - if (isset($style->font)) { - $docStyle->getFont()->setName((string) $style->font->name['val']); - $docStyle->getFont()->setSize((string) $style->font->sz['val']); - if (isset($style->font->b)) { - $docStyle->getFont()->setBold(!isset($style->font->b['val']) || self::boolean((string) $style->font->b['val'])); - } - if (isset($style->font->i)) { - $docStyle->getFont()->setItalic(!isset($style->font->i['val']) || self::boolean((string) $style->font->i['val'])); - } - if (isset($style->font->strike)) { - $docStyle->getFont()->setStrikethrough(!isset($style->font->strike['val']) || self::boolean((string) $style->font->strike['val'])); - } - $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color)); - - if (isset($style->font->u) && !isset($style->font->u['val'])) { - $docStyle->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($style->font->u, $style->font->u['val'])) { - $docStyle->getFont()->setUnderline((string) $style->font->u['val']); - } - - if (isset($style->font->vertAlign, $style->font->vertAlign['val'])) { - $vertAlign = strtolower((string) $style->font->vertAlign['val']); - if ($vertAlign == 'superscript') { - $docStyle->getFont()->setSuperscript(true); - } - if ($vertAlign == 'subscript') { - $docStyle->getFont()->setSubscript(true); - } - } - } - - // fill - if (isset($style->fill)) { - if ($style->fill->gradientFill) { - /** @var SimpleXMLElement $gradientFill */ - $gradientFill = $style->fill->gradientFill[0]; - if (!empty($gradientFill['type'])) { - $docStyle->getFill()->setFillType((string) $gradientFill['type']); - } - $docStyle->getFill()->setRotation((float) ($gradientFill['degree'])); - $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); - $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); - } elseif ($style->fill->patternFill) { - $patternType = (string) $style->fill->patternFill['patternType'] != '' ? (string) $style->fill->patternFill['patternType'] : 'solid'; - $docStyle->getFill()->setFillType($patternType); - if ($style->fill->patternFill->fgColor) { - $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true)); - } - if ($style->fill->patternFill->bgColor) { - $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true)); - } - } - } - - // border - if (isset($style->border)) { - $diagonalUp = self::boolean((string) $style->border['diagonalUp']); - $diagonalDown = self::boolean((string) $style->border['diagonalDown']); - if (!$diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_NONE); - } elseif ($diagonalUp && !$diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_UP); - } elseif (!$diagonalUp && $diagonalDown) { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_DOWN); - } else { - $docStyle->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH); - } - self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left); - self::readBorder($docStyle->getBorders()->getRight(), $style->border->right); - self::readBorder($docStyle->getBorders()->getTop(), $style->border->top); - self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); - self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); - } - - // alignment - if (isset($style->alignment)) { - $docStyle->getAlignment()->setHorizontal((string) $style->alignment['horizontal']); - $docStyle->getAlignment()->setVertical((string) $style->alignment['vertical']); - - $textRotation = 0; - if ((int) $style->alignment['textRotation'] <= 90) { - $textRotation = (int) $style->alignment['textRotation']; - } elseif ((int) $style->alignment['textRotation'] > 90) { - $textRotation = 90 - (int) $style->alignment['textRotation']; - } - - $docStyle->getAlignment()->setTextRotation((int) $textRotation); - $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment['wrapText'])); - $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment['shrinkToFit'])); - $docStyle->getAlignment()->setIndent((int) ((string) $style->alignment['indent']) > 0 ? (int) ((string) $style->alignment['indent']) : 0); - $docStyle->getAlignment()->setReadOrder((int) ((string) $style->alignment['readingOrder']) > 0 ? (int) ((string) $style->alignment['readingOrder']) : 0); - } - - // protection - if (isset($style->protection)) { - if (isset($style->protection['locked'])) { - if (self::boolean((string) $style->protection['locked'])) { - $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); - } - } - - if (isset($style->protection['hidden'])) { - if (self::boolean((string) $style->protection['hidden'])) { - $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED); - } else { - $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED); - } - } - } - - // top-level style settings - if (isset($style->quotePrefix)) { - $docStyle->setQuotePrefix($style->quotePrefix); - } - } - - /** - * @param Border $docBorder - * @param SimpleXMLElement $eleBorder - */ - private static function readBorder(Border $docBorder, $eleBorder) - { - if (isset($eleBorder['style'])) { - $docBorder->setBorderStyle((string) $eleBorder['style']); - } - if (isset($eleBorder->color)) { - $docBorder->getColor()->setARGB(self::readColor($eleBorder->color)); - } - } - - /** - * @param SimpleXMLElement | null $is - * * @return RichText */ - private function parseRichText($is) + private function parseRichText(?SimpleXMLElement $is) { $value = new RichText(); @@ -1718,46 +1644,75 @@ private function parseRichText($is) $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $is->t)); } else { if (is_object($is->r)) { + + /** @var SimpleXMLElement $run */ foreach ($is->r as $run) { if (!isset($run->rPr)) { $value->createText(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); } else { $objText = $value->createTextRun(StringHelper::controlCharacterOOXML2PHP((string) $run->t)); - if (isset($run->rPr->rFont['val'])) { - $objText->getFont()->setName((string) $run->rPr->rFont['val']); + if (isset($run->rPr->rFont)) { + $attr = $run->rPr->rFont->attributes(); + if (isset($attr['val'])) { + $objText->getFont()->setName((string) $attr['val']); + } } - if (isset($run->rPr->sz['val'])) { - $objText->getFont()->setSize((float) $run->rPr->sz['val']); + if (isset($run->rPr->sz)) { + $attr = $run->rPr->sz->attributes(); + if (isset($attr['val'])) { + $objText->getFont()->setSize((float) $attr['val']); + } } if (isset($run->rPr->color)) { - $objText->getFont()->setColor(new Color(self::readColor($run->rPr->color))); + $objText->getFont()->setColor(new Color($this->styleReader->readColor($run->rPr->color))); } - if ((isset($run->rPr->b['val']) && self::boolean((string) $run->rPr->b['val'])) || - (isset($run->rPr->b) && !isset($run->rPr->b['val']))) { - $objText->getFont()->setBold(true); - } - if ((isset($run->rPr->i['val']) && self::boolean((string) $run->rPr->i['val'])) || - (isset($run->rPr->i) && !isset($run->rPr->i['val']))) { - $objText->getFont()->setItalic(true); + if (isset($run->rPr->b)) { + $attr = $run->rPr->b->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setBold(true); + } } - if (isset($run->rPr->vertAlign, $run->rPr->vertAlign['val'])) { - $vertAlign = strtolower((string) $run->rPr->vertAlign['val']); - if ($vertAlign == 'superscript') { - $objText->getFont()->setSuperscript(true); + if (isset($run->rPr->i)) { + $attr = $run->rPr->i->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setItalic(true); } - if ($vertAlign == 'subscript') { - $objText->getFont()->setSubscript(true); + } + if (isset($run->rPr->vertAlign)) { + $attr = $run->rPr->vertAlign->attributes(); + if (isset($attr['val'])) { + $vertAlign = strtolower((string) $attr['val']); + if ($vertAlign == 'superscript') { + $objText->getFont()->setSuperscript(true); + } + if ($vertAlign == 'subscript') { + $objText->getFont()->setSubscript(true); + } } } - if (isset($run->rPr->u) && !isset($run->rPr->u['val'])) { - $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); - } elseif (isset($run->rPr->u, $run->rPr->u['val'])) { - $objText->getFont()->setUnderline((string) $run->rPr->u['val']); + if (isset($run->rPr->u)) { + $attr = $run->rPr->u->attributes(); + if (!isset($attr['val'])) { + $objText->getFont()->setUnderline(\PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE); + } else { + $objText->getFont()->setUnderline((string) $attr['val']); + } } - if ((isset($run->rPr->strike['val']) && self::boolean((string) $run->rPr->strike['val'])) || - (isset($run->rPr->strike) && !isset($run->rPr->strike['val']))) { - $objText->getFont()->setStrikethrough(true); + if (isset($run->rPr->strike)) { + $attr = $run->rPr->strike->attributes(); + if ( + (isset($attr['val']) && self::boolean((string) $attr['val'])) || + (!isset($attr['val'])) + ) { + $objText->getFont()->setStrikethrough(true); + } } } } @@ -1767,12 +1722,7 @@ private function parseRichText($is) return $value; } - /** - * @param Spreadsheet $excel - * @param mixed $customUITarget - * @param mixed $zip - */ - private function readRibbon(Spreadsheet $excel, $customUITarget, $zip) + private function readRibbon(Spreadsheet $excel, string $customUITarget, ZipArchive $zip): void { $baseDir = dirname($customUITarget); $nameCustomUI = basename($customUITarget); @@ -1793,7 +1743,7 @@ private function readRibbon(Spreadsheet $excel, $customUITarget, $zip) if (false !== $UIRels) { // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image foreach ($UIRels->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/image') { // an image ? $customUIImagesNames[(string) $ele['Id']] = (string) $ele['Target']; $customUIImagesBinaries[(string) $ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); @@ -1873,70 +1823,73 @@ private static function boolean($value) } /** - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing - * @param \SimpleXMLElement $cellAnchor * @param array $hyperlinks */ - private function readHyperLinkDrawing($objDrawing, $cellAnchor, $hyperlinks) + private function readHyperLinkDrawing(\PhpOffice\PhpSpreadsheet\Worksheet\Drawing $objDrawing, SimpleXMLElement $cellAnchor, $hyperlinks): void { - $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children('http://schemas.openxmlformats.org/drawingml/2006/main')->hlinkClick; + $hlinkClick = $cellAnchor->pic->nvPicPr->cNvPr->children(Namespaces::DRAWINGML)->hlinkClick; if ($hlinkClick->count() === 0) { return; } - $hlinkId = (string) $hlinkClick->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships')['id']; + $hlinkId = (string) self::getAttributes($hlinkClick, Namespaces::SCHEMA_OFFICE_DOCUMENT)['id']; $hyperlink = new Hyperlink( $hyperlinks[$hlinkId], - (string) self::getArrayItem($cellAnchor->pic->nvPicPr->cNvPr->attributes(), 'name') + (string) self::getArrayItem(self::getAttributes($cellAnchor->pic->nvPicPr->cNvPr), 'name') ); $objDrawing->setHyperlink($hyperlink); } - private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook) + private function readProtection(Spreadsheet $excel, SimpleXMLElement $xmlWorkbook): void { if (!$xmlWorkbook->workbookProtection) { return; } - if ($xmlWorkbook->workbookProtection['lockRevision']) { - $excel->getSecurity()->setLockRevision((bool) $xmlWorkbook->workbookProtection['lockRevision']); - } + $excel->getSecurity()->setLockRevision(self::getLockValue($xmlWorkbook->workbookProtection, 'lockRevision')); + $excel->getSecurity()->setLockStructure(self::getLockValue($xmlWorkbook->workbookProtection, 'lockStructure')); + $excel->getSecurity()->setLockWindows(self::getLockValue($xmlWorkbook->workbookProtection, 'lockWindows')); - if ($xmlWorkbook->workbookProtection['lockStructure']) { - $excel->getSecurity()->setLockStructure((bool) $xmlWorkbook->workbookProtection['lockStructure']); + if ($xmlWorkbook->workbookProtection['revisionsPassword']) { + $excel->getSecurity()->setRevisionsPassword( + (string) $xmlWorkbook->workbookProtection['revisionsPassword'], + true + ); } - if ($xmlWorkbook->workbookProtection['lockWindows']) { - $excel->getSecurity()->setLockWindows((bool) $xmlWorkbook->workbookProtection['lockWindows']); + if ($xmlWorkbook->workbookProtection['workbookPassword']) { + $excel->getSecurity()->setWorkbookPassword( + (string) $xmlWorkbook->workbookProtection['workbookPassword'], + true + ); } + } - if ($xmlWorkbook->workbookProtection['revisionsPassword']) { - $excel->getSecurity()->setRevisionsPassword((string) $xmlWorkbook->workbookProtection['revisionsPassword'], true); + private static function getLockValue(SimpleXmlElement $protection, string $key): ?bool + { + $returnValue = null; + $protectKey = $protection[$key]; + if (!empty($protectKey)) { + $protectKey = (string) $protectKey; + $returnValue = $protectKey !== 'false' && (bool) $protectKey; } - if ($xmlWorkbook->workbookProtection['workbookPassword']) { - $excel->getSecurity()->setWorkbookPassword((string) $xmlWorkbook->workbookProtection['workbookPassword'], true); - } + return $returnValue; } - private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData) + private function readFormControlProperties(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void { + $zip = $this->zip; if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { return; } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $ctrlProps = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/ctrlProp') { $ctrlProps[(string) $ele['Id']] = $ele; } } @@ -1952,30 +1905,25 @@ private function readFormControlProperties(Spreadsheet $excel, ZipArchive $zip, unset($unparsedCtrlProps); } - private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData) + private function readPrinterSettings(Spreadsheet $excel, $dir, $fileWorksheet, $docSheet, array &$unparsedLoadedData): void { + $zip = $this->zip; if (!$zip->locateName(dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels')) { return; } - //~ http://schemas.openxmlformats.org/package/2006/relationships" - $relsWorksheet = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); + $filename = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + $relsWorksheet = $this->loadZipNoNamespace($filename, Namespaces::RELATIONSHIPS); $sheetPrinterSettings = []; foreach ($relsWorksheet->Relationship as $ele) { - if ($ele['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings') { + if ((string) $ele['Type'] === Namespaces::SCHEMA_OFFICE_DOCUMENT . '/printerSettings') { $sheetPrinterSettings[(string) $ele['Id']] = $ele; } } $unparsedPrinterSettings = &$unparsedLoadedData['sheets'][$docSheet->getCodeName()]['printerSettings']; foreach ($sheetPrinterSettings as $rId => $printerSettings) { - $rId = substr($rId, 3); // rIdXXX + $rId = substr($rId, 3) . 'ps'; // rIdXXX, add 'ps' suffix to avoid identical resource identifier collision with unparsed vmlDrawing $unparsedPrinterSettings[$rId] = []; $unparsedPrinterSettings[$rId]['filePath'] = self::dirAdd("$dir/$fileWorksheet", $printerSettings['Target']); $unparsedPrinterSettings[$rId]['relFilePath'] = (string) $printerSettings['Target']; @@ -1984,60 +1932,131 @@ private function readPrinterSettings(Spreadsheet $excel, ZipArchive $zip, $dir, unset($unparsedPrinterSettings); } - /** - * Convert an 'xsd:boolean' XML value to a PHP boolean value. - * A valid 'xsd:boolean' XML value can be one of the following - * four values: 'true', 'false', '1', '0'. It is case sensitive. - * - * Note that just doing '(bool) $xsdBoolean' is not safe, - * since '(bool) "false"' returns true. - * - * @see https://www.w3.org/TR/xmlschema11-2/#boolean - * - * @param string $xsdBoolean An XML string value of type 'xsd:boolean' - * - * @return bool Boolean value - */ - private function castXsdBooleanToBool($xsdBoolean) + private function getWorkbookBaseName(): array { - if ($xsdBoolean === 'false') { - return false; + $workbookBasename = ''; + $xmlNamespaceBase = ''; + + // check if it is an OOXML archive + $rels = $this->loadZip(self::INITIAL_FILE); + foreach ($rels->children(Namespaces::RELATIONSHIPS)->Relationship as $rel) { + $rel = self::getAttributes($rel); + $type = (string) $rel['Type']; + switch ($type) { + case Namespaces::OFFICE_DOCUMENT: + case Namespaces::PURL_OFFICE_DOCUMENT: + $basename = basename((string) $rel['Target']); + $xmlNamespaceBase = dirname($type); + if (preg_match('/workbook.*\.xml/', $basename)) { + $workbookBasename = $basename; + } + + break; + } } - return (bool) $xsdBoolean; + return [$workbookBasename, $xmlNamespaceBase]; } - /** - * @param ZipArchive $zip Opened zip archive - * - * @return string basename of the used excel workbook - */ - private function getWorkbookBaseName(ZipArchive $zip) + private function readSheetProtection(Worksheet $docSheet, SimpleXMLElement $xmlSheet): void { - $workbookBasename = ''; + if ($this->readDataOnly || !$xmlSheet->sheetProtection) { + return; + } - // check if it is an OOXML archive - $rels = simplexml_load_string( - $this->securityScanner->scan( - $this->getFromZipArchive($zip, '_rels/.rels') - ), - 'SimpleXMLElement', - Settings::getLibXmlLoaderOptions() - ); - if ($rels !== false) { - foreach ($rels->Relationship as $rel) { - switch ($rel['Type']) { - case 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument': - $basename = basename($rel['Target']); - if (preg_match('/workbook.*\.xml/', $basename)) { - $workbookBasename = $basename; + $algorithmName = (string) $xmlSheet->sheetProtection['algorithmName']; + $protection = $docSheet->getProtection(); + $protection->setAlgorithm($algorithmName); + + if ($algorithmName) { + $protection->setPassword((string) $xmlSheet->sheetProtection['hashValue'], true); + $protection->setSalt((string) $xmlSheet->sheetProtection['saltValue']); + $protection->setSpinCount((int) $xmlSheet->sheetProtection['spinCount']); + } else { + $protection->setPassword((string) $xmlSheet->sheetProtection['password'], true); + } + + if ($xmlSheet->protectedRanges->protectedRange) { + foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { + $docSheet->protectCells((string) $protectedRange['sqref'], (string) $protectedRange['password'], true); + } + } + } + + private function readAutoFilterTables( + SimpleXMLElement $xmlSheet, + Worksheet $docSheet, + string $dir, + string $fileWorksheet, + ZipArchive $zip + ): void { + if ($xmlSheet && $xmlSheet->autoFilter) { + // In older files, autofilter structure is defined in the worksheet file + (new AutoFilter($docSheet, $xmlSheet))->load(); + } elseif ($xmlSheet && $xmlSheet->tableParts && $xmlSheet->tableParts['count'] > 0) { + // But for Office365, MS decided to make it all just a bit more complicated + $this->readAutoFilterTablesInTablesFile($xmlSheet, $dir, $fileWorksheet, $zip, $docSheet); + } + } + + private function readAutoFilterTablesInTablesFile( + SimpleXMLElement $xmlSheet, + string $dir, + string $fileWorksheet, + ZipArchive $zip, + Worksheet $docSheet + ): void { + foreach ($xmlSheet->tableParts->tablePart as $tablePart) { + $relation = self::getAttributes($tablePart, Namespaces::SCHEMA_OFFICE_DOCUMENT); + $tablePartRel = (string) $relation['id']; + $relationsFileName = dirname("$dir/$fileWorksheet") . '/_rels/' . basename($fileWorksheet) . '.rels'; + + if ($zip->locateName($relationsFileName)) { + $relsTableReferences = $this->loadZip($relationsFileName, Namespaces::RELATIONSHIPS); + foreach ($relsTableReferences->Relationship as $relationship) { + $relationshipAttributes = self::getAttributes($relationship, ''); + + if ((string) $relationshipAttributes['Id'] === $tablePartRel) { + $relationshipFileName = (string) $relationshipAttributes['Target']; + $relationshipFilePath = dirname("$dir/$fileWorksheet") . '/' . $relationshipFileName; + $relationshipFilePath = File::realpath($relationshipFilePath); + + if ($this->fileExistsInArchive($this->zip, $relationshipFilePath)) { + $autoFilter = $this->loadZip($relationshipFilePath); + (new AutoFilter($docSheet, $autoFilter))->load(); } + } + } + } + } + } - break; + private static function extractStyles(?SimpleXMLElement $sxml, string $node1, string $node2): array + { + $array = []; + if ($sxml && $sxml->{$node1}->{$node2}) { + foreach ($sxml->{$node1}->{$node2} as $node) { + $array[] = $node; + } + } + + return $array; + } + + private static function extractPalette(?SimpleXMLElement $sxml): array + { + $array = []; + if ($sxml && $sxml->colors->indexedColors) { + foreach ($sxml->colors->indexedColors->rgbColor as $node) { + if ($node !== null) { + $attr = $node->attributes(); + if (isset($attr['rgb'])) { + $array[] = (string) $attr['rgb']; + } } } } - return $workbookBasename; + return (count($array) === 64) ? $array : []; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php index 69d5f69e..fdc56ce1 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/AutoFilter.php @@ -5,6 +5,7 @@ use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class AutoFilter { @@ -12,22 +13,22 @@ class AutoFilter private $worksheetXml; - public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXml) + public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } - public function load() + public function load(): void { // Remove all "$" in the auto filter range - $autoFilterRange = preg_replace('/\$/', '', $this->worksheetXml->autoFilter['ref']); + $autoFilterRange = preg_replace('/\$/', '', $this->worksheetXml->autoFilter['ref'] ?? ''); if (strpos($autoFilterRange, ':') !== false) { $this->readAutoFilter($autoFilterRange, $this->worksheetXml); } } - private function readAutoFilter($autoFilterRange, $xmlSheet) + private function readAutoFilter($autoFilterRange, $xmlSheet): void { $autoFilter = $this->worksheet->getAutoFilter(); $autoFilter->setRange($autoFilterRange); @@ -60,9 +61,10 @@ private function readAutoFilter($autoFilterRange, $xmlSheet) // Check for dynamic filters $this->readTopTenAutoFilter($filterColumn, $column); } + $autoFilter->setEvaluated(true); } - private function readDateRangeAutoFilter(\SimpleXMLElement $filters, Column $column) + private function readDateRangeAutoFilter(SimpleXMLElement $filters, Column $column): void { foreach ($filters->dateGroupItem as $dateGroupItem) { // Operator is undefined, but always treated as EQUAL @@ -81,14 +83,14 @@ private function readDateRangeAutoFilter(\SimpleXMLElement $filters, Column $col } } - private function readCustomAutoFilter(\SimpleXMLElement $filterColumn, Column $column) + private function readCustomAutoFilter(SimpleXMLElement $filterColumn, Column $column): void { if ($filterColumn->customFilters) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); $customFilters = $filterColumn->customFilters; // Custom filters can an AND or an OR join; // and there should only ever be one or two entries - if ((isset($customFilters['and'])) && ($customFilters['and'] == 1)) { + if ((isset($customFilters['and'])) && ((string) $customFilters['and'] === '1')) { $column->setJoin(Column::AUTOFILTER_COLUMN_JOIN_AND); } foreach ($customFilters->customFilter as $filterRule) { @@ -100,7 +102,7 @@ private function readCustomAutoFilter(\SimpleXMLElement $filterColumn, Column $c } } - private function readDynamicAutoFilter(\SimpleXMLElement $filterColumn, Column $column) + private function readDynamicAutoFilter(SimpleXMLElement $filterColumn, Column $column): void { if ($filterColumn->dynamicFilter) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); @@ -122,19 +124,21 @@ private function readDynamicAutoFilter(\SimpleXMLElement $filterColumn, Column $ } } - private function readTopTenAutoFilter(\SimpleXMLElement $filterColumn, Column $column) + private function readTopTenAutoFilter(SimpleXMLElement $filterColumn, Column $column): void { if ($filterColumn->top10) { $column->setFilterType(Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); // We should only ever have one top10 filter foreach ($filterColumn->top10 as $filterRule) { $column->createRule()->setRule( - (((isset($filterRule['percent'])) && ($filterRule['percent'] == 1)) + ( + ((isset($filterRule['percent'])) && ((string) $filterRule['percent'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE ), (string) $filterRule['val'], - (((isset($filterRule['top'])) && ($filterRule['top'] == 1)) + ( + ((isset($filterRule['top'])) && ((string) $filterRule['top'] === '1')) ? Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP : Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM ) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php index 2b920d70..a5635128 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Chart.php @@ -2,7 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Chart\DataSeries; use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues; use PhpOffice\PhpSpreadsheet\Chart\Layout; @@ -17,7 +17,6 @@ class Chart { /** - * @param SimpleXMLElement $component * @param string $name * @param string $format * @@ -32,7 +31,9 @@ private static function getAttribute(SimpleXMLElement $component, $name, $format } elseif ($format == 'integer') { return (int) $attributes[$name]; } elseif ($format == 'boolean') { - return (bool) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true; + $value = (string) $attributes[$name]; + + return $value === 'true' || $value === '1'; } return (float) $attributes[$name]; @@ -51,7 +52,6 @@ private static function readColor($color, $background = false) } /** - * @param SimpleXMLElement $chartElements * @param string $chartName * * @return \PhpOffice\PhpSpreadsheet\Chart\Chart @@ -63,7 +63,7 @@ public static function readChart(SimpleXMLElement $chartElements, $chartName) $XaxisLabel = $YaxisLabel = $legend = $title = null; $dispBlanksAs = $plotVisOnly = null; - + $plotArea = null; foreach ($chartElementsC as $chartElementKey => $chartElement) { switch ($chartElementKey) { case 'chart': @@ -92,8 +92,22 @@ public static function readChart(SimpleXMLElement $chartElements, $chartName) break; case 'valAx': - if (isset($chartDetail->title)) { - $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta); + if (isset($chartDetail->title, $chartDetail->axPos)) { + $axisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta); + $axPos = self::getAttribute($chartDetail->axPos, 'val', 'string'); + + switch ($axPos) { + case 't': + case 'b': + $XaxisLabel = $axisLabel; + + break; + case 'r': + case 'l': + $YaxisLabel = $axisLabel; + + break; + } } break; @@ -330,26 +344,51 @@ private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartM { if (isset($seriesDetail->strRef)) { $seriesSource = (string) $seriesDetail->strRef->f; - $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); + + if (isset($seriesDetail->strRef->strCache)) { + $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + return $seriesValues; } elseif (isset($seriesDetail->numRef)) { $seriesSource = (string) $seriesDetail->numRef->f; - $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, null, null, null, $marker); + if (isset($seriesDetail->numRef->numCache)) { + $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_NUMBER, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + return $seriesValues; } elseif (isset($seriesDetail->multiLvlStrRef)) { $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; - $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); - $seriesData['pointCount'] = count($seriesData['dataValues']); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); + + if (isset($seriesDetail->multiLvlStrRef->multiLvlStrCache)) { + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + return $seriesValues; } elseif (isset($seriesDetail->multiLvlNumRef)) { $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; - $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); - $seriesData['pointCount'] = count($seriesData['dataValues']); + $seriesValues = new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, null, null, null, $marker); + + if (isset($seriesDetail->multiLvlNumRef->multiLvlNumCache)) { + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); + $seriesValues + ->setFormatCode($seriesData['formatCode']) + ->setDataValues($seriesData['dataValues']); + } - return new DataSeriesValues(DataSeriesValues::DATASERIES_TYPE_STRING, $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker); + return $seriesValues; } return null; @@ -375,7 +414,7 @@ private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n') $pointVal = self::getAttribute($seriesValue, 'idx', 'integer'); if ($dataType == 's') { $seriesVal[$pointVal] = (string) $seriesValue->v; - } elseif ($seriesValue->v === Functions::NA()) { + } elseif ($seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal] = (float) $seriesValue->v; @@ -413,7 +452,7 @@ private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataTy $pointVal = self::getAttribute($seriesValue, 'idx', 'integer'); if ($dataType == 's') { $seriesVal[$pointVal][] = (string) $seriesValue->v; - } elseif ($seriesValue->v === Functions::NA()) { + } elseif ($seriesValue->v === ExcelError::NA()) { $seriesVal[$pointVal] = null; } else { $seriesVal[$pointVal][] = (float) $seriesValue->v; @@ -445,7 +484,7 @@ private static function parseRichText(SimpleXMLElement $titleDetailPart) } $fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer')); - if ($fontSize !== null) { + if (is_int($fontSize)) { $objText->getFont()->setSize(floor($fontSize / 100)); } @@ -502,7 +541,7 @@ private static function readChartAttributes($chartDetail) { $plotAttributes = []; if (isset($chartDetail->dLbls)) { - if (isset($chartDetail->dLbls->howLegendKey)) { + if (isset($chartDetail->dLbls->showLegendKey)) { $plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); } if (isset($chartDetail->dLbls->showVal)) { @@ -529,10 +568,9 @@ private static function readChartAttributes($chartDetail) } /** - * @param Layout $plotArea * @param mixed $plotAttributes */ - private static function setChartAttributes(Layout $plotArea, $plotAttributes) + private static function setChartAttributes(Layout $plotArea, $plotAttributes): void { foreach ($plotAttributes as $plotAttributeKey => $plotAttributeValue) { switch ($plotAttributeKey) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php index e901d990..2a1e2afd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ColumnAndRowAttributes.php @@ -3,8 +3,10 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter; use PhpOffice\PhpSpreadsheet\Reader\IReadFilter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class ColumnAndRowAttributes extends BaseParserClass { @@ -12,7 +14,7 @@ class ColumnAndRowAttributes extends BaseParserClass private $worksheetXml; - public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXml = null) + public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; @@ -25,7 +27,7 @@ public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXm * @param array $columnAttributes array of attributes (indexes are attribute name, values are value) * 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'width', ... ? */ - private function setColumnAttributes($columnAddress, array $columnAttributes) + private function setColumnAttributes($columnAddress, array $columnAttributes): void { if (isset($columnAttributes['xfIndex'])) { $this->worksheet->getColumnDimension($columnAddress)->setXfIndex($columnAttributes['xfIndex']); @@ -51,7 +53,7 @@ private function setColumnAttributes($columnAddress, array $columnAttributes) * @param array $rowAttributes array of attributes (indexes are attribute name, values are value) * 'xfIndex', 'visible', 'collapsed', 'outlineLevel', 'rowHeight', ... ? */ - private function setRowAttributes($rowNumber, array $rowAttributes) + private function setRowAttributes($rowNumber, array $rowAttributes): void { if (isset($rowAttributes['xfIndex'])) { $this->worksheet->getRowDimension($rowNumber)->setXfIndex($rowAttributes['xfIndex']); @@ -70,11 +72,7 @@ private function setRowAttributes($rowNumber, array $rowAttributes) } } - /** - * @param IReadFilter $readFilter - * @param bool $readDataOnly - */ - public function load(IReadFilter $readFilter = null, $readDataOnly = false) + public function load(?IReadFilter $readFilter = null, bool $readDataOnly = false): void { if ($this->worksheetXml === null) { return; @@ -90,11 +88,17 @@ public function load(IReadFilter $readFilter = null, $readDataOnly = false) $rowsAttributes = $this->readRowAttributes($this->worksheetXml->sheetData->row, $readDataOnly); } + if ($readFilter !== null && get_class($readFilter) === DefaultReadFilter::class) { + $readFilter = null; + } + // set columns/rows attributes $columnsAttributesAreSet = []; foreach ($columnsAttributes as $columnCoordinate => $columnAttributes) { - if ($readFilter === null || - !$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes)) { + if ( + $readFilter === null || + !$this->isFilteredColumn($readFilter, $columnCoordinate, $rowsAttributes) + ) { if (!isset($columnsAttributesAreSet[$columnCoordinate])) { $this->setColumnAttributes($columnCoordinate, $columnAttributes); $columnsAttributesAreSet[$columnCoordinate] = true; @@ -104,8 +108,10 @@ public function load(IReadFilter $readFilter = null, $readDataOnly = false) $rowsAttributesAreSet = []; foreach ($rowsAttributes as $rowCoordinate => $rowAttributes) { - if ($readFilter === null || - !$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes)) { + if ( + $readFilter === null || + !$this->isFilteredRow($readFilter, $rowCoordinate, $columnsAttributes) + ) { if (!isset($rowsAttributesAreSet[$rowCoordinate])) { $this->setRowAttributes($rowCoordinate, $rowAttributes); $rowsAttributesAreSet[$rowCoordinate] = true; @@ -125,7 +131,7 @@ private function isFilteredColumn(IReadFilter $readFilter, $columnCoordinate, ar return false; } - private function readColumnAttributes(\SimpleXMLElement $worksheetCols, $readDataOnly) + private function readColumnAttributes(SimpleXMLElement $worksheetCols, $readDataOnly) { $columnAttributes = []; @@ -145,7 +151,7 @@ private function readColumnAttributes(\SimpleXMLElement $worksheetCols, $readDat return $columnAttributes; } - private function readColumnRangeAttributes(\SimpleXMLElement $column, $readDataOnly) + private function readColumnRangeAttributes(SimpleXMLElement $column, $readDataOnly) { $columnAttributes = []; @@ -177,7 +183,7 @@ private function isFilteredRow(IReadFilter $readFilter, $rowCoordinate, array $c return false; } - private function readRowAttributes(\SimpleXMLElement $worksheetRow, $readDataOnly) + private function readRowAttributes(SimpleXMLElement $worksheetRow, $readDataOnly) { $rowAttributes = []; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php index 722b7795..c631a0fe 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/ConditionalStyles.php @@ -2,8 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles as StyleReader; use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormatValueObject; +use PhpOffice\PhpSpreadsheet\Style\Style as Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class ConditionalStyles { @@ -11,35 +17,143 @@ class ConditionalStyles private $worksheetXml; + /** + * @var array + */ + private $ns; + private $dxfs; - public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXml, array $dxfs = []) + public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml, array $dxfs = []) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; $this->dxfs = $dxfs; } - public function load() + public function load(): void { $this->setConditionalStyles( $this->worksheet, - $this->readConditionalStyles($this->worksheetXml) + $this->readConditionalStyles($this->worksheetXml), + $this->worksheetXml->extLst + ); + } + + public function loadFromExt(StyleReader $styleReader): void + { + $this->ns = $this->worksheetXml->getNamespaces(true); + $this->setConditionalsFromExt( + $this->readConditionalsFromExt($this->worksheetXml->extLst, $styleReader) ); } - private function readConditionalStyles($xmlSheet) + private function setConditionalsFromExt(array $conditionals): void + { + foreach ($conditionals as $conditionalRange => $cfRules) { + ksort($cfRules); + // Priority is used as the key for sorting; but may not start at 0, + // so we use array_values to reset the index after sorting. + $this->worksheet->getStyle($conditionalRange) + ->setConditionalStyles(array_values($cfRules)); + } + } + + private function readConditionalsFromExt(SimpleXMLElement $extLst, StyleReader $styleReader): array + { + $conditionals = []; + + if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { + $conditionalFormattingRuleXml = $extLst->ext->children($this->ns['x14']); + if (!$conditionalFormattingRuleXml->conditionalFormattings) { + return []; + } + + foreach ($conditionalFormattingRuleXml->children($this->ns['x14']) as $extFormattingXml) { + $extFormattingRangeXml = $extFormattingXml->children($this->ns['xm']); + if (!$extFormattingRangeXml->sqref) { + continue; + } + + $sqref = (string) $extFormattingRangeXml->sqref; + $extCfRuleXml = $extFormattingXml->cfRule; + + $attributes = $extCfRuleXml->attributes(); + if (!$attributes) { + continue; + } + $conditionType = (string) $attributes->type; + if ( + !Conditional::isValidConditionType($conditionType) || + $conditionType === Conditional::CONDITION_DATABAR + ) { + continue; + } + + $priority = (int) $attributes->priority; + + $conditional = $this->readConditionalRuleFromExt($extCfRuleXml, $attributes); + $cfStyle = $this->readStyleFromExt($extCfRuleXml, $styleReader); + $conditional->setStyle($cfStyle); + $conditionals[$sqref][$priority] = $conditional; + } + } + + return $conditionals; + } + + private function readConditionalRuleFromExt(SimpleXMLElement $cfRuleXml, SimpleXMLElement $attributes): Conditional + { + $conditionType = (string) $attributes->type; + $operatorType = (string) $attributes->operator; + + $operands = []; + foreach ($cfRuleXml->children($this->ns['xm']) as $cfRuleOperandsXml) { + $operands[] = (string) $cfRuleOperandsXml; + } + + $conditional = new Conditional(); + $conditional->setConditionType($conditionType); + $conditional->setOperatorType($operatorType); + if ( + $conditionType === Conditional::CONDITION_CONTAINSTEXT || + $conditionType === Conditional::CONDITION_NOTCONTAINSTEXT || + $conditionType === Conditional::CONDITION_BEGINSWITH || + $conditionType === Conditional::CONDITION_ENDSWITH || + $conditionType === Conditional::CONDITION_TIMEPERIOD + ) { + $conditional->setText(array_pop($operands) ?? ''); + } + $conditional->setConditions($operands); + + return $conditional; + } + + private function readStyleFromExt(SimpleXMLElement $extCfRuleXml, StyleReader $styleReader): Style + { + $cfStyle = new Style(false, true); + if ($extCfRuleXml->dxf) { + $styleXML = $extCfRuleXml->dxf->children(); + + if ($styleXML->borders) { + $styleReader->readBorderStyle($cfStyle->getBorders(), $styleXML->borders); + } + if ($styleXML->fill) { + $styleReader->readFillStyle($cfStyle->getFill(), $styleXML->fill); + } + } + + return $cfStyle; + } + + private function readConditionalStyles($xmlSheet): array { $conditionals = []; foreach ($xmlSheet->conditionalFormatting as $conditional) { foreach ($conditional->cfRule as $cfRule) { - if (((string) $cfRule['type'] == Conditional::CONDITION_NONE - || (string) $cfRule['type'] == Conditional::CONDITION_CELLIS - || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSTEXT - || (string) $cfRule['type'] == Conditional::CONDITION_CONTAINSBLANKS - || (string) $cfRule['type'] == Conditional::CONDITION_NOTCONTAINSBLANKS - || (string) $cfRule['type'] == Conditional::CONDITION_EXPRESSION) - && isset($this->dxfs[(int) ($cfRule['dxfId'])])) { + if (Conditional::isValidConditionType((string) $cfRule['type']) && isset($this->dxfs[(int) ($cfRule['dxfId'])])) { + $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; + } elseif ((string) $cfRule['type'] == Conditional::CONDITION_DATABAR) { $conditionals[(string) $conditional['sqref']][(int) ($cfRule['priority'])] = $cfRule; } } @@ -48,23 +162,25 @@ private function readConditionalStyles($xmlSheet) return $conditionals; } - private function setConditionalStyles(Worksheet $worksheet, array $conditionals) + private function setConditionalStyles(Worksheet $worksheet, array $conditionals, $xmlExtLst): void { - foreach ($conditionals as $ref => $cfRules) { + foreach ($conditionals as $cellRangeReference => $cfRules) { ksort($cfRules); - $conditionalStyles = $this->readStyleRules($cfRules); + $conditionalStyles = $this->readStyleRules($cfRules, $xmlExtLst); - // Extract all cell references in $ref - $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref))); + // Extract all cell references in $cellRangeReference + $cellBlocks = explode(' ', str_replace('$', '', strtoupper($cellRangeReference))); foreach ($cellBlocks as $cellBlock) { $worksheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles); } } } - private function readStyleRules($cfRules) + private function readStyleRules($cfRules, $extLst) { + $conditionalFormattingRuleExtensions = ConditionalFormattingRuleExtension::parseExtLstXml($extLst); $conditionalStyles = []; + foreach ($cfRules as $cfRule) { $objConditional = new Conditional(); $objConditional->setConditionType((string) $cfRule['type']); @@ -72,23 +188,85 @@ private function readStyleRules($cfRules) if ((string) $cfRule['text'] != '') { $objConditional->setText((string) $cfRule['text']); + } elseif ((string) $cfRule['timePeriod'] != '') { + $objConditional->setText((string) $cfRule['timePeriod']); } if (isset($cfRule['stopIfTrue']) && (int) $cfRule['stopIfTrue'] === 1) { $objConditional->setStopIfTrue(true); } - if (count($cfRule->formula) > 1) { - foreach ($cfRule->formula as $formula) { - $objConditional->addCondition((string) $formula); + if (count($cfRule->formula) >= 1) { + foreach ($cfRule->formula as $formulax) { + $formula = (string) $formulax; + if ($formula === 'TRUE') { + $objConditional->addCondition(true); + } elseif ($formula === 'FALSE') { + $objConditional->addCondition(false); + } else { + $objConditional->addCondition($formula); + } } } else { - $objConditional->addCondition((string) $cfRule->formula); + $objConditional->addCondition(''); + } + + if (isset($cfRule->dataBar)) { + $objConditional->setDataBar( + $this->readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions) + ); + } else { + $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); } - $objConditional->setStyle(clone $this->dxfs[(int) ($cfRule['dxfId'])]); + $conditionalStyles[] = $objConditional; } return $conditionalStyles; } + + private function readDataBarOfConditionalRule($cfRule, $conditionalFormattingRuleExtensions): ConditionalDataBar + { + $dataBar = new ConditionalDataBar(); + //dataBar attribute + if (isset($cfRule->dataBar['showValue'])) { + $dataBar->setShowValue((bool) $cfRule->dataBar['showValue']); + } + + //dataBar children + //conditionalFormatValueObjects + $cfvoXml = $cfRule->dataBar->cfvo; + $cfvoIndex = 0; + foreach ((count($cfvoXml) > 1 ? $cfvoXml : [$cfvoXml]) as $cfvo) { + if ($cfvoIndex === 0) { + $dataBar->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); + } + if ($cfvoIndex === 1) { + $dataBar->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $cfvo['type'], (string) $cfvo['val'])); + } + ++$cfvoIndex; + } + + //color + if (isset($cfRule->dataBar->color)) { + $dataBar->setColor((string) $cfRule->dataBar->color['rgb']); + } + //extLst + $this->readDataBarExtLstOfConditionalRule($dataBar, $cfRule, $conditionalFormattingRuleExtensions); + + return $dataBar; + } + + private function readDataBarExtLstOfConditionalRule(ConditionalDataBar $dataBar, $cfRule, $conditionalFormattingRuleExtensions): void + { + if (isset($cfRule->extLst)) { + $ns = $cfRule->extLst->getNamespaces(true); + foreach ((count($cfRule->extLst) > 0 ? $cfRule->extLst->ext : [$cfRule->extLst->ext]) as $ext) { + $extId = (string) $ext->children($ns['x14'])->id; + if (isset($conditionalFormattingRuleExtensions[$extId]) && (string) $ext['uri'] === '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}') { + $dataBar->setConditionalFormattingRuleExt($conditionalFormattingRuleExtensions[$extId]); + } + } + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php index 4bb44129..b699cb57 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/DataValidations.php @@ -4,6 +4,7 @@ use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class DataValidations { @@ -11,13 +12,13 @@ class DataValidations private $worksheetXml; - public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXml) + public function __construct(Worksheet $workSheet, SimpleXMLElement $worksheetXml) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } - public function load() + public function load(): void { foreach ($this->worksheetXml->dataValidations->dataValidation as $dataValidation) { // Uppercase coordinate @@ -33,16 +34,18 @@ public function load() $docValidation->setType((string) $dataValidation['type']); $docValidation->setErrorStyle((string) $dataValidation['errorStyle']); $docValidation->setOperator((string) $dataValidation['operator']); - $docValidation->setAllowBlank($dataValidation['allowBlank'] != 0); - $docValidation->setShowDropDown($dataValidation['showDropDown'] == 0); - $docValidation->setShowInputMessage($dataValidation['showInputMessage'] != 0); - $docValidation->setShowErrorMessage($dataValidation['showErrorMessage'] != 0); + $docValidation->setAllowBlank(filter_var($dataValidation['allowBlank'], FILTER_VALIDATE_BOOLEAN)); + // showDropDown is inverted (works as hideDropDown if true) + $docValidation->setShowDropDown(!filter_var($dataValidation['showDropDown'], FILTER_VALIDATE_BOOLEAN)); + $docValidation->setShowInputMessage(filter_var($dataValidation['showInputMessage'], FILTER_VALIDATE_BOOLEAN)); + $docValidation->setShowErrorMessage(filter_var($dataValidation['showErrorMessage'], FILTER_VALIDATE_BOOLEAN)); $docValidation->setErrorTitle((string) $dataValidation['errorTitle']); $docValidation->setError((string) $dataValidation['error']); $docValidation->setPromptTitle((string) $dataValidation['promptTitle']); $docValidation->setPrompt((string) $dataValidation['prompt']); $docValidation->setFormula1((string) $dataValidation->formula1); $docValidation->setFormula2((string) $dataValidation->formula2); + $docValidation->setSqref($range); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php index 400b2725..84884996 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Hyperlinks.php @@ -3,7 +3,9 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class Hyperlinks { @@ -16,42 +18,46 @@ public function __construct(Worksheet $workSheet) $this->worksheet = $workSheet; } - public function readHyperlinks(\SimpleXMLElement $relsWorksheet) + public function readHyperlinks(SimpleXMLElement $relsWorksheet): void { - foreach ($relsWorksheet->Relationship as $element) { - if ($element['Type'] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink') { - $this->hyperlinks[(string) $element['Id']] = (string) $element['Target']; + foreach ($relsWorksheet->children(Namespaces::RELATIONSHIPS)->Relationship as $elementx) { + $element = Xlsx::getAttributes($elementx); + if ($element->Type == Namespaces::HYPERLINK) { + $this->hyperlinks[(string) $element->Id] = (string) $element->Target; } } } - public function setHyperlinks(\SimpleXMLElement $worksheetXml) + public function setHyperlinks(SimpleXMLElement $worksheetXml): void { - foreach ($worksheetXml->hyperlink as $hyperlink) { - $this->setHyperlink($hyperlink, $this->worksheet); + foreach ($worksheetXml->children(Namespaces::MAIN)->hyperlink as $hyperlink) { + if ($hyperlink !== null) { + $this->setHyperlink($hyperlink, $this->worksheet); + } } } - private function setHyperlink(\SimpleXMLElement $hyperlink, Worksheet $worksheet) + private function setHyperlink(SimpleXMLElement $hyperlink, Worksheet $worksheet): void { // Link url - $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $linkRel = Xlsx::getAttributes($hyperlink, Namespaces::SCHEMA_OFFICE_DOCUMENT); - foreach (Coordinate::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { + $attributes = Xlsx::getAttributes($hyperlink); + foreach (Coordinate::extractAllCellReferencesInRange($attributes->ref) as $cellReference) { $cell = $worksheet->getCell($cellReference); if (isset($linkRel['id'])) { - $hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']]; - if (isset($hyperlink['location'])) { - $hyperlinkUrl .= '#' . (string) $hyperlink['location']; + $hyperlinkUrl = $this->hyperlinks[(string) $linkRel['id']] ?? null; + if (isset($attributes['location'])) { + $hyperlinkUrl .= '#' . (string) $attributes['location']; } $cell->getHyperlink()->setUrl($hyperlinkUrl); - } elseif (isset($hyperlink['location'])) { - $cell->getHyperlink()->setUrl('sheet://' . (string) $hyperlink['location']); + } elseif (isset($attributes['location'])) { + $cell->getHyperlink()->setUrl('sheet://' . (string) $attributes['location']); } // Tooltip - if (isset($hyperlink['tooltip'])) { - $cell->getHyperlink()->setTooltip((string) $hyperlink['tooltip']); + if (isset($attributes['tooltip'])) { + $cell->getHyperlink()->setTooltip((string) $attributes['tooltip']); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php new file mode 100644 index 00000000..c0713ae4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Namespaces.php @@ -0,0 +1,78 @@ +worksheet = $workSheet; $this->worksheetXml = $worksheetXml; @@ -31,7 +32,7 @@ public function load(array $unparsedLoadedData) return $unparsedLoadedData; } - private function margins(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) + private function margins(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->pageMargins) { $docPageMargins = $worksheet->getPageMargins(); @@ -44,7 +45,7 @@ private function margins(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) } } - private function pageSetup(\SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData) + private function pageSetup(SimpleXMLElement $xmlSheet, Worksheet $worksheet, array $unparsedLoadedData) { if ($xmlSheet->pageSetup) { $docPageSetup = $worksheet->getPageSetup(); @@ -64,12 +65,17 @@ private function pageSetup(\SimpleXMLElement $xmlSheet, Worksheet $worksheet, ar if (isset($xmlSheet->pageSetup['fitToWidth']) && (int) ($xmlSheet->pageSetup['fitToWidth']) >= 0) { $docPageSetup->setFitToWidth((int) ($xmlSheet->pageSetup['fitToWidth']), false); } - if (isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) && - self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber'])) { + if ( + isset($xmlSheet->pageSetup['firstPageNumber'], $xmlSheet->pageSetup['useFirstPageNumber']) && + self::boolean((string) $xmlSheet->pageSetup['useFirstPageNumber']) + ) { $docPageSetup->setFirstPageNumber((int) ($xmlSheet->pageSetup['firstPageNumber'])); } + if (isset($xmlSheet->pageSetup['pageOrder'])) { + $docPageSetup->setPageOrder((string) $xmlSheet->pageSetup['pageOrder']); + } - $relAttributes = $xmlSheet->pageSetup->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $relAttributes = $xmlSheet->pageSetup->attributes(Namespaces::SCHEMA_OFFICE_DOCUMENT); if (isset($relAttributes['id'])) { $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'] = (string) $relAttributes['id']; } @@ -78,31 +84,39 @@ private function pageSetup(\SimpleXMLElement $xmlSheet, Worksheet $worksheet, ar return $unparsedLoadedData; } - private function headerFooter(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) + private function headerFooter(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->headerFooter) { $docHeaderFooter = $worksheet->getHeaderFooter(); - if (isset($xmlSheet->headerFooter['differentOddEven']) && - self::boolean((string) $xmlSheet->headerFooter['differentOddEven'])) { + if ( + isset($xmlSheet->headerFooter['differentOddEven']) && + self::boolean((string) $xmlSheet->headerFooter['differentOddEven']) + ) { $docHeaderFooter->setDifferentOddEven(true); } else { $docHeaderFooter->setDifferentOddEven(false); } - if (isset($xmlSheet->headerFooter['differentFirst']) && - self::boolean((string) $xmlSheet->headerFooter['differentFirst'])) { + if ( + isset($xmlSheet->headerFooter['differentFirst']) && + self::boolean((string) $xmlSheet->headerFooter['differentFirst']) + ) { $docHeaderFooter->setDifferentFirst(true); } else { $docHeaderFooter->setDifferentFirst(false); } - if (isset($xmlSheet->headerFooter['scaleWithDoc']) && - !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc'])) { + if ( + isset($xmlSheet->headerFooter['scaleWithDoc']) && + !self::boolean((string) $xmlSheet->headerFooter['scaleWithDoc']) + ) { $docHeaderFooter->setScaleWithDocument(false); } else { $docHeaderFooter->setScaleWithDocument(true); } - if (isset($xmlSheet->headerFooter['alignWithMargins']) && - !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins'])) { + if ( + isset($xmlSheet->headerFooter['alignWithMargins']) && + !self::boolean((string) $xmlSheet->headerFooter['alignWithMargins']) + ) { $docHeaderFooter->setAlignWithMargins(false); } else { $docHeaderFooter->setAlignWithMargins(true); @@ -117,7 +131,7 @@ private function headerFooter(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) } } - private function pageBreaks(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) + private function pageBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { if ($xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk) { $this->rowBreaks($xmlSheet, $worksheet); @@ -127,7 +141,7 @@ private function pageBreaks(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) } } - private function rowBreaks(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) + private function rowBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->rowBreaks->brk as $brk) { if ($brk['man']) { @@ -136,7 +150,7 @@ private function rowBreaks(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) } } - private function columnBreaks(\SimpleXMLElement $xmlSheet, Worksheet $worksheet) + private function columnBreaks(SimpleXMLElement $xmlSheet, Worksheet $worksheet): void { foreach ($xmlSheet->colBreaks->brk as $brk) { if ($brk['man']) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php index bf8e57d8..82b5172b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Properties.php @@ -5,11 +5,14 @@ use PhpOffice\PhpSpreadsheet\Document\Properties as DocumentProperties; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; use PhpOffice\PhpSpreadsheet\Settings; +use SimpleXMLElement; class Properties { + /** @var XmlScanner */ private $securityScanner; + /** @var DocumentProperties */ private $docProps; public function __construct(XmlScanner $securityScanner, DocumentProperties $docProps) @@ -18,28 +21,39 @@ public function __construct(XmlScanner $securityScanner, DocumentProperties $doc $this->docProps = $docProps; } - private function extractPropertyData($propertyData) + /** + * @param mixed $obj + */ + private static function nullOrSimple($obj): ?SimpleXMLElement { - return simplexml_load_string( + return ($obj instanceof SimpleXMLElement) ? $obj : null; + } + + private function extractPropertyData(string $propertyData): ?SimpleXMLElement + { + // okay to omit namespace because everything will be processed by xpath + $obj = simplexml_load_string( $this->securityScanner->scan($propertyData), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); + + return self::nullOrSimple($obj); } - public function readCoreProperties($propertyData) + public function readCoreProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { - $xmlCore->registerXPathNamespace('dc', 'http://purl.org/dc/elements/1.1/'); - $xmlCore->registerXPathNamespace('dcterms', 'http://purl.org/dc/terms/'); - $xmlCore->registerXPathNamespace('cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); + $xmlCore->registerXPathNamespace('dc', Namespaces::DC_ELEMENTS); + $xmlCore->registerXPathNamespace('dcterms', Namespaces::DC_TERMS); + $xmlCore->registerXPathNamespace('cp', Namespaces::CORE_PROPERTIES2); $this->docProps->setCreator((string) self::getArrayItem($xmlCore->xpath('dc:creator'))); $this->docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath('cp:lastModifiedBy'))); - $this->docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:created')))); //! respect xsi:type - $this->docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath('dcterms:modified')))); //! respect xsi:type + $this->docProps->setCreated((string) self::getArrayItem($xmlCore->xpath('dcterms:created'))); //! respect xsi:type + $this->docProps->setModified((string) self::getArrayItem($xmlCore->xpath('dcterms:modified'))); //! respect xsi:type $this->docProps->setTitle((string) self::getArrayItem($xmlCore->xpath('dc:title'))); $this->docProps->setDescription((string) self::getArrayItem($xmlCore->xpath('dc:description'))); $this->docProps->setSubject((string) self::getArrayItem($xmlCore->xpath('dc:subject'))); @@ -48,7 +62,7 @@ public function readCoreProperties($propertyData) } } - public function readExtendedProperties($propertyData) + public function readExtendedProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); @@ -62,13 +76,13 @@ public function readExtendedProperties($propertyData) } } - public function readCustomProperties($propertyData) + public function readCustomProperties(string $propertyData): void { $xmlCore = $this->extractPropertyData($propertyData); if (is_object($xmlCore)) { foreach ($xmlCore as $xmlProperty) { - /** @var \SimpleXMLElement $xmlProperty */ + /** @var SimpleXMLElement $xmlProperty */ $cellDataOfficeAttributes = $xmlProperty->attributes(); if (isset($cellDataOfficeAttributes['name'])) { $propertyName = (string) $cellDataOfficeAttributes['name']; @@ -84,8 +98,12 @@ public function readCustomProperties($propertyData) } } - private static function getArrayItem(array $array, $key = 0) + /** + * @param array|false $array + * @param mixed $key + */ + private static function getArrayItem($array, $key = 0): ?SimpleXMLElement { - return $array[$key] ?? null; + return is_array($array) ? ($array[$key] ?? null) : null; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php index eb61a5d3..a302cc56 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViewOptions.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class SheetViewOptions extends BaseParserClass { @@ -10,23 +11,20 @@ class SheetViewOptions extends BaseParserClass private $worksheetXml; - public function __construct(Worksheet $workSheet, \SimpleXMLElement $worksheetXml = null) + public function __construct(Worksheet $workSheet, ?SimpleXMLElement $worksheetXml = null) { $this->worksheet = $workSheet; $this->worksheetXml = $worksheetXml; } - /** - * @param bool $readDataOnly - */ - public function load($readDataOnly = false) + public function load(bool $readDataOnly, Styles $styleReader): void { if ($this->worksheetXml === null) { return; } if (isset($this->worksheetXml->sheetPr)) { - $this->tabColor($this->worksheetXml->sheetPr); + $this->tabColor($this->worksheetXml->sheetPr, $styleReader); $this->codeName($this->worksheetXml->sheetPr); $this->outlines($this->worksheetXml->sheetPr); $this->pageSetup($this->worksheetXml->sheetPr); @@ -41,32 +39,36 @@ public function load($readDataOnly = false) } } - private function tabColor(\SimpleXMLElement $sheetPr) + private function tabColor(SimpleXMLElement $sheetPr, Styles $styleReader): void { - if (isset($sheetPr->tabColor, $sheetPr->tabColor['rgb'])) { - $this->worksheet->getTabColor()->setARGB((string) $sheetPr->tabColor['rgb']); + if (isset($sheetPr->tabColor)) { + $this->worksheet->getTabColor()->setARGB($styleReader->readColor($sheetPr->tabColor)); } } - private function codeName(\SimpleXMLElement $sheetPr) + private function codeName(SimpleXMLElement $sheetPr): void { if (isset($sheetPr['codeName'])) { $this->worksheet->setCodeName((string) $sheetPr['codeName'], false); } } - private function outlines(\SimpleXMLElement $sheetPr) + private function outlines(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->outlinePr)) { - if (isset($sheetPr->outlinePr['summaryRight']) && - !self::boolean((string) $sheetPr->outlinePr['summaryRight'])) { + if ( + isset($sheetPr->outlinePr['summaryRight']) && + !self::boolean((string) $sheetPr->outlinePr['summaryRight']) + ) { $this->worksheet->setShowSummaryRight(false); } else { $this->worksheet->setShowSummaryRight(true); } - if (isset($sheetPr->outlinePr['summaryBelow']) && - !self::boolean((string) $sheetPr->outlinePr['summaryBelow'])) { + if ( + isset($sheetPr->outlinePr['summaryBelow']) && + !self::boolean((string) $sheetPr->outlinePr['summaryBelow']) + ) { $this->worksheet->setShowSummaryBelow(false); } else { $this->worksheet->setShowSummaryBelow(true); @@ -74,11 +76,13 @@ private function outlines(\SimpleXMLElement $sheetPr) } } - private function pageSetup(\SimpleXMLElement $sheetPr) + private function pageSetup(SimpleXMLElement $sheetPr): void { if (isset($sheetPr->pageSetUpPr)) { - if (isset($sheetPr->pageSetUpPr['fitToPage']) && - !self::boolean((string) $sheetPr->pageSetUpPr['fitToPage'])) { + if ( + isset($sheetPr->pageSetUpPr['fitToPage']) && + !self::boolean((string) $sheetPr->pageSetUpPr['fitToPage']) + ) { $this->worksheet->getPageSetup()->setFitToPage(false); } else { $this->worksheet->getPageSetup()->setFitToPage(true); @@ -86,11 +90,13 @@ private function pageSetup(\SimpleXMLElement $sheetPr) } } - private function sheetFormat(\SimpleXMLElement $sheetFormatPr) + private function sheetFormat(SimpleXMLElement $sheetFormatPr): void { - if (isset($sheetFormatPr['customHeight']) && + if ( + isset($sheetFormatPr['customHeight']) && self::boolean((string) $sheetFormatPr['customHeight']) && - isset($sheetFormatPr['defaultRowHeight'])) { + isset($sheetFormatPr['defaultRowHeight']) + ) { $this->worksheet->getDefaultRowDimension() ->setRowHeight((float) $sheetFormatPr['defaultRowHeight']); } @@ -100,13 +106,15 @@ private function sheetFormat(\SimpleXMLElement $sheetFormatPr) ->setWidth((float) $sheetFormatPr['defaultColWidth']); } - if (isset($sheetFormatPr['zeroHeight']) && - ((string) $sheetFormatPr['zeroHeight'] === '1')) { + if ( + isset($sheetFormatPr['zeroHeight']) && + ((string) $sheetFormatPr['zeroHeight'] === '1') + ) { $this->worksheet->getDefaultRowDimension()->setZeroHeight(true); } } - private function printOptions(\SimpleXMLElement $printOptions) + private function printOptions(SimpleXMLElement $printOptions): void { if (self::boolean((string) $printOptions['gridLinesSet'])) { $this->worksheet->setShowGridlines(true); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php index 88c01ead..b2bc99f0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/SheetViews.php @@ -3,22 +3,31 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; +use SimpleXMLElement; class SheetViews extends BaseParserClass { + /** @var SimpleXMLElement */ private $sheetViewXml; + /** @var SimpleXMLElement */ + private $sheetViewAttributes; + + /** @var Worksheet */ private $worksheet; - public function __construct(\SimpleXMLElement $sheetViewXml, Worksheet $workSheet) + public function __construct(SimpleXMLElement $sheetViewXml, Worksheet $workSheet) { $this->sheetViewXml = $sheetViewXml; + $this->sheetViewAttributes = Xlsx::testSimpleXml($sheetViewXml->attributes()); $this->worksheet = $workSheet; } - public function load() + public function load(): void { + $this->topLeft(); $this->zoomScale(); $this->view(); $this->gridLines(); @@ -29,15 +38,15 @@ public function load() if (isset($this->sheetViewXml->pane)) { $this->pane(); } - if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection['sqref'])) { + if (isset($this->sheetViewXml->selection, $this->sheetViewXml->selection->attributes()->sqref)) { $this->selection(); } } - private function zoomScale() + private function zoomScale(): void { - if (isset($this->sheetViewXml['zoomScale'])) { - $zoomScale = (int) ($this->sheetViewXml['zoomScale']); + if (isset($this->sheetViewAttributes->zoomScale)) { + $zoomScale = (int) ($this->sheetViewAttributes->zoomScale); if ($zoomScale <= 0) { // setZoomScale will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents @@ -47,8 +56,8 @@ private function zoomScale() $this->worksheet->getSheetView()->setZoomScale($zoomScale); } - if (isset($this->sheetViewXml['zoomScaleNormal'])) { - $zoomScaleNormal = (int) ($this->sheetViewXml['zoomScaleNormal']); + if (isset($this->sheetViewAttributes->zoomScaleNormal)) { + $zoomScaleNormal = (int) ($this->sheetViewAttributes->zoomScaleNormal); if ($zoomScaleNormal <= 0) { // setZoomScaleNormal will throw an Exception if the scale is less than or equals 0 // that is OK when manually creating documents, but we should be able to read all documents @@ -59,65 +68,73 @@ private function zoomScale() } } - private function view() + private function view(): void { - if (isset($this->sheetViewXml['view'])) { - $this->worksheet->getSheetView()->setView((string) $this->sheetViewXml['view']); + if (isset($this->sheetViewAttributes->view)) { + $this->worksheet->getSheetView()->setView((string) $this->sheetViewAttributes->view); } } - private function gridLines() + private function topLeft(): void { - if (isset($this->sheetViewXml['showGridLines'])) { + if (isset($this->sheetViewAttributes->topLeftCell)) { + $this->worksheet->setTopLeftCell($this->sheetViewAttributes->topLeftCell); + } + } + + private function gridLines(): void + { + if (isset($this->sheetViewAttributes->showGridLines)) { $this->worksheet->setShowGridLines( - self::boolean((string) $this->sheetViewXml['showGridLines']) + self::boolean((string) $this->sheetViewAttributes->showGridLines) ); } } - private function headers() + private function headers(): void { - if (isset($this->sheetViewXml['showRowColHeaders'])) { + if (isset($this->sheetViewAttributes->showRowColHeaders)) { $this->worksheet->setShowRowColHeaders( - self::boolean((string) $this->sheetViewXml['showRowColHeaders']) + self::boolean((string) $this->sheetViewAttributes->showRowColHeaders) ); } } - private function direction() + private function direction(): void { - if (isset($this->sheetViewXml['rightToLeft'])) { + if (isset($this->sheetViewAttributes->rightToLeft)) { $this->worksheet->setRightToLeft( - self::boolean((string) $this->sheetViewXml['rightToLeft']) + self::boolean((string) $this->sheetViewAttributes->rightToLeft) ); } } - private function showZeros() + private function showZeros(): void { - if (isset($this->sheetViewXml['showZeros'])) { + if (isset($this->sheetViewAttributes->showZeros)) { $this->worksheet->getSheetView()->setShowZeros( - self::boolean((string) $this->sheetViewXml['showZeros']) + self::boolean((string) $this->sheetViewAttributes->showZeros) ); } } - private function pane() + private function pane(): void { $xSplit = 0; $ySplit = 0; $topLeftCell = null; + $paneAttributes = $this->sheetViewXml->pane->attributes(); - if (isset($this->sheetViewXml->pane['xSplit'])) { - $xSplit = (int) ($this->sheetViewXml->pane['xSplit']); + if (isset($paneAttributes->xSplit)) { + $xSplit = (int) ($paneAttributes->xSplit); } - if (isset($this->sheetViewXml->pane['ySplit'])) { - $ySplit = (int) ($this->sheetViewXml->pane['ySplit']); + if (isset($paneAttributes->ySplit)) { + $ySplit = (int) ($paneAttributes->ySplit); } - if (isset($this->sheetViewXml->pane['topLeftCell'])) { - $topLeftCell = (string) $this->sheetViewXml->pane['topLeftCell']; + if (isset($paneAttributes->topLeftCell)) { + $topLeftCell = (string) $paneAttributes->topLeftCell; } $this->worksheet->freezePane( @@ -126,12 +143,14 @@ private function pane() ); } - private function selection() + private function selection(): void { - $sqref = (string) $this->sheetViewXml->selection['sqref']; - $sqref = explode(' ', $sqref); - $sqref = $sqref[0]; - - $this->worksheet->setSelectedCells($sqref); + $attributes = $this->sheetViewXml->selection->attributes(); + if ($attributes !== null) { + $sqref = (string) $attributes->sqref; + $sqref = explode(' ', $sqref); + $sqref = $sqref[0]; + $this->worksheet->setSelectedCells($sqref); + } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php index 40106258..2c15c515 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Styles.php @@ -2,6 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx; +use PhpOffice\PhpSpreadsheet\Reader\Xlsx; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; @@ -11,108 +12,188 @@ use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; +use SimpleXMLElement; +use stdClass; class Styles extends BaseParserClass { /** * Theme instance. * - * @var Theme + * @var ?Theme */ - private static $theme = null; + private $theme; + /** @var array */ + private $workbookPalette = []; + + /** @var array */ private $styles = []; + /** @var array */ private $cellStyles = []; + /** @var SimpleXMLElement */ private $styleXml; - public function __construct(\SimpleXMLElement $styleXml) + /** @var string */ + private $namespace = ''; + + public function setNamespace(string $namespace): void + { + $this->namespace = $namespace; + } + + public function setWorkbookPalette(array $palette): void + { + $this->workbookPalette = $palette; + } + + /** + * Cast SimpleXMLElement to bool to overcome Scrutinizer problem. + * + * @param mixed $value + */ + private static function castBool($value): bool + { + return (bool) $value; + } + + private function getStyleAttributes(SimpleXMLElement $value): SimpleXMLElement + { + $attr = null; + if (self::castBool($value)) { + $attr = $value->attributes(''); + if ($attr === null || count($attr) === 0) { + $attr = $value->attributes($this->namespace); + } + } + + return Xlsx::testSimpleXml($attr); + } + + public function setStyleXml(SimpleXmlElement $styleXml): void { $this->styleXml = $styleXml; } - public function setStyleBaseData(Theme $theme = null, $styles = [], $cellStyles = []) + public function setTheme(Theme $theme): void + { + $this->theme = $theme; + } + + public function setStyleBaseData(?Theme $theme = null, array $styles = [], array $cellStyles = []): void { - self::$theme = $theme; + $this->theme = $theme; $this->styles = $styles; $this->cellStyles = $cellStyles; } - private static function readFontStyle(Font $fontStyle, \SimpleXMLElement $fontStyleXml) + public function readFontStyle(Font $fontStyle, SimpleXMLElement $fontStyleXml): void { - $fontStyle->setName((string) $fontStyleXml->name['val']); - $fontStyle->setSize((float) $fontStyleXml->sz['val']); - + if (isset($fontStyleXml->name)) { + $attr = $this->getStyleAttributes($fontStyleXml->name); + if (isset($attr['val'])) { + $fontStyle->setName((string) $attr['val']); + } + } + if (isset($fontStyleXml->sz)) { + $attr = $this->getStyleAttributes($fontStyleXml->sz); + if (isset($attr['val'])) { + $fontStyle->setSize((float) $attr['val']); + } + } if (isset($fontStyleXml->b)) { - $fontStyle->setBold(!isset($fontStyleXml->b['val']) || self::boolean((string) $fontStyleXml->b['val'])); + $attr = $this->getStyleAttributes($fontStyleXml->b); + $fontStyle->setBold(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->i)) { - $fontStyle->setItalic(!isset($fontStyleXml->i['val']) || self::boolean((string) $fontStyleXml->i['val'])); + $attr = $this->getStyleAttributes($fontStyleXml->i); + $fontStyle->setItalic(!isset($attr['val']) || self::boolean((string) $attr['val'])); } if (isset($fontStyleXml->strike)) { - $fontStyle->setStrikethrough(!isset($fontStyleXml->strike['val']) || self::boolean((string) $fontStyleXml->strike['val'])); - } - $fontStyle->getColor()->setARGB(self::readColor($fontStyleXml->color)); - - if (isset($fontStyleXml->u) && !isset($fontStyleXml->u['val'])) { - $fontStyle->setUnderline(Font::UNDERLINE_SINGLE); - } elseif (isset($fontStyleXml->u, $fontStyleXml->u['val'])) { - $fontStyle->setUnderline((string) $fontStyleXml->u['val']); + $attr = $this->getStyleAttributes($fontStyleXml->strike); + $fontStyle->setStrikethrough(!isset($attr['val']) || self::boolean((string) $attr['val'])); } + $fontStyle->getColor()->setARGB($this->readColor($fontStyleXml->color)); - if (isset($fontStyleXml->vertAlign, $fontStyleXml->vertAlign['val'])) { - $verticalAlign = strtolower((string) $fontStyleXml->vertAlign['val']); - if ($verticalAlign === 'superscript') { - $fontStyle->setSuperscript(true); + if (isset($fontStyleXml->u)) { + $attr = $this->getStyleAttributes($fontStyleXml->u); + if (!isset($attr['val'])) { + $fontStyle->setUnderline(Font::UNDERLINE_SINGLE); + } else { + $fontStyle->setUnderline((string) $attr['val']); } - if ($verticalAlign === 'subscript') { - $fontStyle->setSubscript(true); + } + if (isset($fontStyleXml->vertAlign)) { + $attr = $this->getStyleAttributes($fontStyleXml->vertAlign); + if (isset($attr['val'])) { + $verticalAlign = strtolower((string) $attr['val']); + if ($verticalAlign === 'superscript') { + $fontStyle->setSuperscript(true); + } elseif ($verticalAlign === 'subscript') { + $fontStyle->setSubscript(true); + } } } } - private static function readNumberFormat(NumberFormat $numfmtStyle, \SimpleXMLElement $numfmtStyleXml) + private function readNumberFormat(NumberFormat $numfmtStyle, SimpleXMLElement $numfmtStyleXml): void { - if ($numfmtStyleXml->count() === 0) { + if ((string) $numfmtStyleXml['formatCode'] !== '') { + $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmtStyleXml['formatCode'])); + return; } - $numfmt = $numfmtStyleXml->attributes(); - if ($numfmt->count() > 0 && isset($numfmt['formatCode'])) { - $numfmtStyle->setFormatCode((string) $numfmt['formatCode']); + $numfmt = $this->getStyleAttributes($numfmtStyleXml); + if (isset($numfmt['formatCode'])) { + $numfmtStyle->setFormatCode(self::formatGeneral((string) $numfmt['formatCode'])); } } - private static function readFillStyle(Fill $fillStyle, \SimpleXMLElement $fillStyleXml) + public function readFillStyle(Fill $fillStyle, SimpleXMLElement $fillStyleXml): void { if ($fillStyleXml->gradientFill) { - /** @var \SimpleXMLElement $gradientFill */ + /** @var SimpleXMLElement $gradientFill */ $gradientFill = $fillStyleXml->gradientFill[0]; - if (!empty($gradientFill['type'])) { - $fillStyle->setFillType((string) $gradientFill['type']); + $attr = $this->getStyleAttributes($gradientFill); + if (!empty($attr['type'])) { + $fillStyle->setFillType((string) $attr['type']); } - $fillStyle->setRotation((float) ($gradientFill['degree'])); - $gradientFill->registerXPathNamespace('sml', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - $fillStyle->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); - $fillStyle->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); + $fillStyle->setRotation((float) ($attr['degree'])); + $gradientFill->registerXPathNamespace('sml', Namespaces::MAIN); + $fillStyle->getStartColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=0]'))->color)); + $fillStyle->getEndColor()->setARGB($this->readColor(self::getArrayItem($gradientFill->xpath('sml:stop[@position=1]'))->color)); } elseif ($fillStyleXml->patternFill) { - $patternType = (string) $fillStyleXml->patternFill['patternType'] != '' ? (string) $fillStyleXml->patternFill['patternType'] : 'solid'; - $fillStyle->setFillType($patternType); + $defaultFillStyle = Fill::FILL_NONE; if ($fillStyleXml->patternFill->fgColor) { - $fillStyle->getStartColor()->setARGB(self::readColor($fillStyleXml->patternFill->fgColor, true)); - } else { - $fillStyle->getStartColor()->setARGB('FF000000'); + $fillStyle->getStartColor()->setARGB($this->readColor($fillStyleXml->patternFill->fgColor, true)); + $defaultFillStyle = Fill::FILL_SOLID; } if ($fillStyleXml->patternFill->bgColor) { - $fillStyle->getEndColor()->setARGB(self::readColor($fillStyleXml->patternFill->bgColor, true)); + $fillStyle->getEndColor()->setARGB($this->readColor($fillStyleXml->patternFill->bgColor, true)); + $defaultFillStyle = Fill::FILL_SOLID; } + + $type = ''; + if ((string) $fillStyleXml->patternFill['patternType'] !== '') { + $type = (string) $fillStyleXml->patternFill['patternType']; + } else { + $attr = $this->getStyleAttributes($fillStyleXml->patternFill); + $type = (string) $attr['patternType']; + } + $patternType = ($type === '') ? $defaultFillStyle : $type; + + $fillStyle->setFillType($patternType); } } - private static function readBorderStyle(Borders $borderStyle, \SimpleXMLElement $borderStyleXml) + public function readBorderStyle(Borders $borderStyle, SimpleXMLElement $borderStyleXml): void { - $diagonalUp = self::boolean((string) $borderStyleXml['diagonalUp']); - $diagonalDown = self::boolean((string) $borderStyleXml['diagonalDown']); + $diagonalUp = $this->getAttribute($borderStyleXml, 'diagonalUp'); + $diagonalUp = self::boolean($diagonalUp); + $diagonalDown = $this->getAttribute($borderStyleXml, 'diagonalDown'); + $diagonalDown = self::boolean($diagonalDown); if (!$diagonalUp && !$diagonalDown) { $borderStyle->setDiagonalDirection(Borders::DIAGONAL_NONE); } elseif ($diagonalUp && !$diagonalDown) { @@ -123,82 +204,128 @@ private static function readBorderStyle(Borders $borderStyle, \SimpleXMLElement $borderStyle->setDiagonalDirection(Borders::DIAGONAL_BOTH); } - self::readBorder($borderStyle->getLeft(), $borderStyleXml->left); - self::readBorder($borderStyle->getRight(), $borderStyleXml->right); - self::readBorder($borderStyle->getTop(), $borderStyleXml->top); - self::readBorder($borderStyle->getBottom(), $borderStyleXml->bottom); - self::readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal); + $this->readBorder($borderStyle->getLeft(), $borderStyleXml->left); + $this->readBorder($borderStyle->getRight(), $borderStyleXml->right); + $this->readBorder($borderStyle->getTop(), $borderStyleXml->top); + $this->readBorder($borderStyle->getBottom(), $borderStyleXml->bottom); + $this->readBorder($borderStyle->getDiagonal(), $borderStyleXml->diagonal); + } + + private function getAttribute(SimpleXMLElement $xml, string $attribute): string + { + $style = ''; + if ((string) $xml[$attribute] !== '') { + $style = (string) $xml[$attribute]; + } else { + $attr = $this->getStyleAttributes($xml); + if (isset($attr[$attribute])) { + $style = (string) $attr[$attribute]; + } + } + + return $style; } - private static function readBorder(Border $border, \SimpleXMLElement $borderXml) + private function readBorder(Border $border, SimpleXMLElement $borderXml): void { - if (isset($borderXml['style'])) { - $border->setBorderStyle((string) $borderXml['style']); + $style = $this->getAttribute($borderXml, 'style'); + if ($style !== '') { + $border->setBorderStyle((string) $style); } if (isset($borderXml->color)) { - $border->getColor()->setARGB(self::readColor($borderXml->color)); + $border->getColor()->setARGB($this->readColor($borderXml->color)); } } - private static function readAlignmentStyle(Alignment $alignment, \SimpleXMLElement $alignmentXml) + public function readAlignmentStyle(Alignment $alignment, SimpleXMLElement $alignmentXml): void { - $alignment->setHorizontal((string) $alignmentXml->alignment['horizontal']); - $alignment->setVertical((string) $alignmentXml->alignment['vertical']); + $horizontal = $this->getAttribute($alignmentXml, 'horizontal'); + $alignment->setHorizontal($horizontal); + $vertical = $this->getAttribute($alignmentXml, 'vertical'); + $alignment->setVertical((string) $vertical); + + $textRotation = (int) $this->getAttribute($alignmentXml, 'textRotation'); + if ($textRotation > 90) { + $textRotation = 90 - $textRotation; + } + $alignment->setTextRotation($textRotation); + + $wrapText = $this->getAttribute($alignmentXml, 'wrapText'); + $alignment->setWrapText(self::boolean((string) $wrapText)); + $shrinkToFit = $this->getAttribute($alignmentXml, 'shrinkToFit'); + $alignment->setShrinkToFit(self::boolean((string) $shrinkToFit)); + $indent = (int) $this->getAttribute($alignmentXml, 'indent'); + $alignment->setIndent(max($indent, 0)); + $readingOrder = (int) $this->getAttribute($alignmentXml, 'readingOrder'); + $alignment->setReadOrder(max($readingOrder, 0)); + } - $textRotation = 0; - if ((int) $alignmentXml->alignment['textRotation'] <= 90) { - $textRotation = (int) $alignmentXml->alignment['textRotation']; - } elseif ((int) $alignmentXml->alignment['textRotation'] > 90) { - $textRotation = 90 - (int) $alignmentXml->alignment['textRotation']; + private static function formatGeneral(string $formatString): string + { + if ($formatString === 'GENERAL') { + $formatString = NumberFormat::FORMAT_GENERAL; } - $alignment->setTextRotation((int) $textRotation); - $alignment->setWrapText(self::boolean((string) $alignmentXml->alignment['wrapText'])); - $alignment->setShrinkToFit(self::boolean((string) $alignmentXml->alignment['shrinkToFit'])); - $alignment->setIndent((int) ((string) $alignmentXml->alignment['indent']) > 0 ? (int) ((string) $alignmentXml->alignment['indent']) : 0); - $alignment->setReadOrder((int) ((string) $alignmentXml->alignment['readingOrder']) > 0 ? (int) ((string) $alignmentXml->alignment['readingOrder']) : 0); + return $formatString; } - private function readStyle(Style $docStyle, $style) + /** + * Read style. + * + * @param SimpleXMLElement|stdClass $style + */ + public function readStyle(Style $docStyle, $style): void { - if ($style->numFmt instanceof \SimpleXMLElement) { - self::readNumberFormat($docStyle->getNumberFormat(), $style->numFmt); + if ($style->numFmt instanceof SimpleXMLElement) { + $this->readNumberFormat($docStyle->getNumberFormat(), $style->numFmt); } else { - $docStyle->getNumberFormat()->setFormatCode($style->numFmt); + $docStyle->getNumberFormat()->setFormatCode(self::formatGeneral((string) $style->numFmt)); } if (isset($style->font)) { - self::readFontStyle($docStyle->getFont(), $style->font); + $this->readFontStyle($docStyle->getFont(), $style->font); } if (isset($style->fill)) { - self::readFillStyle($docStyle->getFill(), $style->fill); + $this->readFillStyle($docStyle->getFill(), $style->fill); } if (isset($style->border)) { - self::readBorderStyle($docStyle->getBorders(), $style->border); + $this->readBorderStyle($docStyle->getBorders(), $style->border); } - if (isset($style->alignment->alignment)) { - self::readAlignmentStyle($docStyle->getAlignment(), $style->alignment); + if (isset($style->alignment)) { + $this->readAlignmentStyle($docStyle->getAlignment(), $style->alignment); } // protection if (isset($style->protection)) { - $this->readProtectionLocked($docStyle, $style); - $this->readProtectionHidden($docStyle, $style); + $this->readProtectionLocked($docStyle, $style->protection); + $this->readProtectionHidden($docStyle, $style->protection); } // top-level style settings if (isset($style->quotePrefix)) { - $docStyle->setQuotePrefix(true); + $docStyle->setQuotePrefix((bool) $style->quotePrefix); } } - private function readProtectionLocked(Style $docStyle, $style) + /** + * Read protection locked attribute. + */ + public function readProtectionLocked(Style $docStyle, SimpleXMLElement $style): void { - if (isset($style->protection['locked'])) { - if (self::boolean((string) $style->protection['locked'])) { + $locked = ''; + if ((string) $style['locked'] !== '') { + $locked = (string) $style['locked']; + } else { + $attr = $this->getStyleAttributes($style); + if (isset($attr['locked'])) { + $locked = (string) $attr['locked']; + } + } + if ($locked !== '') { + if (self::boolean($locked)) { $docStyle->getProtection()->setLocked(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED); @@ -206,10 +333,22 @@ private function readProtectionLocked(Style $docStyle, $style) } } - private function readProtectionHidden(Style $docStyle, $style) + /** + * Read protection hidden attribute. + */ + public function readProtectionHidden(Style $docStyle, SimpleXMLElement $style): void { - if (isset($style->protection['hidden'])) { - if (self::boolean((string) $style->protection['hidden'])) { + $hidden = ''; + if ((string) $style['hidden'] !== '') { + $hidden = (string) $style['hidden']; + } else { + $attr = $this->getStyleAttributes($style); + if (isset($attr['hidden'])) { + $hidden = (string) $attr['hidden']; + } + } + if ($hidden !== '') { + if (self::boolean((string) $hidden)) { $docStyle->getProtection()->setHidden(Protection::PROTECTION_PROTECTED); } else { $docStyle->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED); @@ -217,18 +356,25 @@ private function readProtectionHidden(Style $docStyle, $style) } } - private static function readColor($color, $background = false) + public function readColor(SimpleXMLElement $color, bool $background = false): string { - if (isset($color['rgb'])) { - return (string) $color['rgb']; - } elseif (isset($color['indexed'])) { - return Color::indexedColor($color['indexed'] - 7, $background)->getARGB(); - } elseif (isset($color['theme'])) { - if (self::$theme !== null) { - $returnColour = self::$theme->getColourByIndex((int) $color['theme']); - if (isset($color['tint'])) { - $tintAdjust = (float) $color['tint']; - $returnColour = Color::changeBrightness($returnColour, $tintAdjust); + $attr = $this->getStyleAttributes($color); + if (isset($attr['rgb'])) { + return (string) $attr['rgb']; + } + if (isset($attr['indexed'])) { + if (empty($this->workbookPalette)) { + return Color::indexedColor((int) ($attr['indexed'] - 7), $background)->getARGB() ?? ''; + } + + return Color::indexedColor((int) ($attr['indexed']), $background, $this->workbookPalette)->getARGB() ?? ''; + } + if (isset($attr['theme'])) { + if ($this->theme !== null) { + $returnColour = $this->theme->getColourByIndex((int) $attr['theme']); + if (isset($attr['tint'])) { + $tintAdjust = (float) $attr['tint']; + $returnColour = Color::changeBrightness($returnColour ?? '', $tintAdjust); } return 'FF' . $returnColour; @@ -238,7 +384,7 @@ private static function readColor($color, $background = false) return ($background) ? 'FFFFFFFF' : 'FF000000'; } - public function dxfs($readDataOnly = false) + public function dxfs(bool $readDataOnly = false): array { $dxfs = []; if (!$readDataOnly && $this->styleXml) { @@ -252,7 +398,8 @@ public function dxfs($readDataOnly = false) } // Cell Styles if ($this->styleXml->cellStyles) { - foreach ($this->styleXml->cellStyles->cellStyle as $cellStyle) { + foreach ($this->styleXml->cellStyles->cellStyle as $cellStylex) { + $cellStyle = Xlsx::getAttributes($cellStylex); if ((int) ($cellStyle['builtinId']) == 0) { if (isset($this->cellStyles[(int) ($cellStyle['xfId'])])) { // Set default style @@ -269,13 +416,20 @@ public function dxfs($readDataOnly = false) return $dxfs; } - public function styles() + public function styles(): array { return $this->styles; } - private static function getArrayItem($array, $key = 0) + /** + * Get array item. + * + * @param mixed $array (usually array, in theory can be false) + * + * @return stdClass + */ + private static function getArrayItem($array, int $key = 0) { - return $array[$key] ?? null; + return is_array($array) ? ($array[$key] ?? null) : null; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php index c105f3c1..1f2b863c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/Theme.php @@ -21,16 +21,16 @@ class Theme /** * Colour Map. * - * @var array of string + * @var string[] */ private $colourMap; /** * Create a new Theme. * - * @param mixed $themeName - * @param mixed $colourSchemeName - * @param mixed $colourMap + * @param string $themeName + * @param string $colourSchemeName + * @param string[] $colourMap */ public function __construct($themeName, $colourSchemeName, $colourMap) { @@ -63,9 +63,9 @@ public function getColourSchemeName() /** * Get colour Map Value by Position. * - * @param mixed $index + * @param int $index * - * @return string + * @return null|string */ public function getColourByIndex($index) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php new file mode 100644 index 00000000..9d61e3d3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xlsx/WorkbookView.php @@ -0,0 +1,153 @@ +spreadsheet = $spreadsheet; + } + + /** + * @param mixed $mainNS + */ + public function viewSettings(SimpleXMLElement $xmlWorkbook, $mainNS, array $mapSheetId, bool $readDataOnly): void + { + if ($this->spreadsheet->getSheetCount() == 0) { + $this->spreadsheet->createSheet(); + } + // Default active sheet index to the first loaded worksheet from the file + $this->spreadsheet->setActiveSheetIndex(0); + + $workbookView = $xmlWorkbook->children($mainNS)->bookViews->workbookView; + if (($readDataOnly !== true || !empty($this->loadSheetsOnly)) && !empty($workbookView)) { + $workbookViewAttributes = self::testSimpleXml(self::getAttributes($workbookView)); + // active sheet index + $activeTab = (int) $workbookViewAttributes->activeTab; // refers to old sheet index + // keep active sheet index if sheet is still loaded, else first sheet is set as the active worksheet + if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { + $this->spreadsheet->setActiveSheetIndex($mapSheetId[$activeTab]); + } + + $this->horizontalScroll($workbookViewAttributes); + $this->verticalScroll($workbookViewAttributes); + $this->sheetTabs($workbookViewAttributes); + $this->minimized($workbookViewAttributes); + $this->autoFilterDateGrouping($workbookViewAttributes); + $this->firstSheet($workbookViewAttributes); + $this->visibility($workbookViewAttributes); + $this->tabRatio($workbookViewAttributes); + } + } + + /** + * @param mixed $value + */ + public static function testSimpleXml($value): SimpleXMLElement + { + return ($value instanceof SimpleXMLElement) + ? $value + : new SimpleXMLElement(''); + } + + public static function getAttributes(?SimpleXMLElement $value, string $ns = ''): SimpleXMLElement + { + return self::testSimpleXml($value === null ? $value : $value->attributes($ns)); + } + + /** + * Convert an 'xsd:boolean' XML value to a PHP boolean value. + * A valid 'xsd:boolean' XML value can be one of the following + * four values: 'true', 'false', '1', '0'. It is case sensitive. + * + * Note that just doing '(bool) $xsdBoolean' is not safe, + * since '(bool) "false"' returns true. + * + * @see https://www.w3.org/TR/xmlschema11-2/#boolean + * + * @param string $xsdBoolean An XML string value of type 'xsd:boolean' + * + * @return bool Boolean value + */ + private function castXsdBooleanToBool(string $xsdBoolean): bool + { + if ($xsdBoolean === 'false') { + return false; + } + + return (bool) $xsdBoolean; + } + + private function horizontalScroll(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->showHorizontalScroll)) { + $showHorizontalScroll = (string) $workbookViewAttributes->showHorizontalScroll; + $this->spreadsheet->setShowHorizontalScroll($this->castXsdBooleanToBool($showHorizontalScroll)); + } + } + + private function verticalScroll(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->showVerticalScroll)) { + $showVerticalScroll = (string) $workbookViewAttributes->showVerticalScroll; + $this->spreadsheet->setShowVerticalScroll($this->castXsdBooleanToBool($showVerticalScroll)); + } + } + + private function sheetTabs(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->showSheetTabs)) { + $showSheetTabs = (string) $workbookViewAttributes->showSheetTabs; + $this->spreadsheet->setShowSheetTabs($this->castXsdBooleanToBool($showSheetTabs)); + } + } + + private function minimized(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->minimized)) { + $minimized = (string) $workbookViewAttributes->minimized; + $this->spreadsheet->setMinimized($this->castXsdBooleanToBool($minimized)); + } + } + + private function autoFilterDateGrouping(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->autoFilterDateGrouping)) { + $autoFilterDateGrouping = (string) $workbookViewAttributes->autoFilterDateGrouping; + $this->spreadsheet->setAutoFilterDateGrouping($this->castXsdBooleanToBool($autoFilterDateGrouping)); + } + } + + private function firstSheet(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->firstSheet)) { + $firstSheet = (string) $workbookViewAttributes->firstSheet; + $this->spreadsheet->setFirstSheetIndex((int) $firstSheet); + } + } + + private function visibility(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->visibility)) { + $visibility = (string) $workbookViewAttributes->visibility; + $this->spreadsheet->setVisibility($visibility); + } + } + + private function tabRatio(SimpleXMLElement $workbookViewAttributes): void + { + if (isset($workbookViewAttributes->tabRatio)) { + $tabRatio = (string) $workbookViewAttributes->tabRatio; + $this->spreadsheet->setTabRatio((int) $tabRatio); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php index b4fffa4f..bac40961 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml.php @@ -2,19 +2,22 @@ namespace PhpOffice\PhpSpreadsheet\Reader; +use DateTime; +use DateTimeZone; +use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\Document\Properties; +use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner; +use PhpOffice\PhpSpreadsheet\Reader\Xml\PageSettings; +use PhpOffice\PhpSpreadsheet\Reader\Xml\Properties; +use PhpOffice\PhpSpreadsheet\Reader\Xml\Style; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; -use PhpOffice\PhpSpreadsheet\Style\Font; use SimpleXMLElement; /** @@ -29,13 +32,6 @@ class Xml extends BaseReader */ protected $styles = []; - /** - * Character set used in the file. - * - * @var string - */ - protected $charSet = 'UTF-8'; - /** * Create a new Excel2003XML Reader instance. */ @@ -45,16 +41,20 @@ public function __construct() $this->securityScanner = XmlScanner::getInstance($this); } + private $fileContents = ''; + + public static function xmlMappings(): array + { + return array_merge( + Style\Fill::FILL_MAPPINGS, + Style\Border::BORDER_MAPPINGS + ); + } + /** * Can the current IReader read the file? - * - * @param string $pFilename - * - * @throws Exception - * - * @return bool */ - public function canRead($pFilename) + public function canRead(string $filename): bool { // Office xmlns:o="urn:schemas-microsoft-com:office:office" // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" @@ -68,17 +68,14 @@ public function canRead($pFilename) $signature = [ '', + 'xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet', ]; // Open file - $this->openFile($pFilename); - $fileHandle = $this->fileHandle; + $data = file_get_contents($filename); - // Read sample data (first 2 KB will do) - $data = fread($fileHandle, 2048); - fclose($fileHandle); - $data = str_replace("'", '"', $data); // fix headers with single quote + // Why? + //$data = str_replace("'", '"', $data); // fix headers with single quote $valid = true; foreach ($signature as $match) { @@ -91,9 +88,14 @@ public function canRead($pFilename) } // Retrieve charset encoding - if (preg_match('//um', $data, $matches)) { - $this->charSet = strtoupper($matches[1]); + if (preg_match('//m', $data, $matches)) { + $charSet = strtoupper($matches[1]); + if (1 == preg_match('/^ISO-8859-\d[\dL]?$/i', $charSet)) { + $data = StringHelper::convertEncoding($data, 'UTF-8', $charSet); + $data = preg_replace('/()/um', '$1' . 'UTF-8' . '$2', $data, 1); + } } + $this->fileContents = $data; return $valid; } @@ -101,23 +103,22 @@ public function canRead($pFilename) /** * Check if the file is a valid SimpleXML. * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * - * @return false|\SimpleXMLElement + * @return false|SimpleXMLElement */ - public function trySimpleXMLLoadString($pFilename) + public function trySimpleXMLLoadString($filename) { try { $xml = simplexml_load_string( - $this->securityScanner->scan(file_get_contents($pFilename)), + $this->securityScanner->scan($this->fileContents ?: file_get_contents($filename)), 'SimpleXMLElement', Settings::getLibXmlLoaderOptions() ); } catch (\Exception $e) { - throw new Exception('Cannot load invalid XML file: ' . $pFilename, 0, $e); + throw new Exception('Cannot load invalid XML file: ' . $filename, 0, $e); } + $this->fileContents = ''; return $xml; } @@ -125,29 +126,30 @@ public function trySimpleXMLLoadString($pFilename) /** * Reads names of the worksheets from a file, without parsing the whole file to a Spreadsheet object. * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetNames($pFilename) + public function listWorksheetNames($filename) { - File::assertFile($pFilename); - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } $worksheetNames = []; - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); - $worksheetNames[] = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); + $worksheetNames[] = (string) $worksheet_ss['Name']; } return $worksheetNames; @@ -156,26 +158,30 @@ public function listWorksheetNames($pFilename) /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns). * - * @param string $pFilename - * - * @throws Exception + * @param string $filename * * @return array */ - public function listWorksheetInfo($pFilename) + public function listWorksheetInfo($filename) { - File::assertFile($pFilename); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); + } $worksheetInfo = []; - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); $worksheetID = 1; $xml_ss = $xml->children($namespaces['ss']); foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); $tmpInfo = []; $tmpInfo['worksheetName'] = ''; @@ -184,10 +190,9 @@ public function listWorksheetInfo($pFilename) $tmpInfo['totalRows'] = 0; $tmpInfo['totalColumns'] = 0; + $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; if (isset($worksheet_ss['Name'])) { $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; - } else { - $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; } if (isset($worksheet->Table->Row)) { @@ -226,212 +231,87 @@ public function listWorksheetInfo($pFilename) /** * Loads Spreadsheet from file. - * - * @param string $pFilename - * - * @throws Exception - * - * @return Spreadsheet */ - public function load($pFilename) + protected function loadSpreadsheetFromFile(string $filename): Spreadsheet { // Create new Spreadsheet $spreadsheet = new Spreadsheet(); $spreadsheet->removeSheetByIndex(0); // Load into this instance - return $this->loadIntoExisting($pFilename, $spreadsheet); - } - - private static function identifyFixedStyleValue($styleList, &$styleAttributeValue) - { - $styleAttributeValue = strtolower($styleAttributeValue); - foreach ($styleList as $style) { - if ($styleAttributeValue == strtolower($style)) { - $styleAttributeValue = $style; - - return true; - } - } - - return false; - } - - /** - * pixel units to excel width units(units of 1/256th of a character width). - * - * @param float $pxs - * - * @return float - */ - protected static function pixel2WidthUnits($pxs) - { - $UNIT_OFFSET_MAP = [0, 36, 73, 109, 146, 182, 219]; - - $widthUnits = 256 * ($pxs / 7); - $widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)]; - - return $widthUnits; - } - - /** - * excel width units(units of 1/256th of a character width) to pixel units. - * - * @param float $widthUnits - * - * @return float - */ - protected static function widthUnits2Pixel($widthUnits) - { - $pixels = ($widthUnits / 256) * 7; - $offsetWidthUnits = $widthUnits % 256; - - return $pixels + round($offsetWidthUnits / (256 / 7)); - } - - protected static function hex2str($hex) - { - return chr(hexdec($hex[1])); + return $this->loadIntoExisting($filename, $spreadsheet); } /** * Loads from file into Spreadsheet instance. * - * @param string $pFilename - * @param Spreadsheet $spreadsheet - * - * @throws Exception + * @param string $filename * * @return Spreadsheet */ - public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) + public function loadIntoExisting($filename, Spreadsheet $spreadsheet) { - File::assertFile($pFilename); - if (!$this->canRead($pFilename)) { - throw new Exception($pFilename . ' is an Invalid Spreadsheet file.'); + File::assertFile($filename); + if (!$this->canRead($filename)) { + throw new Exception($filename . ' is an Invalid Spreadsheet file.'); } - $xml = $this->trySimpleXMLLoadString($pFilename); + $xml = $this->trySimpleXMLLoadString($filename); + if ($xml === false) { + throw new Exception("Problem reading {$filename}"); + } $namespaces = $xml->getNamespaces(true); - $docProps = $spreadsheet->getProperties(); - if (isset($xml->DocumentProperties[0])) { - foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { - switch ($propertyName) { - case 'Title': - $docProps->setTitle(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Subject': - $docProps->setSubject(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Author': - $docProps->setCreator(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Created': - $creationDate = strtotime($propertyValue); - $docProps->setCreated($creationDate); - - break; - case 'LastAuthor': - $docProps->setLastModifiedBy(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'LastSaved': - $lastSaveDate = strtotime($propertyValue); - $docProps->setModified($lastSaveDate); - - break; - case 'Company': - $docProps->setCompany(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Category': - $docProps->setCategory(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Manager': - $docProps->setManager(self::convertStringEncoding($propertyValue, $this->charSet)); + (new Properties($spreadsheet))->readProperties($xml, $namespaces); - break; - case 'Keywords': - $docProps->setKeywords(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - case 'Description': - $docProps->setDescription(self::convertStringEncoding($propertyValue, $this->charSet)); - - break; - } - } - } - if (isset($xml->CustomDocumentProperties)) { - foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { - $propertyAttributes = $propertyValue->attributes($namespaces['dt']); - $propertyName = preg_replace_callback('/_x([0-9a-z]{4})_/', ['self', 'hex2str'], $propertyName); - $propertyType = Properties::PROPERTY_TYPE_UNKNOWN; - switch ((string) $propertyAttributes) { - case 'string': - $propertyType = Properties::PROPERTY_TYPE_STRING; - $propertyValue = trim($propertyValue); - - break; - case 'boolean': - $propertyType = Properties::PROPERTY_TYPE_BOOLEAN; - $propertyValue = (bool) $propertyValue; - - break; - case 'integer': - $propertyType = Properties::PROPERTY_TYPE_INTEGER; - $propertyValue = (int) $propertyValue; - - break; - case 'float': - $propertyType = Properties::PROPERTY_TYPE_FLOAT; - $propertyValue = (float) $propertyValue; - - break; - case 'dateTime.tz': - $propertyType = Properties::PROPERTY_TYPE_DATE; - $propertyValue = strtotime(trim($propertyValue)); - - break; - } - $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); - } - } - - $this->parseStyles($xml, $namespaces); + $this->styles = (new Style())->parseStyles($xml, $namespaces); $worksheetID = 0; $xml_ss = $xml->children($namespaces['ss']); - foreach ($xml_ss->Worksheet as $worksheet) { - $worksheet_ss = $worksheet->attributes($namespaces['ss']); + /** @var null|SimpleXMLElement $worksheetx */ + foreach ($xml_ss->Worksheet as $worksheetx) { + $worksheet = $worksheetx ?? new SimpleXMLElement(''); + $worksheet_ss = self::getAttributes($worksheet, $namespaces['ss']); - if ((isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) && - (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))) { + if ( + isset($this->loadSheetsOnly, $worksheet_ss['Name']) && + (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly)) + ) { continue; } // Create new Worksheet $spreadsheet->createSheet(); $spreadsheet->setActiveSheetIndex($worksheetID); + $worksheetName = ''; if (isset($worksheet_ss['Name'])) { - $worksheetName = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet); + $worksheetName = (string) $worksheet_ss['Name']; // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in // formula cells... during the load, all formulae should be correct, and we're simply bringing // the worksheet name in line with the formula, not the reverse $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false); } + // locally scoped defined names + if (isset($worksheet->Names[0])) { + foreach ($worksheet->Names[0] as $definedName) { + $definedName_ss = self::getAttributes($definedName, $namespaces['ss']); + $name = (string) $definedName_ss['Name']; + $definedValue = (string) $definedName_ss['RefersTo']; + $convertedValue = AddressHelper::convertFormulaToA1($definedValue); + if ($convertedValue[0] === '=') { + $convertedValue = substr($convertedValue, 1); + } + $spreadsheet->addDefinedName(DefinedName::createInstance($name, $spreadsheet->getActiveSheet(), $convertedValue, true)); + } + } + $columnID = 'A'; if (isset($worksheet->Table->Column)) { foreach ($worksheet->Table->Column as $columnData) { - $columnData_ss = $columnData->attributes($namespaces['ss']); + $columnData_ss = self::getAttributes($columnData, $namespaces['ss']); if (isset($columnData_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $columnData_ss['Index']); } @@ -448,14 +328,14 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $additionalMergedCells = 0; foreach ($worksheet->Table->Row as $rowData) { $rowHasData = false; - $row_ss = $rowData->attributes($namespaces['ss']); + $row_ss = self::getAttributes($rowData, $namespaces['ss']); if (isset($row_ss['Index'])) { $rowID = (int) $row_ss['Index']; } $columnID = 'A'; foreach ($rowData->Cell as $cell) { - $cell_ss = $cell->attributes($namespaces['ss']); + $cell_ss = self::getAttributes($cell, $namespaces['ss']); if (isset($cell_ss['Index'])) { $columnID = Coordinate::stringFromColumnIndex((int) $cell_ss['Index']); } @@ -470,14 +350,14 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) } if (isset($cell_ss['HRef'])) { - $spreadsheet->getActiveSheet()->getCell($cellRange)->getHyperlink()->setUrl($cell_ss['HRef']); + $spreadsheet->getActiveSheet()->getCell($cellRange)->getHyperlink()->setUrl((string) $cell_ss['HRef']); } if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { $columnTo = $columnID; if (isset($cell_ss['MergeAcross'])) { $additionalMergedCells += (int) $cell_ss['MergeAcross']; - $columnTo = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross']); + $columnTo = Coordinate::stringFromColumnIndex((int) (Coordinate::columnIndexFromString($columnID) + $cell_ss['MergeAcross'])); } $rowTo = $rowID; if (isset($cell_ss['MergeDown'])) { @@ -487,16 +367,17 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) $spreadsheet->getActiveSheet()->mergeCells($cellRange); } - $cellIsSet = $hasCalculatedValue = false; + $hasCalculatedValue = false; $cellDataFormula = ''; if (isset($cell_ss['Formula'])) { $cellDataFormula = $cell_ss['Formula']; $hasCalculatedValue = true; } if (isset($cell->Data)) { - $cellValue = $cellData = $cell->Data; + $cellData = $cell->Data; + $cellValue = (string) $cellData; $type = DataType::TYPE_NULL; - $cellData_ss = $cellData->attributes($namespaces['ss']); + $cellData_ss = self::getAttributes($cellData, $namespaces['ss']); if (isset($cellData_ss['Type'])) { $cellDataType = $cellData_ss['Type']; switch ($cellDataType) { @@ -510,7 +391,6 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) const TYPE_ERROR = 'e'; */ case 'String': - $cellValue = self::convertStringEncoding($cellValue, $this->charSet); $type = DataType::TYPE_STRING; break; @@ -529,11 +409,13 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) break; case 'DateTime': $type = DataType::TYPE_NUMERIC; - $cellValue = Date::PHPToExcel(strtotime($cellValue)); + $dateTime = new DateTime($cellValue, new DateTimeZone('UTC')); + $cellValue = Date::PHPToExcel($dateTime); break; case 'Error': $type = DataType::TYPE_ERROR; + $hasCalculatedValue = false; break; } @@ -542,85 +424,28 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) if ($hasCalculatedValue) { $type = DataType::TYPE_FORMULA; $columnNumber = Coordinate::columnIndexFromString($columnID); - if (substr($cellDataFormula, 0, 3) == 'of:') { - $cellDataFormula = substr($cellDataFormula, 3); - $temp = explode('"', $cellDataFormula); - $key = false; - foreach ($temp as &$value) { - // Only replace in alternate array entries (i.e. non-quoted blocks) - if ($key = !$key) { - $value = str_replace(['[.', '.', ']'], '', $value); - } - } - } else { - // Convert R1C1 style references to A1 style references (but only when not quoted) - $temp = explode('"', $cellDataFormula); - $key = false; - foreach ($temp as &$value) { - // Only replace in alternate array entries (i.e. non-quoted blocks) - if ($key = !$key) { - preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); - // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way - // through the formula from left to right. Reversing means that we work right to left.through - // the formula - $cellReferences = array_reverse($cellReferences); - // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, - // then modify the formula to use that new reference - foreach ($cellReferences as $cellReference) { - $rowReference = $cellReference[2][0]; - // Empty R reference is the current row - if ($rowReference == '') { - $rowReference = $rowID; - } - // Bracketed R references are relative to the current row - if ($rowReference[0] == '[') { - $rowReference = $rowID + trim($rowReference, '[]'); - } - $columnReference = $cellReference[4][0]; - // Empty C reference is the current column - if ($columnReference == '') { - $columnReference = $columnNumber; - } - // Bracketed C references are relative to the current column - if ($columnReference[0] == '[') { - $columnReference = $columnNumber + trim($columnReference, '[]'); - } - $A1CellReference = Coordinate::stringFromColumnIndex($columnReference) . $rowReference; - $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); - } - } - } - } - unset($value); - // Then rebuild the formula string - $cellDataFormula = implode('"', $temp); + $cellDataFormula = AddressHelper::convertFormulaToA1($cellDataFormula, $rowID, $columnNumber); } $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); if ($hasCalculatedValue) { $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setCalculatedValue($cellValue); } - $cellIsSet = $rowHasData = true; + $rowHasData = true; } if (isset($cell->Comment)) { - $commentAttributes = $cell->Comment->attributes($namespaces['ss']); - $author = 'unknown'; - if (isset($commentAttributes->Author)) { - $author = (string) $commentAttributes->Author; - } - $node = $cell->Comment->Data->asXML(); - $annotation = strip_tags($node); - $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation)); + $this->parseCellComment($cell->Comment, $namespaces, $spreadsheet, $columnID, $rowID); } - if (($cellIsSet) && (isset($cell_ss['StyleID']))) { + if (isset($cell_ss['StyleID'])) { $style = (string) $cell_ss['StyleID']; if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) { - if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) { - $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null); - } - $spreadsheet->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]); + //if (!$spreadsheet->getActiveSheet()->cellExists($columnID . $rowID)) { + // $spreadsheet->getActiveSheet()->getCell($columnID . $rowID)->setValue(null); + //} + $spreadsheet->getActiveSheet()->getStyle($cellRange) + ->applyFromArray($this->styles[$style]); } } ++$columnID; @@ -633,249 +458,75 @@ public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet) if ($rowHasData) { if (isset($row_ss['Height'])) { $rowHeight = $row_ss['Height']; - $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight); + $spreadsheet->getActiveSheet()->getRowDimension($rowID)->setRowHeight((float) $rowHeight); } } ++$rowID; } + + if (isset($namespaces['x'])) { + $xmlX = $worksheet->children($namespaces['x']); + if (isset($xmlX->WorksheetOptions)) { + (new PageSettings($xmlX, $namespaces))->loadPageSettings($spreadsheet); + } + } } ++$worksheetID; } - // Return - return $spreadsheet; - } - - protected static function convertStringEncoding($string, $charset) - { - if ($charset != 'UTF-8') { - return StringHelper::convertEncoding($string, 'UTF-8', $charset); - } - - return $string; - } - - protected function parseRichText($is) - { - $value = new RichText(); - - $value->createText(self::convertStringEncoding($is, $this->charSet)); - - return $value; - } - - /** - * @param SimpleXMLElement $xml - * @param array $namespaces - */ - private function parseStyles(SimpleXMLElement $xml, array $namespaces) - { - if (!isset($xml->Styles)) { - return; - } - - foreach ($xml->Styles[0] as $style) { - $style_ss = $style->attributes($namespaces['ss']); - $styleID = (string) $style_ss['ID']; - $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : []; - foreach ($style as $styleType => $styleData) { - $styleAttributes = $styleData->attributes($namespaces['ss']); - switch ($styleType) { - case 'Alignment': - $this->parseStyleAlignment($styleID, $styleAttributes); - - break; - case 'Borders': - $this->parseStyleBorders($styleID, $styleData, $namespaces); - - break; - case 'Font': - $this->parseStyleFont($styleID, $styleAttributes); - - break; - case 'Interior': - $this->parseStyleInterior($styleID, $styleAttributes); - - break; - case 'NumberFormat': - $this->parseStyleNumberFormat($styleID, $styleAttributes); - - break; + // Globally scoped defined names + $activeWorksheet = $spreadsheet->setActiveSheetIndex(0); + if (isset($xml->Names[0])) { + foreach ($xml->Names[0] as $definedName) { + $definedName_ss = self::getAttributes($definedName, $namespaces['ss']); + $name = (string) $definedName_ss['Name']; + $definedValue = (string) $definedName_ss['RefersTo']; + $convertedValue = AddressHelper::convertFormulaToA1($definedValue); + if ($convertedValue[0] === '=') { + $convertedValue = substr($convertedValue, 1); } + $spreadsheet->addDefinedName(DefinedName::createInstance($name, $activeWorksheet, $convertedValue)); } } - } - /** - * @param string $styleID - * @param SimpleXMLElement $styleAttributes - */ - private function parseStyleAlignment($styleID, SimpleXMLElement $styleAttributes) - { - $verticalAlignmentStyles = [ - Alignment::VERTICAL_BOTTOM, - Alignment::VERTICAL_TOP, - Alignment::VERTICAL_CENTER, - Alignment::VERTICAL_JUSTIFY, - ]; - $horizontalAlignmentStyles = [ - Alignment::HORIZONTAL_GENERAL, - Alignment::HORIZONTAL_LEFT, - Alignment::HORIZONTAL_RIGHT, - Alignment::HORIZONTAL_CENTER, - Alignment::HORIZONTAL_CENTER_CONTINUOUS, - Alignment::HORIZONTAL_JUSTIFY, - ]; - - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = (string) $styleAttributeValue; - switch ($styleAttributeKey) { - case 'Vertical': - if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) { - $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue; - } - - break; - case 'Horizontal': - if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) { - $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue; - } - - break; - case 'WrapText': - $this->styles[$styleID]['alignment']['wrapText'] = true; - - break; - } - } + // Return + return $spreadsheet; } - /** - * @param $styleID - * @param SimpleXMLElement $styleData - * @param array $namespaces - */ - private function parseStyleBorders($styleID, SimpleXMLElement $styleData, array $namespaces) - { - foreach ($styleData->Border as $borderStyle) { - $borderAttributes = $borderStyle->attributes($namespaces['ss']); - $thisBorder = []; - foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) { - switch ($borderStyleKey) { - case 'LineStyle': - $thisBorder['borderStyle'] = Border::BORDER_MEDIUM; - - break; - case 'Weight': - break; - case 'Position': - $borderPosition = strtolower($borderStyleValue); - - break; - case 'Color': - $borderColour = substr($borderStyleValue, 1); - $thisBorder['color']['rgb'] = $borderColour; - - break; - } - } - if (!empty($thisBorder)) { - if (($borderPosition == 'left') || ($borderPosition == 'right') || ($borderPosition == 'top') || ($borderPosition == 'bottom')) { - $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder; - } - } + protected function parseCellComment( + SimpleXMLElement $comment, + array $namespaces, + Spreadsheet $spreadsheet, + string $columnID, + int $rowID + ): void { + $commentAttributes = $comment->attributes($namespaces['ss']); + $author = 'unknown'; + if (isset($commentAttributes->Author)) { + $author = (string) $commentAttributes->Author; } - } - - /** - * @param $styleID - * @param SimpleXMLElement $styleAttributes - */ - private function parseStyleFont($styleID, SimpleXMLElement $styleAttributes) - { - $underlineStyles = [ - Font::UNDERLINE_NONE, - Font::UNDERLINE_DOUBLE, - Font::UNDERLINE_DOUBLEACCOUNTING, - Font::UNDERLINE_SINGLE, - Font::UNDERLINE_SINGLEACCOUNTING, - ]; - - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = (string) $styleAttributeValue; - switch ($styleAttributeKey) { - case 'FontName': - $this->styles[$styleID]['font']['name'] = $styleAttributeValue; - - break; - case 'Size': - $this->styles[$styleID]['font']['size'] = $styleAttributeValue; - - break; - case 'Color': - $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1); - - break; - case 'Bold': - $this->styles[$styleID]['font']['bold'] = true; - break; - case 'Italic': - $this->styles[$styleID]['font']['italic'] = true; - - break; - case 'Underline': - if (self::identifyFixedStyleValue($underlineStyles, $styleAttributeValue)) { - $this->styles[$styleID]['font']['underline'] = $styleAttributeValue; - } - - break; - } - } + $node = $comment->Data->asXML(); + $annotation = strip_tags((string) $node); + $spreadsheet->getActiveSheet()->getComment($columnID . $rowID) + ->setAuthor($author) + ->setText($this->parseRichText($annotation)); } - /** - * @param $styleID - * @param SimpleXMLElement $styleAttributes - */ - private function parseStyleInterior($styleID, SimpleXMLElement $styleAttributes) + protected function parseRichText(string $annotation): RichText { - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - switch ($styleAttributeKey) { - case 'Color': - $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1); + $value = new RichText(); - break; - case 'Pattern': - $this->styles[$styleID]['fill']['fillType'] = strtolower($styleAttributeValue); + $value->createText($annotation); - break; - } - } + return $value; } - /** - * @param $styleID - * @param SimpleXMLElement $styleAttributes - */ - private function parseStyleNumberFormat($styleID, SimpleXMLElement $styleAttributes) + private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement { - $fromFormats = ['\-', '\ ']; - $toFormats = ['-', ' ']; - - foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { - $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); - switch ($styleAttributeValue) { - case 'Short Date': - $styleAttributeValue = 'dd/mm/yyyy'; - - break; - } - - if ($styleAttributeValue > '') { - $this->styles[$styleID]['numberFormat']['formatCode'] = $styleAttributeValue; - } - } + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php new file mode 100644 index 00000000..c0caca3b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/PageSettings.php @@ -0,0 +1,134 @@ +pageSetup($xmlX, $namespaces, $this->getPrintDefaults()); + $this->printSettings = $this->printSetup($xmlX, $printSettings); + } + + public function loadPageSettings(Spreadsheet $spreadsheet): void + { + $spreadsheet->getActiveSheet()->getPageSetup() + ->setPaperSize($this->printSettings->paperSize) + ->setOrientation($this->printSettings->orientation) + ->setScale($this->printSettings->scale) + ->setVerticalCentered($this->printSettings->verticalCentered) + ->setHorizontalCentered($this->printSettings->horizontalCentered) + ->setPageOrder($this->printSettings->printOrder); + $spreadsheet->getActiveSheet()->getPageMargins() + ->setTop($this->printSettings->topMargin) + ->setHeader($this->printSettings->headerMargin) + ->setLeft($this->printSettings->leftMargin) + ->setRight($this->printSettings->rightMargin) + ->setBottom($this->printSettings->bottomMargin) + ->setFooter($this->printSettings->footerMargin); + } + + private function getPrintDefaults(): stdClass + { + return (object) [ + 'paperSize' => 9, + 'orientation' => PageSetup::ORIENTATION_DEFAULT, + 'scale' => 100, + 'horizontalCentered' => false, + 'verticalCentered' => false, + 'printOrder' => PageSetup::PAGEORDER_DOWN_THEN_OVER, + 'topMargin' => 0.75, + 'headerMargin' => 0.3, + 'leftMargin' => 0.7, + 'rightMargin' => 0.7, + 'bottomMargin' => 0.75, + 'footerMargin' => 0.3, + ]; + } + + private function pageSetup(SimpleXMLElement $xmlX, array $namespaces, stdClass $printDefaults): stdClass + { + if (isset($xmlX->WorksheetOptions->PageSetup)) { + foreach ($xmlX->WorksheetOptions->PageSetup as $pageSetupData) { + foreach ($pageSetupData as $pageSetupKey => $pageSetupValue) { + $pageSetupAttributes = $pageSetupValue->attributes($namespaces['x']); + if (!$pageSetupAttributes) { + continue; + } + + switch ($pageSetupKey) { + case 'Layout': + $this->setLayout($printDefaults, $pageSetupAttributes); + + break; + case 'Header': + $printDefaults->headerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; + + break; + case 'Footer': + $printDefaults->footerMargin = (float) $pageSetupAttributes->Margin ?: 1.0; + + break; + case 'PageMargins': + $this->setMargins($printDefaults, $pageSetupAttributes); + + break; + } + } + } + } + + return $printDefaults; + } + + private function printSetup(SimpleXMLElement $xmlX, stdClass $printDefaults): stdClass + { + if (isset($xmlX->WorksheetOptions->Print)) { + foreach ($xmlX->WorksheetOptions->Print as $printData) { + foreach ($printData as $printKey => $printValue) { + switch ($printKey) { + case 'LeftToRight': + $printDefaults->printOrder = PageSetup::PAGEORDER_OVER_THEN_DOWN; + + break; + case 'PaperSizeIndex': + $printDefaults->paperSize = (int) $printValue ?: 9; + + break; + case 'Scale': + $printDefaults->scale = (int) $printValue ?: 100; + + break; + } + } + } + } + + return $printDefaults; + } + + private function setLayout(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void + { + $printDefaults->orientation = (string) strtolower($pageSetupAttributes->Orientation ?? '') ?: PageSetup::ORIENTATION_PORTRAIT; + $printDefaults->horizontalCentered = (bool) $pageSetupAttributes->CenterHorizontal ?: false; + $printDefaults->verticalCentered = (bool) $pageSetupAttributes->CenterVertical ?: false; + } + + private function setMargins(stdClass $printDefaults, SimpleXMLElement $pageSetupAttributes): void + { + $printDefaults->leftMargin = (float) $pageSetupAttributes->Left ?: 1.0; + $printDefaults->rightMargin = (float) $pageSetupAttributes->Right ?: 1.0; + $printDefaults->topMargin = (float) $pageSetupAttributes->Top ?: 1.0; + $printDefaults->bottomMargin = (float) $pageSetupAttributes->Bottom ?: 1.0; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php new file mode 100644 index 00000000..1c3e421a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Properties.php @@ -0,0 +1,157 @@ +spreadsheet = $spreadsheet; + } + + public function readProperties(SimpleXMLElement $xml, array $namespaces): void + { + $this->readStandardProperties($xml); + $this->readCustomProperties($xml, $namespaces); + } + + protected function readStandardProperties(SimpleXMLElement $xml): void + { + if (isset($xml->DocumentProperties[0])) { + $docProps = $this->spreadsheet->getProperties(); + + foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + + $this->processStandardProperty($docProps, $propertyName, $propertyValue); + } + } + } + + protected function readCustomProperties(SimpleXMLElement $xml, array $namespaces): void + { + if (isset($xml->CustomDocumentProperties)) { + $docProps = $this->spreadsheet->getProperties(); + + foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { + $propertyAttributes = self::getAttributes($propertyValue, $namespaces['dt']); + $propertyName = preg_replace_callback('/_x([0-9a-f]{4})_/i', [$this, 'hex2str'], $propertyName); + + $this->processCustomProperty($docProps, $propertyName, $propertyValue, $propertyAttributes); + } + } + } + + protected function processStandardProperty( + DocumentProperties $docProps, + string $propertyName, + string $stringValue + ): void { + switch ($propertyName) { + case 'Title': + $docProps->setTitle($stringValue); + + break; + case 'Subject': + $docProps->setSubject($stringValue); + + break; + case 'Author': + $docProps->setCreator($stringValue); + + break; + case 'Created': + $docProps->setCreated($stringValue); + + break; + case 'LastAuthor': + $docProps->setLastModifiedBy($stringValue); + + break; + case 'LastSaved': + $docProps->setModified($stringValue); + + break; + case 'Company': + $docProps->setCompany($stringValue); + + break; + case 'Category': + $docProps->setCategory($stringValue); + + break; + case 'Manager': + $docProps->setManager($stringValue); + + break; + case 'Keywords': + $docProps->setKeywords($stringValue); + + break; + case 'Description': + $docProps->setDescription($stringValue); + + break; + } + } + + protected function processCustomProperty( + DocumentProperties $docProps, + string $propertyName, + ?SimpleXMLElement $propertyValue, + SimpleXMLElement $propertyAttributes + ): void { + $propertyType = DocumentProperties::PROPERTY_TYPE_UNKNOWN; + + switch ((string) $propertyAttributes) { + case 'string': + $propertyType = DocumentProperties::PROPERTY_TYPE_STRING; + $propertyValue = trim((string) $propertyValue); + + break; + case 'boolean': + $propertyType = DocumentProperties::PROPERTY_TYPE_BOOLEAN; + $propertyValue = (bool) $propertyValue; + + break; + case 'integer': + $propertyType = DocumentProperties::PROPERTY_TYPE_INTEGER; + $propertyValue = (int) $propertyValue; + + break; + case 'float': + $propertyType = DocumentProperties::PROPERTY_TYPE_FLOAT; + $propertyValue = (float) $propertyValue; + + break; + case 'dateTime.tz': + $propertyType = DocumentProperties::PROPERTY_TYPE_DATE; + $propertyValue = trim((string) $propertyValue); + + break; + } + + $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); + } + + protected function hex2str(array $hex): string + { + return mb_chr((int) hexdec($hex[1]), 'UTF-8'); + } + + private static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement + { + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php new file mode 100644 index 00000000..0e3cd16d --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style.php @@ -0,0 +1,83 @@ +Styles)) { + return []; + } + + $alignmentStyleParser = new Style\Alignment(); + $borderStyleParser = new Style\Border(); + $fontStyleParser = new Style\Font(); + $fillStyleParser = new Style\Fill(); + $numberFormatStyleParser = new Style\NumberFormat(); + + foreach ($xml->Styles[0] as $style) { + $style_ss = self::getAttributes($style, $namespaces['ss']); + $styleID = (string) $style_ss['ID']; + $this->styles[$styleID] = $this->styles['Default'] ?? []; + + $alignment = $border = $font = $fill = $numberFormat = []; + + foreach ($style as $styleType => $styleDatax) { + $styleData = $styleDatax ?? new SimpleXMLElement(''); + $styleAttributes = $styleData->attributes($namespaces['ss']); + + switch ($styleType) { + case 'Alignment': + if ($styleAttributes) { + $alignment = $alignmentStyleParser->parseStyle($styleAttributes); + } + + break; + case 'Borders': + $border = $borderStyleParser->parseStyle($styleData, $namespaces); + + break; + case 'Font': + if ($styleAttributes) { + $font = $fontStyleParser->parseStyle($styleAttributes); + } + + break; + case 'Interior': + if ($styleAttributes) { + $fill = $fillStyleParser->parseStyle($styleAttributes); + } + + break; + case 'NumberFormat': + if ($styleAttributes) { + $numberFormat = $numberFormatStyleParser->parseStyle($styleAttributes); + } + + break; + } + } + + $this->styles[$styleID] = array_merge($alignment, $border, $font, $fill, $numberFormat); + } + + return $this->styles; + } + + protected static function getAttributes(?SimpleXMLElement $simple, string $node): SimpleXMLElement + { + return ($simple === null) + ? new SimpleXMLElement('') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php new file mode 100644 index 00000000..d1363548 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Alignment.php @@ -0,0 +1,58 @@ + $styleAttributeValue) { + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'Vertical': + if (self::identifyFixedStyleValue(self::VERTICAL_ALIGNMENT_STYLES, $styleAttributeValue)) { + $style['alignment']['vertical'] = $styleAttributeValue; + } + + break; + case 'Horizontal': + if (self::identifyFixedStyleValue(self::HORIZONTAL_ALIGNMENT_STYLES, $styleAttributeValue)) { + $style['alignment']['horizontal'] = $styleAttributeValue; + } + + break; + case 'WrapText': + $style['alignment']['wrapText'] = true; + + break; + case 'Rotate': + $style['alignment']['textRotation'] = $styleAttributeValue; + + break; + } + } + + return $style; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php new file mode 100644 index 00000000..8aefd9c9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Border.php @@ -0,0 +1,98 @@ + [ + '1continuous' => BorderStyle::BORDER_THIN, + '1dash' => BorderStyle::BORDER_DASHED, + '1dashdot' => BorderStyle::BORDER_DASHDOT, + '1dashdotdot' => BorderStyle::BORDER_DASHDOTDOT, + '1dot' => BorderStyle::BORDER_DOTTED, + '1double' => BorderStyle::BORDER_DOUBLE, + '2continuous' => BorderStyle::BORDER_MEDIUM, + '2dash' => BorderStyle::BORDER_MEDIUMDASHED, + '2dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, + '2dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, + '2dot' => BorderStyle::BORDER_DOTTED, + '2double' => BorderStyle::BORDER_DOUBLE, + '3continuous' => BorderStyle::BORDER_THICK, + '3dash' => BorderStyle::BORDER_MEDIUMDASHED, + '3dashdot' => BorderStyle::BORDER_MEDIUMDASHDOT, + '3dashdotdot' => BorderStyle::BORDER_MEDIUMDASHDOTDOT, + '3dot' => BorderStyle::BORDER_DOTTED, + '3double' => BorderStyle::BORDER_DOUBLE, + ], + ]; + + public function parseStyle(SimpleXMLElement $styleData, array $namespaces): array + { + $style = []; + + $diagonalDirection = ''; + $borderPosition = ''; + foreach ($styleData->Border as $borderStyle) { + $borderAttributes = self::getAttributes($borderStyle, $namespaces['ss']); + $thisBorder = []; + $styleType = (string) $borderAttributes->Weight; + $styleType .= strtolower((string) $borderAttributes->LineStyle); + $thisBorder['borderStyle'] = self::BORDER_MAPPINGS['borderStyle'][$styleType] ?? BorderStyle::BORDER_NONE; + + foreach ($borderAttributes as $borderStyleKey => $borderStyleValuex) { + $borderStyleValue = (string) $borderStyleValuex; + switch ($borderStyleKey) { + case 'Position': + [$borderPosition, $diagonalDirection] = + $this->parsePosition($borderStyleValue, $diagonalDirection); + + break; + case 'Color': + $borderColour = substr($borderStyleValue, 1); + $thisBorder['color']['rgb'] = $borderColour; + + break; + } + } + + if ($borderPosition) { + $style['borders'][$borderPosition] = $thisBorder; + } elseif ($diagonalDirection) { + $style['borders']['diagonalDirection'] = $diagonalDirection; + $style['borders']['diagonal'] = $thisBorder; + } + } + + return $style; + } + + protected function parsePosition(string $borderStyleValue, string $diagonalDirection): array + { + $borderStyleValue = strtolower($borderStyleValue); + + if (in_array($borderStyleValue, self::BORDER_POSITIONS)) { + $borderPosition = $borderStyleValue; + } elseif ($borderStyleValue === 'diagonalleft') { + $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_DOWN; + } elseif ($borderStyleValue === 'diagonalright') { + $diagonalDirection = $diagonalDirection ? Borders::DIAGONAL_BOTH : Borders::DIAGONAL_UP; + } + + return [$borderPosition ?? null, $diagonalDirection]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php new file mode 100644 index 00000000..9a612152 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Fill.php @@ -0,0 +1,63 @@ + [ + 'solid' => FillStyles::FILL_SOLID, + 'gray75' => FillStyles::FILL_PATTERN_DARKGRAY, + 'gray50' => FillStyles::FILL_PATTERN_MEDIUMGRAY, + 'gray25' => FillStyles::FILL_PATTERN_LIGHTGRAY, + 'gray125' => FillStyles::FILL_PATTERN_GRAY125, + 'gray0625' => FillStyles::FILL_PATTERN_GRAY0625, + 'horzstripe' => FillStyles::FILL_PATTERN_DARKHORIZONTAL, // horizontal stripe + 'vertstripe' => FillStyles::FILL_PATTERN_DARKVERTICAL, // vertical stripe + 'reversediagstripe' => FillStyles::FILL_PATTERN_DARKUP, // reverse diagonal stripe + 'diagstripe' => FillStyles::FILL_PATTERN_DARKDOWN, // diagonal stripe + 'diagcross' => FillStyles::FILL_PATTERN_DARKGRID, // diagoanl crosshatch + 'thickdiagcross' => FillStyles::FILL_PATTERN_DARKTRELLIS, // thick diagonal crosshatch + 'thinhorzstripe' => FillStyles::FILL_PATTERN_LIGHTHORIZONTAL, + 'thinvertstripe' => FillStyles::FILL_PATTERN_LIGHTVERTICAL, + 'thinreversediagstripe' => FillStyles::FILL_PATTERN_LIGHTUP, + 'thindiagstripe' => FillStyles::FILL_PATTERN_LIGHTDOWN, + 'thinhorzcross' => FillStyles::FILL_PATTERN_LIGHTGRID, // thin horizontal crosshatch + 'thindiagcross' => FillStyles::FILL_PATTERN_LIGHTTRELLIS, // thin diagonal crosshatch + ], + ]; + + public function parseStyle(SimpleXMLElement $styleAttributes): array + { + $style = []; + + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValuex) { + $styleAttributeValue = (string) $styleAttributeValuex; + switch ($styleAttributeKey) { + case 'Color': + $style['fill']['endColor']['rgb'] = substr($styleAttributeValue, 1); + $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'PatternColor': + $style['fill']['startColor']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'Pattern': + $lcStyleAttributeValue = strtolower((string) $styleAttributeValue); + $style['fill']['fillType'] + = self::FILL_MAPPINGS['fillType'][$lcStyleAttributeValue] ?? FillStyles::FILL_NONE; + + break; + } + } + + return $style; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php new file mode 100644 index 00000000..16ab44d8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/Font.php @@ -0,0 +1,79 @@ + $styleAttributeValue) { + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'FontName': + $style['font']['name'] = $styleAttributeValue; + + break; + case 'Size': + $style['font']['size'] = $styleAttributeValue; + + break; + case 'Color': + $style['font']['color']['rgb'] = substr($styleAttributeValue, 1); + + break; + case 'Bold': + $style['font']['bold'] = true; + + break; + case 'Italic': + $style['font']['italic'] = true; + + break; + case 'Underline': + $style = $this->parseUnderline($style, $styleAttributeValue); + + break; + case 'VerticalAlign': + $style = $this->parseVerticalAlign($style, $styleAttributeValue); + + break; + } + } + + return $style; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php new file mode 100644 index 00000000..a31aa9eb --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/NumberFormat.php @@ -0,0 +1,33 @@ + $styleAttributeValue) { + $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); + + switch ($styleAttributeValue) { + case 'Short Date': + $styleAttributeValue = 'dd/mm/yyyy'; + + break; + } + + if ($styleAttributeValue > '') { + $style['numberFormat']['formatCode'] = $styleAttributeValue; + } + } + + return $style; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php new file mode 100644 index 00000000..fc9ace82 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Reader/Xml/Style/StyleBase.php @@ -0,0 +1,32 @@ +') + : ($simple->attributes($node) ?? new SimpleXMLElement('')); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php index 143e80d8..4a6ee039 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php @@ -2,8 +2,12 @@ namespace PhpOffice\PhpSpreadsheet; +use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; +use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter; +use PhpOffice\PhpSpreadsheet\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class ReferenceHelper @@ -18,10 +22,15 @@ class ReferenceHelper /** * Instance of this class. * - * @var ReferenceHelper + * @var ?ReferenceHelper */ private static $instance; + /** + * @var CellReferenceHelper + */ + private $cellReferenceHelper; + /** * Get an instance of this class. * @@ -29,7 +38,7 @@ class ReferenceHelper */ public static function getInstance() { - if (!isset(self::$instance) || (self::$instance === null)) { + if (self::$instance === null) { self::$instance = new self(); } @@ -68,7 +77,7 @@ public static function columnSort($a, $b) */ public static function columnReverseSort($a, $b) { - return 1 - strcasecmp(strlen($a) . $a, strlen($b) . $b); + return -strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** @@ -82,8 +91,8 @@ public static function columnReverseSort($a, $b) */ public static function cellSort($a, $b) { - [$ac, $ar] = sscanf($a, '%[A-Z]%d'); - [$bc, $br] = sscanf($b, '%[A-Z]%d'); + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); if ($ar === $br) { return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); @@ -103,73 +112,42 @@ public static function cellSort($a, $b) */ public static function cellReverseSort($a, $b) { - [$ac, $ar] = sscanf($a, '%[A-Z]%d'); - [$bc, $br] = sscanf($b, '%[A-Z]%d'); + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); if ($ar === $br) { - return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); + return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? 1 : -1; } - /** - * Test whether a cell address falls within a defined range of cells. - * - * @param string $cellAddress Address of the cell we're testing - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * - * @return bool - */ - private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) - { - [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); - $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); - // Is cell within the range of rows/columns if we're deleting - if ($pNumRows < 0 && - ($cellRow >= ($beforeRow + $pNumRows)) && - ($cellRow < $beforeRow)) { - return true; - } elseif ($pNumCols < 0 && - ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && - ($cellColumnIndex < $beforeColumnIndex)) { - return true; - } - - return false; - } - /** * Update page breaks when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustPageBreaks(Worksheet $worksheet, $numberOfColumns, $numberOfRows): void { - $aBreaks = $pSheet->getBreaks(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']); + $aBreaks = $worksheet->getBreaks(); + ($numberOfColumns > 0 || $numberOfRows > 0) + ? uksort($aBreaks, [self::class, 'cellReverseSort']) + : uksort($aBreaks, [self::class, 'cellSort']); - foreach ($aBreaks as $key => $value) { - if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + foreach ($aBreaks as $cellAddress => $value) { + if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { // If we're deleting, then clear any defined breaks that are within the range // of rows/columns that we're deleting - $pSheet->setBreak($key, Worksheet::BREAK_NONE); + $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE); } else { // Otherwise update any affected breaks by inserting a new break at the appropriate point // and removing the old affected break - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); - if ($key != $newReference) { - $pSheet->setBreak($newReference, $value) - ->setBreak($key, Worksheet::BREAK_NONE); + $newReference = $this->updateCellReference($cellAddress); + if ($cellAddress !== $newReference) { + $worksheet->setBreak($newReference, $value) + ->setBreak($cellAddress, Worksheet::BREAK_NONE); } } } @@ -178,76 +156,108 @@ protected function adjustPageBreaks(Worksheet $pSheet, $pBefore, $beforeColumnIn /** * Update cell comments when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing */ - protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustComments($worksheet): void { - $aComments = $pSheet->getComments(); + $aComments = $worksheet->getComments(); $aNewComments = []; // the new array of all comments - foreach ($aComments as $key => &$value) { + foreach ($aComments as $cellAddress => &$value) { // Any comments inside a deleted range will be ignored - if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) { // Otherwise build a new array of comments indexed by the adjusted cell reference - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($cellAddress); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments - $pSheet->setComments($aNewComments); + $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows): void { - $aHyperlinkCollection = $pSheet->getHyperlinkCollection(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']); + $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); + ($numberOfColumns > 0 || $numberOfRows > 0) + ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort']) + : uksort($aHyperlinkCollection, [self::class, 'cellSort']); + + foreach ($aHyperlinkCollection as $cellAddress => $value) { + $newReference = $this->updateCellReference($cellAddress); + if ($this->cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) { + $worksheet->setHyperlink($cellAddress, null); + } elseif ($cellAddress !== $newReference) { + $worksheet->setHyperlink($newReference, $value); + $worksheet->setHyperlink($cellAddress, null); + } + } + } - foreach ($aHyperlinkCollection as $key => $value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); - if ($key != $newReference) { - $pSheet->setHyperlink($newReference, $value); - $pSheet->setHyperlink($key, null); + /** + * Update conditional formatting styles when inserting/deleting rows/columns. + * + * @param Worksheet $worksheet The worksheet that we're editing + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows): void + { + $aStyles = $worksheet->getConditionalStylesCollection(); + ($numberOfColumns > 0 || $numberOfRows > 0) + ? uksort($aStyles, [self::class, 'cellReverseSort']) + : uksort($aStyles, [self::class, 'cellSort']); + + foreach ($aStyles as $cellAddress => $cfRules) { + $worksheet->removeConditionalStyles($cellAddress); + $newReference = $this->updateCellReference($cellAddress); + + foreach ($cfRules as &$cfRule) { + /** @var Conditional $cfRule */ + $conditions = $cfRule->getConditions(); + foreach ($conditions as &$condition) { + if (is_string($condition)) { + $condition = $this->updateFormulaReferences( + $condition, + $this->cellReferenceHelper->beforeCellAddress(), + $numberOfColumns, + $numberOfRows, + $worksheet->getTitle(), + true + ); + } + } + $cfRule->setConditions($conditions); } + $worksheet->setConditionalStyles($newReference, $cfRules); } } /** * Update data validations when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustDataValidations(Worksheet $worksheet, $numberOfColumns, $numberOfRows): void { - $aDataValidationCollection = $pSheet->getDataValidationCollection(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']); - - foreach ($aDataValidationCollection as $key => $value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); - if ($key != $newReference) { - $pSheet->setDataValidation($newReference, $value); - $pSheet->setDataValidation($key, null); + $aDataValidationCollection = $worksheet->getDataValidationCollection(); + ($numberOfColumns > 0 || $numberOfRows > 0) + ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort']) + : uksort($aDataValidationCollection, [self::class, 'cellSort']); + + foreach ($aDataValidationCollection as $cellAddress => $value) { + $newReference = $this->updateCellReference($cellAddress); + if ($cellAddress !== $newReference) { + $worksheet->setDataValidation($newReference, $value); + $worksheet->setDataValidation($cellAddress, null); } } } @@ -255,44 +265,37 @@ protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, /** * Update merged cells when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing */ - protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustMergeCells(Worksheet $worksheet): void { - $aMergeCells = $pSheet->getMergeCells(); + $aMergeCells = $worksheet->getMergeCells(); $aNewMergeCells = []; // the new array of all merge cells - foreach ($aMergeCells as $key => &$value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + foreach ($aMergeCells as $cellAddress => &$value) { + $newReference = $this->updateCellReference($cellAddress); $aNewMergeCells[$newReference] = $newReference; } - $pSheet->setMergeCells($aNewMergeCells); // replace the merge cells array + $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array } /** * Update protected cells when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustProtectedCells(Worksheet $worksheet, $numberOfColumns, $numberOfRows): void { - $aProtectedCells = $pSheet->getProtectedCells(); - ($pNumCols > 0 || $pNumRows > 0) ? - uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']); - foreach ($aProtectedCells as $key => $value) { - $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); - if ($key != $newReference) { - $pSheet->protectCells($newReference, $value, true); - $pSheet->unprotectCells($key); + $aProtectedCells = $worksheet->getProtectedCells(); + ($numberOfColumns > 0 || $numberOfRows > 0) + ? uksort($aProtectedCells, [self::class, 'cellReverseSort']) + : uksort($aProtectedCells, [self::class, 'cellSort']); + foreach ($aProtectedCells as $cellAddress => $value) { + $newReference = $this->updateCellReference($cellAddress); + if ($cellAddress !== $newReference) { + $worksheet->protectCells($newReference, $value, true); + $worksheet->unprotectCells($cellAddress); } } } @@ -300,54 +303,47 @@ protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $ /** * Update column dimensions when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing */ - protected function adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustColumnDimensions(Worksheet $worksheet): void { - $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true); + $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true); if (!empty($aColumnDimensions)) { foreach ($aColumnDimensions as $objColumnDimension) { - $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1'); [$newReference] = Coordinate::coordinateFromString($newReference); - if ($objColumnDimension->getColumnIndex() != $newReference) { + if ($objColumnDimension->getColumnIndex() !== $newReference) { $objColumnDimension->setColumnIndex($newReference); } } - $pSheet->refreshColumnDimensions(); + $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * - * @param Worksheet $pSheet The worksheet that we're editing - * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') - * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing * @param int $beforeRow Number of the row we're inserting/deleting before - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ - protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + protected function adjustRowDimensions(Worksheet $worksheet, $beforeRow, $numberOfRows): void { - $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true); + $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true); if (!empty($aRowDimensions)) { foreach ($aRowDimensions as $objRowDimension) { - $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex()); [, $newReference] = Coordinate::coordinateFromString($newReference); - if ($objRowDimension->getRowIndex() != $newReference) { - $objRowDimension->setRowIndex($newReference); + $newRoweference = (int) $newReference; + if ($objRowDimension->getRowIndex() !== $newRoweference) { + $objRowDimension->setRowIndex($newRoweference); } } - $pSheet->refreshRowDimensions(); + $worksheet->refreshRowDimensions(); - $copyDimension = $pSheet->getRowDimension($beforeRow - 1); - for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) { - $newDimension = $pSheet->getRowDimension($i); + $copyDimension = $worksheet->getRowDimension($beforeRow - 1); + for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) { + $newDimension = $worksheet->getRowDimension($i); $newDimension->setRowHeight($copyDimension->getRowHeight()); $newDimension->setVisible($copyDimension->getVisible()); $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); @@ -359,52 +355,62 @@ protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $p /** * Insert a new column or row, updating all possible related data. * - * @param string $pBefore Insert before this cell address (e.g. 'A1') - * @param int $pNumCols Number of columns to insert/delete (negative values indicate deletion) - * @param int $pNumRows Number of rows to insert/delete (negative values indicate deletion) - * @param Worksheet $pSheet The worksheet that we're editing - * - * @throws Exception + * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1') + * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) + * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) + * @param Worksheet $worksheet The worksheet that we're editing */ - public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pSheet) - { - $remove = ($pNumCols < 0 || $pNumRows < 0); - $allCoordinates = $pSheet->getCoordinates(); + public function insertNewBefore( + string $beforeCellAddress, + int $numberOfColumns, + int $numberOfRows, + Worksheet $worksheet + ): void { + $remove = ($numberOfColumns < 0 || $numberOfRows < 0); + $allCoordinates = $worksheet->getCoordinates(); + + if ( + $this->cellReferenceHelper === null || + $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) + ) { + $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); + } - // Get coordinate of $pBefore - [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore); - $beforeColumnIndex = Coordinate::columnIndexFromString($beforeColumn); + // Get coordinate of $beforeCellAddress + [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); + $highestColumn = $worksheet->getHighestColumn(); + $highestRow = $worksheet->getHighestRow(); // 1. Clear column strips if we are removing columns - if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) { - for ($i = 1; $i <= $highestRow - 1; ++$i) { - for ($j = $beforeColumnIndex - 1 + $pNumCols; $j <= $beforeColumnIndex - 2; ++$j) { - $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i; - $pSheet->removeConditionalStyles($coordinate); - if ($pSheet->cellExists($coordinate)) { - $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); - $pSheet->getCell($coordinate)->setXfIndex(0); - } - } - } + if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { + $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet); } // 2. Clear row strips if we are removing rows - if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) { - for ($i = $beforeColumnIndex - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$i) { - for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) { - $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j; - $pSheet->removeConditionalStyles($coordinate); - if ($pSheet->cellExists($coordinate)) { - $pSheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); - $pSheet->getCell($coordinate)->setXfIndex(0); - } - } + if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { + $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet); + } + + // Find missing coordinates. This is important when inserting column before the last column + $missingCoordinates = array_filter( + array_map(function ($row) use ($highestColumn) { + return $highestColumn . $row; + }, range(1, $highestRow)), + function ($coordinate) use ($allCoordinates) { + return !in_array($coordinate, $allCoordinates); + } + ); + + // Create missing cells with null values + if (!empty($missingCoordinates)) { + foreach ($missingCoordinates as $coordinate) { + $worksheet->createNewCell($coordinate); } + + // Refresh all coordinates + $allCoordinates = $worksheet->getCoordinates(); } // Loop through cells, bottom-up, and change cell coordinate @@ -413,225 +419,156 @@ public function insertNewBefore($pBefore, $pNumCols, $pNumRows, Worksheet $pShee $allCoordinates = array_reverse($allCoordinates); } while ($coordinate = array_pop($allCoordinates)) { - $cell = $pSheet->getCell($coordinate); + $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); - if ($cellIndex - 1 + $pNumCols < 0) { + if ($cellIndex - 1 + $numberOfColumns < 0) { continue; } // New coordinate - $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $pNumCols) . ($cell->getRow() + $pNumRows); + $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows); // Should the cell be updated? Move value and cellXf index from one cell to another. - if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) { + if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles - $pSheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); + $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location - if ($cell->getDataType() == DataType::TYPE_FORMULA) { + if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted - $pSheet->getCell($newCoordinate) - ->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + $worksheet->getCell($newCoordinate) + ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle())); } else { // Formula should not be adjusted - $pSheet->getCell($newCoordinate)->setValue($cell->getValue()); + $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType()); } // Clear the original cell - $pSheet->getCellCollection()->delete($coordinate); + $worksheet->getCellCollection()->delete($coordinate); } else { /* We don't need to update styles for rows/columns before our insertion position, but we do still need to adjust any formulae in those cells */ - if ($cell->getDataType() == DataType::TYPE_FORMULA) { + if ($cell->getDataType() === DataType::TYPE_FORMULA) { // Formula should be adjusted - $cell->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle())); } } } // Duplicate styles for the newly inserted cells - $highestColumn = $pSheet->getHighestColumn(); - $highestRow = $pSheet->getHighestRow(); - - if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) { - for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { - // Style - $coordinate = Coordinate::stringFromColumnIndex($beforeColumnIndex - 1) . $i; - if ($pSheet->cellExists($coordinate)) { - $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); - $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? - $pSheet->getConditionalStyles($coordinate) : false; - for ($j = $beforeColumnIndex; $j <= $beforeColumnIndex - 1 + $pNumCols; ++$j) { - $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); - if ($conditionalStyles) { - $cloned = []; - foreach ($conditionalStyles as $conditionalStyle) { - $cloned[] = clone $conditionalStyle; - } - $pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned); - } - } - } - } + $highestColumn = $worksheet->getHighestColumn(); + $highestRow = $worksheet->getHighestRow(); + + if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { + $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns); } - if ($pNumRows > 0 && $beforeRow - 1 > 0) { - for ($i = $beforeColumnIndex; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) { - // Style - $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); - if ($pSheet->cellExists($coordinate)) { - $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); - $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? - $pSheet->getConditionalStyles($coordinate) : false; - for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { - $pSheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); - if ($conditionalStyles) { - $cloned = []; - foreach ($conditionalStyles as $conditionalStyle) { - $cloned[] = clone $conditionalStyle; - } - $pSheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned); - } - } - } - } + if ($numberOfRows > 0 && $beforeRow - 1 > 0) { + $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows); } // Update worksheet: column dimensions - $this->adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustColumnDimensions($worksheet); // Update worksheet: row dimensions - $this->adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows); // Update worksheet: page breaks - $this->adjustPageBreaks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: comments - $this->adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustComments($worksheet); // Update worksheet: hyperlinks - $this->adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows); + + // Update worksheet: conditional formatting styles + $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: data validations - $this->adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: merge cells - $this->adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustMergeCells($worksheet); // Update worksheet: protected cells - $this->adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter - $autoFilter = $pSheet->getAutoFilter(); - $autoFilterRange = $autoFilter->getRange(); - if (!empty($autoFilterRange)) { - if ($pNumCols != 0) { - $autoFilterColumns = $autoFilter->getColumns(); - if (count($autoFilterColumns) > 0) { - $column = ''; - $row = 0; - sscanf($pBefore, '%[A-Z]%d', $column, $row); - $columnIndex = Coordinate::columnIndexFromString($column); - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); - if ($columnIndex <= $rangeEnd[0]) { - if ($pNumCols < 0) { - // If we're actually deleting any columns that fall within the autofilter range, - // then we delete any rules for those columns - $deleteColumn = $columnIndex + $pNumCols - 1; - $deleteCount = abs($pNumCols); - for ($i = 1; $i <= $deleteCount; ++$i) { - if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) { - $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1)); - } - ++$deleteColumn; - } - } - $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; + $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns); - // Shuffle columns in autofilter range - if ($pNumCols > 0) { - $startColRef = $startCol; - $endColRef = $rangeEnd[0]; - $toColRef = $rangeEnd[0] + $pNumCols; - - do { - $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); - --$endColRef; - --$toColRef; - } while ($startColRef <= $endColRef); - } else { - // For delete, we shuffle from beginning to end to avoid overwriting - $startColID = Coordinate::stringFromColumnIndex($startCol); - $toColID = Coordinate::stringFromColumnIndex($startCol + $pNumCols); - $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1); - do { - $autoFilter->shiftColumn($startColID, $toColID); - ++$startColID; - ++$toColID; - } while ($startColID != $endColID); - } - } - } - } - $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows)); - } + // Update worksheet: table + $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns); // Update worksheet: freeze pane - if ($pSheet->getFreezePane()) { - $splitCell = $pSheet->getFreezePane(); - $topLeftCell = $pSheet->getTopLeftCell(); + if ($worksheet->getFreezePane()) { + $splitCell = $worksheet->getFreezePane() ?? ''; + $topLeftCell = $worksheet->getTopLeftCell() ?? ''; - $splitCell = $this->updateCellReference($splitCell, $pBefore, $pNumCols, $pNumRows); - $topLeftCell = $this->updateCellReference($topLeftCell, $pBefore, $pNumCols, $pNumRows); + $splitCell = $this->updateCellReference($splitCell); + $topLeftCell = $this->updateCellReference($topLeftCell); - $pSheet->freezePane($splitCell, $topLeftCell); + $worksheet->freezePane($splitCell, $topLeftCell); } // Page setup - if ($pSheet->getPageSetup()->isPrintAreaSet()) { - $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows)); + if ($worksheet->getPageSetup()->isPrintAreaSet()) { + $worksheet->getPageSetup()->setPrintArea( + $this->updateCellReference($worksheet->getPageSetup()->getPrintArea()) + ); } // Update worksheet: drawings - $aDrawings = $pSheet->getDrawingCollection(); + $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { - $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows); + $newReference = $this->updateCellReference($objDrawing->getCoordinates()); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } } - // Update workbook: named ranges - if (count($pSheet->getParent()->getNamedRanges()) > 0) { - foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) { - if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) { - $namedRange->setRange($this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)); + // Update workbook: define names + if (count($worksheet->getParent()->getDefinedNames()) > 0) { + foreach ($worksheet->getParent()->getDefinedNames() as $definedName) { + if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashCode() === $worksheet->getHashCode()) { + $definedName->setValue($this->updateCellReference($definedName->getValue())); } } } // Garbage collect - $pSheet->garbageCollect(); + $worksheet->garbageCollect(); } /** * Update references within formulas. * - * @param string $pFormula Formula to update - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to insert - * @param int $pNumRows Number of rows to insert - * @param string $sheetName Worksheet name/title - * - * @throws Exception + * @param string $formula Formula to update + * @param string $beforeCellAddress Insert before this one + * @param int $numberOfColumns Number of columns to insert + * @param int $numberOfRows Number of rows to insert + * @param string $worksheetName Worksheet name/title * * @return string Updated formula */ - public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') - { + public function updateFormulaReferences( + $formula = '', + $beforeCellAddress = 'A1', + $numberOfColumns = 0, + $numberOfRows = 0, + $worksheetName = '', + bool $includeAbsoluteReferences = false + ) { + if ( + $this->cellReferenceHelper === null || + $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows) + ) { + $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows); + } + // Update cell references in the formula - $formulaBlocks = explode('"', $pFormula); + $formulaBlocks = explode('"', $formula); $i = false; foreach ($formulaBlocks as &$formulaBlock) { // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) @@ -639,21 +576,21 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo $adjustCount = 0; $newCellTokens = $cellTokens = []; // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) - $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); + $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = substr($this->updateCellReference('$A' . $match[3], $pBefore, $pNumCols, $pNumRows), 2); - $modified4 = substr($this->updateCellReference('$A' . $match[4], $pBefore, $pNumCols, $pNumRows), 2); + $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences), 2); + $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences), 2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { - if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = 100000; - $row = 10000000 + trim($match[3], '$'); + $row = 10000000 + (int) trim($match[3], '$'); $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); @@ -664,16 +601,16 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo } } // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) - $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); + $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = substr($this->updateCellReference($match[3] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); - $modified4 = substr($this->updateCellReference($match[4] . '$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences), 0, -2); + $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences), 0, -2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { - if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more @@ -689,22 +626,22 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo } } // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) - $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); + $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; - $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); - $modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows); + $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences); + $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences); if ($match[3] . $match[4] !== $modified3 . $modified4) { - if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3 . ':' . $modified4; [$column, $row] = Coordinate::coordinateFromString($match[3]); // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; - $row = trim($row, '$') + 10000000; + $row = (int) trim($row, '$') + 10000000; $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); @@ -715,23 +652,25 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo } } // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) - $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/i', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); + $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', ' ' . $formulaBlock . ' ', $matches, PREG_SET_ORDER); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3]; - $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); + $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences); if ($match[3] !== $modified3) { - if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + if (($match[2] == '') || (trim($match[2], "'") == $worksheetName)) { $toString = ($match[2] > '') ? $match[2] . '!' : ''; $toString .= $modified3; [$column, $row] = Coordinate::coordinateFromString($match[3]); + $columnAdditionalIndex = $column[0] === '$' ? 1 : 0; + $rowAdditionalIndex = $row[0] === '$' ? 1 : 0; // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000; - $row = trim($row, '$') + 10000000; - $cellIndex = $row . $column; + $row = (int) trim($row, '$') + 10000000; + $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(? 0) { - if ($pNumCols > 0 || $pNumRows > 0) { + if ($numberOfColumns > 0 || $numberOfRows > 0) { krsort($cellTokens); krsort($newCellTokens); } else { @@ -758,34 +697,164 @@ public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCo return implode('"', $formulaBlocks); } + /** + * Update all cell references within a formula, irrespective of worksheet. + */ + public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string + { + $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows); + + if ($numberOfColumns !== 0) { + $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns); + } + + if ($numberOfRows !== 0) { + $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows); + } + + return $formula; + } + + private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', + $formula, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $columnLengths = array_map('strlen', array_column($splitRanges[6], 0)); + $rowLengths = array_map('strlen', array_column($splitRanges[7], 0)); + $columnOffsets = array_column($splitRanges[6], 1); + $rowOffsets = array_column($splitRanges[7], 1); + + $columns = $splitRanges[6]; + $rows = $splitRanges[7]; + + while ($splitCount > 0) { + --$splitCount; + $columnLength = $columnLengths[$splitCount]; + $rowLength = $rowLengths[$splitCount]; + $columnOffset = $columnOffsets[$splitCount]; + $rowOffset = $rowOffsets[$splitCount]; + $column = $columns[$splitCount][0]; + $row = $rows[$splitCount][0]; + + if (!empty($column) && $column[0] !== '$') { + $column = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($column) + $numberOfColumns); + $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength); + } + if (!empty($row) && $row[0] !== '$') { + $row += $numberOfRows; + $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength); + } + } + + return $formula; + } + + private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui', + $formula, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0)); + $fromColumnOffsets = array_column($splitRanges[1], 1); + $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0)); + $toColumnOffsets = array_column($splitRanges[2], 1); + + $fromColumns = $splitRanges[1]; + $toColumns = $splitRanges[2]; + + while ($splitCount > 0) { + --$splitCount; + $fromColumnLength = $fromColumnLengths[$splitCount]; + $toColumnLength = $toColumnLengths[$splitCount]; + $fromColumnOffset = $fromColumnOffsets[$splitCount]; + $toColumnOffset = $toColumnOffsets[$splitCount]; + $fromColumn = $fromColumns[$splitCount][0]; + $toColumn = $toColumns[$splitCount][0]; + + if (!empty($fromColumn) && $fromColumn[0] !== '$') { + $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns); + $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength); + } + if (!empty($toColumn) && $toColumn[0] !== '$') { + $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns); + $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength); + } + } + + return $formula; + } + + private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui', + $formula, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0)); + $fromRowOffsets = array_column($splitRanges[1], 1); + $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0)); + $toRowOffsets = array_column($splitRanges[2], 1); + + $fromRows = $splitRanges[1]; + $toRows = $splitRanges[2]; + + while ($splitCount > 0) { + --$splitCount; + $fromRowLength = $fromRowLengths[$splitCount]; + $toRowLength = $toRowLengths[$splitCount]; + $fromRowOffset = $fromRowOffsets[$splitCount]; + $toRowOffset = $toRowOffsets[$splitCount]; + $fromRow = $fromRows[$splitCount][0]; + $toRow = $toRows[$splitCount][0]; + + if (!empty($fromRow) && $fromRow[0] !== '$') { + $fromRow += $numberOfRows; + $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength); + } + if (!empty($toRow) && $toRow[0] !== '$') { + $toRow += $numberOfRows; + $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength); + } + } + + return $formula; + } + /** * Update cell reference. * - * @param string $pCellRange Cell range - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment - * - * @throws Exception + * @param string $cellReference Cell address or range of addresses * * @return string Updated cell range */ - public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + private function updateCellReference($cellReference = 'A1', bool $includeAbsoluteReferences = false) { // Is it in another worksheet? Will not have to update anything. - if (strpos($pCellRange, '!') !== false) { - return $pCellRange; + if (strpos($cellReference, '!') !== false) { + return $cellReference; // Is it a range or a single cell? - } elseif (!Coordinate::coordinateIsRange($pCellRange)) { + } elseif (!Coordinate::coordinateIsRange($cellReference)) { // Single cell - return $this->updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows); - } elseif (Coordinate::coordinateIsRange($pCellRange)) { + return $this->cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences); + } elseif (Coordinate::coordinateIsRange($cellReference)) { // Range - return $this->updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows); + return $this->updateCellRange($cellReference, $includeAbsoluteReferences); } // Return original - return $pCellRange; + return $cellReference; } /** @@ -795,7 +864,7 @@ public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCo * @param string $oldName Old name (name to replace) * @param string $newName New name */ - public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $newName = '') + public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $newName = ''): void { if ($oldName == '') { return; @@ -804,7 +873,7 @@ public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $ne foreach ($spreadsheet->getWorksheetIterator() as $sheet) { foreach ($sheet->getCoordinates(false) as $coordinate) { $cell = $sheet->getCell($coordinate); - if (($cell !== null) && ($cell->getDataType() == DataType::TYPE_FORMULA)) { + if (($cell !== null) && ($cell->getDataType() === DataType::TYPE_FORMULA)) { $formula = $cell->getValue(); if (strpos($formula, $oldName) !== false) { $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); @@ -819,35 +888,32 @@ public function updateNamedFormulas(Spreadsheet $spreadsheet, $oldName = '', $ne /** * Update cell range. * - * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment - * - * @throws Exception + * @param string $cellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') * * @return string Updated cell range */ - private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false): string { - if (!Coordinate::coordinateIsRange($pCellRange)) { + if (!Coordinate::coordinateIsRange($cellRange)) { throw new Exception('Only cell ranges may be passed to this method.'); } // Update range - $range = Coordinate::splitRange($pCellRange); + $range = Coordinate::splitRange($cellRange); $ic = count($range); for ($i = 0; $i < $ic; ++$i) { $jc = count($range[$i]); for ($j = 0; $j < $jc; ++$j) { if (ctype_alpha($range[$i][$j])) { - $r = Coordinate::coordinateFromString($this->updateSingleCellReference($range[$i][$j] . '1', $pBefore, $pNumCols, $pNumRows)); - $range[$i][$j] = $r[0]; + $range[$i][$j] = Coordinate::coordinateFromString( + $this->cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences) + )[0]; } elseif (ctype_digit($range[$i][$j])) { - $r = Coordinate::coordinateFromString($this->updateSingleCellReference('A' . $range[$i][$j], $pBefore, $pNumCols, $pNumRows)); - $range[$i][$j] = $r[1]; + $range[$i][$j] = Coordinate::coordinateFromString( + $this->cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences) + )[1]; } else { - $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); + $range[$i][$j] = $this->cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences); } } } @@ -856,52 +922,225 @@ private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCo return Coordinate::buildRange($range); } - /** - * Update single cell reference. - * - * @param string $pCellReference Single cell reference - * @param string $pBefore Insert before this one - * @param int $pNumCols Number of columns to increment - * @param int $pNumRows Number of rows to increment - * - * @throws Exception - * - * @return string Updated cell reference - */ - private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void { - if (Coordinate::coordinateIsRange($pCellReference)) { - throw new Exception('Only single cell references may be passed to this method.'); + for ($i = 1; $i <= $highestRow - 1; ++$i) { + for ($j = $beforeColumn - 1 + $numberOfColumns; $j <= $beforeColumn - 2; ++$j) { + $coordinate = Coordinate::stringFromColumnIndex($j + 1) . $i; + $worksheet->removeConditionalStyles($coordinate); + if ($worksheet->cellExists($coordinate)) { + $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); + $worksheet->getCell($coordinate)->setXfIndex(0); + } + } } + } - // Get coordinate of $pBefore - [$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($pBefore); + private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void + { + $lastColumnIndex = Coordinate::columnIndexFromString($highestColumn) - 1; + + for ($i = $beforeColumn - 1; $i <= $lastColumnIndex; ++$i) { + for ($j = $beforeRow + $numberOfRows; $j <= $beforeRow - 1; ++$j) { + $coordinate = Coordinate::stringFromColumnIndex($i + 1) . $j; + $worksheet->removeConditionalStyles($coordinate); + if ($worksheet->cellExists($coordinate)) { + $worksheet->getCell($coordinate)->setValueExplicit('', DataType::TYPE_NULL); + $worksheet->getCell($coordinate)->setXfIndex(0); + } + } + } + } - // Get coordinate of $pCellReference - [$newColumn, $newRow] = Coordinate::coordinateFromString($pCellReference); + private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void + { + $autoFilter = $worksheet->getAutoFilter(); + $autoFilterRange = $autoFilter->getRange(); + if (!empty($autoFilterRange)) { + if ($numberOfColumns !== 0) { + $autoFilterColumns = $autoFilter->getColumns(); + if (count($autoFilterColumns) > 0) { + $column = ''; + $row = 0; + sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); + $columnIndex = Coordinate::columnIndexFromString($column); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange); + if ($columnIndex <= $rangeEnd[0]) { + if ($numberOfColumns < 0) { + $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter); + } + $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; - // Verify which parts should be updated - $updateColumn = (($newColumn[0] != '$') && ($beforeColumn[0] != '$') && (Coordinate::columnIndexFromString($newColumn) >= Coordinate::columnIndexFromString($beforeColumn))); - $updateRow = (($newRow[0] != '$') && ($beforeRow[0] != '$') && $newRow >= $beforeRow); + // Shuffle columns in autofilter range + if ($numberOfColumns > 0) { + $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); + } else { + $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter); + } + } + } + } + + $worksheet->setAutoFilter( + $this->updateCellReference($autoFilterRange) + ); + } + } + + private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void + { + // If we're actually deleting any columns that fall within the autofilter range, + // then we delete any rules for those columns + $deleteColumn = $columnIndex + $numberOfColumns - 1; + $deleteCount = abs($numberOfColumns); + + for ($i = 1; $i <= $deleteCount; ++$i) { + $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); + if (isset($autoFilterColumns[$columnName])) { + $autoFilter->clearColumn($columnName); + } + ++$deleteColumn; + } + } + + private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void + { + $startColRef = $startCol; + $endColRef = $rangeEnd; + $toColRef = $rangeEnd + $numberOfColumns; + + do { + $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); + --$endColRef; + --$toColRef; + } while ($startColRef <= $endColRef); + } + + private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void + { + // For delete, we shuffle from beginning to end to avoid overwriting + $startColID = Coordinate::stringFromColumnIndex($startCol); + $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); + $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); + + do { + $autoFilter->shiftColumn($startColID, $toColID); + ++$startColID; + ++$toColID; + } while ($startColID !== $endColID); + } + + private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void + { + $tableCollection = $worksheet->getTableCollection(); + + foreach ($tableCollection as $table) { + $tableRange = $table->getRange(); + if (!empty($tableRange)) { + if ($numberOfColumns !== 0) { + $tableColumns = $table->getColumns(); + if (count($tableColumns) > 0) { + $column = ''; + $row = 0; + sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row); + $columnIndex = Coordinate::columnIndexFromString($column); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange); + if ($columnIndex <= $rangeEnd[0]) { + if ($numberOfColumns < 0) { + $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table); + } + $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; + + // Shuffle columns in table range + if ($numberOfColumns > 0) { + $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table); + } else { + $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table); + } + } + } + } - // Create new column reference - if ($updateColumn) { - $newColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($newColumn) + $pNumCols); + $table->setRange($this->updateCellReference($tableRange)); + } } + } - // Create new row reference - if ($updateRow) { - $newRow = $newRow + $pNumRows; + private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void + { + // If we're actually deleting any columns that fall within the table range, + // then we delete any rules for those columns + $deleteColumn = $columnIndex + $numberOfColumns - 1; + $deleteCount = abs($numberOfColumns); + + for ($i = 1; $i <= $deleteCount; ++$i) { + $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1); + if (isset($tableColumns[$columnName])) { + $table->clearColumn($columnName); + } + ++$deleteColumn; } + } - // Return new reference - return $newColumn . $newRow; + private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void + { + $startColRef = $startCol; + $endColRef = $rangeEnd; + $toColRef = $rangeEnd + $numberOfColumns; + + do { + $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef)); + --$endColRef; + --$toColRef; + } while ($startColRef <= $endColRef); + } + + private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void + { + // For delete, we shuffle from beginning to end to avoid overwriting + $startColID = Coordinate::stringFromColumnIndex($startCol); + $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns); + $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1); + + do { + $table->shiftColumn($startColID, $toColID); + ++$startColID; + ++$toColID; + } while ($startColID !== $endColID); + } + + private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void + { + $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1); + for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { + // Style + $coordinate = $beforeColumnName . $i; + if ($worksheet->cellExists($coordinate)) { + $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); + for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { + $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); + } + } + } + } + + private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void + { + $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); + for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) { + // Style + $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); + if ($worksheet->cellExists($coordinate)) { + $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); + for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { + $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); + } + } + } } /** * __clone implementation. Cloning should not be allowed in a Singleton! - * - * @throws Exception */ final public function __clone() { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php index 69954676..39b70c86 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/ITextElement.php @@ -14,7 +14,7 @@ public function getText(); /** * Set text. * - * @param $text string Text + * @param string $text Text * * @return ITextElement */ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php index 6e90fa35..3a6e1f8e 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/RichText.php @@ -4,7 +4,6 @@ use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; class RichText implements IComparable @@ -18,40 +17,36 @@ class RichText implements IComparable /** * Create a new RichText instance. - * - * @param Cell $pCell - * - * @throws Exception */ - public function __construct(Cell $pCell = null) + public function __construct(?Cell $cell = null) { // Initialise variables $this->richTextElements = []; // Rich-Text string attached to cell? - if ($pCell !== null) { + if ($cell !== null) { // Add cell text and style - if ($pCell->getValue() != '') { - $objRun = new Run($pCell->getValue()); - $objRun->setFont(clone $pCell->getWorksheet()->getStyle($pCell->getCoordinate())->getFont()); + if ($cell->getValue() != '') { + $objRun = new Run($cell->getValue()); + $objRun->setFont(clone $cell->getWorksheet()->getStyle($cell->getCoordinate())->getFont()); $this->addText($objRun); } // Set parent value - $pCell->setValueExplicit($this, DataType::TYPE_STRING); + $cell->setValueExplicit($this, DataType::TYPE_STRING); } } /** * Add text. * - * @param ITextElement $pText Rich text element + * @param ITextElement $text Rich text element * * @return $this */ - public function addText(ITextElement $pText) + public function addText(ITextElement $text) { - $this->richTextElements[] = $pText; + $this->richTextElements[] = $text; return $this; } @@ -59,15 +54,13 @@ public function addText(ITextElement $pText) /** * Create text. * - * @param string $pText Text - * - * @throws Exception + * @param string $text Text * * @return TextElement */ - public function createText($pText) + public function createText($text) { - $objText = new TextElement($pText); + $objText = new TextElement($text); $this->addText($objText); return $objText; @@ -76,15 +69,13 @@ public function createText($pText) /** * Create text run. * - * @param string $pText Text - * - * @throws Exception + * @param string $text Text * * @return Run */ - public function createTextRun($pText) + public function createTextRun($text) { - $objText = new Run($pText); + $objText = new Run($text); $this->addText($objText); return $objText; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php index aa4a8e46..9c9f8072 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/Run.php @@ -16,11 +16,11 @@ class Run extends TextElement implements ITextElement /** * Create a new Run instance. * - * @param string $pText Text + * @param string $text Text */ - public function __construct($pText = '') + public function __construct($text = '') { - parent::__construct($pText); + parent::__construct($text); // Initialise variables $this->font = new Font(); } @@ -38,13 +38,13 @@ public function getFont() /** * Set font. * - * @param Font $pFont Font + * @param Font $font Font * * @return $this */ - public function setFont(Font $pFont = null) + public function setFont(?Font $font = null) { - $this->font = $pFont; + $this->font = $font; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php index f8be5d55..6bec005b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/RichText/TextElement.php @@ -14,12 +14,12 @@ class TextElement implements ITextElement /** * Create a new TextElement instance. * - * @param string $pText Text + * @param string $text Text */ - public function __construct($pText = '') + public function __construct($text = '') { // Initialise variables - $this->text = $pText; + $this->text = $text; } /** @@ -35,7 +35,7 @@ public function getText() /** * Set text. * - * @param $text string Text + * @param string $text Text * * @return $this */ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php index 03fa6ac2..5fbbadb6 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php @@ -5,6 +5,8 @@ use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Chart\Renderer\IRenderer; use PhpOffice\PhpSpreadsheet\Collection\Memory; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestFactoryInterface; use Psr\SimpleCache\CacheInterface; class Settings @@ -22,27 +24,26 @@ class Settings * * @var int */ - private static $libXmlLoaderOptions = null; + private static $libXmlLoaderOptions; /** - * Allow/disallow libxml_disable_entity_loader() call when not thread safe. - * Default behaviour is to do the check, but if you're running PHP versions - * 7.2 < 7.2.1 - * 7.1 < 7.1.13 - * 7.0 < 7.0.27 - * then you may need to disable this check to prevent unwanted behaviour in other threads - * SECURITY WARNING: Changing this flag is not recommended. + * The cache implementation to be used for cell collection. * - * @var bool + * @var CacheInterface */ - private static $libXmlDisableEntityLoader = true; + private static $cache; /** - * The cache implementation to be used for cell collection. + * The HTTP client implementation to be used for network request. * - * @var CacheInterface + * @var null|ClientInterface */ - private static $cache; + private static $httpClient; + + /** + * @var null|RequestFactoryInterface + */ + private static $requestFactory; /** * Set the locale code to use for formula translations and any special formatting. @@ -51,26 +52,29 @@ class Settings * * @return bool Success or failure */ - public static function setLocale($locale) + public static function setLocale(string $locale) { return Calculation::getInstance()->setLocale($locale); } + public static function getLocale(): string + { + return Calculation::getInstance()->getLocale(); + } + /** * Identify to PhpSpreadsheet the external library to use for rendering charts. * - * @param string $rendererClass Class name of the chart renderer + * @param string $rendererClassName Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph - * - * @throws Exception */ - public static function setChartRenderer($rendererClass) + public static function setChartRenderer(string $rendererClassName): void { - if (!is_a($rendererClass, IRenderer::class, true)) { + if (!is_a($rendererClassName, IRenderer::class, true)) { throw new Exception('Chart renderer must implement ' . IRenderer::class); } - self::$chartRenderer = $rendererClass; + self::$chartRenderer = $rendererClassName; } /** @@ -79,17 +83,22 @@ public static function setChartRenderer($rendererClass) * @return null|string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ - public static function getChartRenderer() + public static function getChartRenderer(): ?string { return self::$chartRenderer; } + public static function htmlEntityFlags(): int + { + return \ENT_COMPAT; + } + /** * Set default options for libxml loader. * * @param int $options Default options for libxml loader */ - public static function setLibXmlLoaderOptions($options) + public static function setLibXmlLoaderOptions($options): void { if ($options === null && defined('LIBXML_DTDLOAD')) { $options = LIBXML_DTDLOAD | LIBXML_DTDATTR; @@ -103,60 +112,53 @@ public static function setLibXmlLoaderOptions($options) * * @return int Default options for libxml loader */ - public static function getLibXmlLoaderOptions() + public static function getLibXmlLoaderOptions(): int { if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) { self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); } elseif (self::$libXmlLoaderOptions === null) { - self::$libXmlLoaderOptions = true; + self::$libXmlLoaderOptions = 0; } return self::$libXmlLoaderOptions; } /** - * Enable/Disable the entity loader for libxml loader. - * Allow/disallow libxml_disable_entity_loader() call when not thread safe. - * Default behaviour is to do the check, but if you're running PHP versions - * 7.2 < 7.2.1 - * 7.1 < 7.1.13 - * 7.0 < 7.0.27 - * then you may need to disable this check to prevent unwanted behaviour in other threads - * SECURITY WARNING: Changing this flag to false is not recommended. + * Deprecated, has no effect. * * @param bool $state + * + * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+ */ - public static function setLibXmlDisableEntityLoader($state) + public static function setLibXmlDisableEntityLoader($state): void { - self::$libXmlDisableEntityLoader = (bool) $state; + // noop } /** - * Return the state of the entity loader (disabled/enabled) for libxml loader. + * Deprecated, has no effect. * * @return bool $state + * + * @deprecated will be removed without replacement as it is no longer necessary on PHP 7.3.0+ */ - public static function getLibXmlDisableEntityLoader() + public static function getLibXmlDisableEntityLoader(): bool { - return self::$libXmlDisableEntityLoader; + return true; } /** * Sets the implementation of cache that should be used for cell collection. - * - * @param CacheInterface $cache */ - public static function setCache(CacheInterface $cache) + public static function setCache(CacheInterface $cache): void { self::$cache = $cache; } /** - * Gets the implementation of cache that should be used for cell collection. - * - * @return CacheInterface + * Gets the implementation of cache that is being used for cell collection. */ - public static function getCache() + public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = new Memory(); @@ -164,4 +166,49 @@ public static function getCache() return self::$cache; } + + /** + * Set the HTTP client implementation to be used for network request. + */ + public static function setHttpClient(ClientInterface $httpClient, RequestFactoryInterface $requestFactory): void + { + self::$httpClient = $httpClient; + self::$requestFactory = $requestFactory; + } + + /** + * Unset the HTTP client configuration. + */ + public static function unsetHttpClient(): void + { + self::$httpClient = null; + self::$requestFactory = null; + } + + /** + * Get the HTTP client implementation to be used for network request. + */ + public static function getHttpClient(): ClientInterface + { + self::assertHttpClient(); + + return self::$httpClient; + } + + /** + * Get the HTTP request factory. + */ + public static function getRequestFactory(): RequestFactoryInterface + { + self::assertHttpClient(); + + return self::$requestFactory; + } + + private static function assertHttpClient(): void + { + if (!self::$httpClient || !self::$requestFactory) { + throw new Exception('HTTP client must be configured via Settings::setHttpClient() to be able to use WEBSERVICE function.'); + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php index 4b578242..8718a613 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/CodePage.php @@ -6,133 +6,109 @@ class CodePage { + public const DEFAULT_CODE_PAGE = 'CP1252'; + + /** @var array */ + private static $pageArray = [ + 0 => 'CP1252', // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program + 367 => 'ASCII', // ASCII + 437 => 'CP437', // OEM US + //720 => 'notsupported', // OEM Arabic + 737 => 'CP737', // OEM Greek + 775 => 'CP775', // OEM Baltic + 850 => 'CP850', // OEM Latin I + 852 => 'CP852', // OEM Latin II (Central European) + 855 => 'CP855', // OEM Cyrillic + 857 => 'CP857', // OEM Turkish + 858 => 'CP858', // OEM Multilingual Latin I with Euro + 860 => 'CP860', // OEM Portugese + 861 => 'CP861', // OEM Icelandic + 862 => 'CP862', // OEM Hebrew + 863 => 'CP863', // OEM Canadian (French) + 864 => 'CP864', // OEM Arabic + 865 => 'CP865', // OEM Nordic + 866 => 'CP866', // OEM Cyrillic (Russian) + 869 => 'CP869', // OEM Greek (Modern) + 874 => 'CP874', // ANSI Thai + 932 => 'CP932', // ANSI Japanese Shift-JIS + 936 => 'CP936', // ANSI Chinese Simplified GBK + 949 => 'CP949', // ANSI Korean (Wansung) + 950 => 'CP950', // ANSI Chinese Traditional BIG5 + 1200 => 'UTF-16LE', // UTF-16 (BIFF8) + 1250 => 'CP1250', // ANSI Latin II (Central European) + 1251 => 'CP1251', // ANSI Cyrillic + 1252 => 'CP1252', // ANSI Latin I (BIFF4-BIFF7) + 1253 => 'CP1253', // ANSI Greek + 1254 => 'CP1254', // ANSI Turkish + 1255 => 'CP1255', // ANSI Hebrew + 1256 => 'CP1256', // ANSI Arabic + 1257 => 'CP1257', // ANSI Baltic + 1258 => 'CP1258', // ANSI Vietnamese + 1361 => 'CP1361', // ANSI Korean (Johab) + 10000 => 'MAC', // Apple Roman + 10001 => 'CP932', // Macintosh Japanese + 10002 => 'CP950', // Macintosh Chinese Traditional + 10003 => 'CP1361', // Macintosh Korean + 10004 => 'MACARABIC', // Apple Arabic + 10005 => 'MACHEBREW', // Apple Hebrew + 10006 => 'MACGREEK', // Macintosh Greek + 10007 => 'MACCYRILLIC', // Macintosh Cyrillic + 10008 => 'CP936', // Macintosh - Simplified Chinese (GB 2312) + 10010 => 'MACROMANIA', // Macintosh Romania + 10017 => 'MACUKRAINE', // Macintosh Ukraine + 10021 => 'MACTHAI', // Macintosh Thai + 10029 => ['MACCENTRALEUROPE', 'MAC-CENTRALEUROPE'], // Macintosh Central Europe + 10079 => 'MACICELAND', // Macintosh Icelandic + 10081 => 'MACTURKISH', // Macintosh Turkish + 10082 => 'MACCROATIAN', // Macintosh Croatian + 21010 => 'UTF-16LE', // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE + 32768 => 'MAC', // Apple Roman + //32769 => 'unsupported', // ANSI Latin I (BIFF2-BIFF3) + 65000 => 'UTF-7', // Unicode (UTF-7) + 65001 => 'UTF-8', // Unicode (UTF-8) + 99999 => ['unsupported'], // Unicode (UTF-8) + ]; + + public static function validate(string $codePage): bool + { + return in_array($codePage, self::$pageArray, true); + } + /** * Convert Microsoft Code Page Identifier to Code Page Name which iconv * and mbstring understands. * * @param int $codePage Microsoft Code Page Indentifier * - * @throws PhpSpreadsheetException - * * @return string Code Page Name */ - public static function numberToName($codePage) + public static function numberToName(int $codePage): string { - switch ($codePage) { - case 367: - return 'ASCII'; // ASCII - case 437: - return 'CP437'; // OEM US - case 720: - throw new PhpSpreadsheetException('Code page 720 not supported.'); // OEM Arabic - case 737: - return 'CP737'; // OEM Greek - case 775: - return 'CP775'; // OEM Baltic - case 850: - return 'CP850'; // OEM Latin I - case 852: - return 'CP852'; // OEM Latin II (Central European) - case 855: - return 'CP855'; // OEM Cyrillic - case 857: - return 'CP857'; // OEM Turkish - case 858: - return 'CP858'; // OEM Multilingual Latin I with Euro - case 860: - return 'CP860'; // OEM Portugese - case 861: - return 'CP861'; // OEM Icelandic - case 862: - return 'CP862'; // OEM Hebrew - case 863: - return 'CP863'; // OEM Canadian (French) - case 864: - return 'CP864'; // OEM Arabic - case 865: - return 'CP865'; // OEM Nordic - case 866: - return 'CP866'; // OEM Cyrillic (Russian) - case 869: - return 'CP869'; // OEM Greek (Modern) - case 874: - return 'CP874'; // ANSI Thai - case 932: - return 'CP932'; // ANSI Japanese Shift-JIS - case 936: - return 'CP936'; // ANSI Chinese Simplified GBK - case 949: - return 'CP949'; // ANSI Korean (Wansung) - case 950: - return 'CP950'; // ANSI Chinese Traditional BIG5 - case 1200: - return 'UTF-16LE'; // UTF-16 (BIFF8) - case 1250: - return 'CP1250'; // ANSI Latin II (Central European) - case 1251: - return 'CP1251'; // ANSI Cyrillic - case 0: - // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program - case 1252: - return 'CP1252'; // ANSI Latin I (BIFF4-BIFF7) - case 1253: - return 'CP1253'; // ANSI Greek - case 1254: - return 'CP1254'; // ANSI Turkish - case 1255: - return 'CP1255'; // ANSI Hebrew - case 1256: - return 'CP1256'; // ANSI Arabic - case 1257: - return 'CP1257'; // ANSI Baltic - case 1258: - return 'CP1258'; // ANSI Vietnamese - case 1361: - return 'CP1361'; // ANSI Korean (Johab) - case 10000: - return 'MAC'; // Apple Roman - case 10001: - return 'CP932'; // Macintosh Japanese - case 10002: - return 'CP950'; // Macintosh Chinese Traditional - case 10003: - return 'CP1361'; // Macintosh Korean - case 10004: - return 'MACARABIC'; // Apple Arabic - case 10005: - return 'MACHEBREW'; // Apple Hebrew - case 10006: - return 'MACGREEK'; // Macintosh Greek - case 10007: - return 'MACCYRILLIC'; // Macintosh Cyrillic - case 10008: - return 'CP936'; // Macintosh - Simplified Chinese (GB 2312) - case 10010: - return 'MACROMANIA'; // Macintosh Romania - case 10017: - return 'MACUKRAINE'; // Macintosh Ukraine - case 10021: - return 'MACTHAI'; // Macintosh Thai - case 10029: - return 'MACCENTRALEUROPE'; // Macintosh Central Europe - case 10079: - return 'MACICELAND'; // Macintosh Icelandic - case 10081: - return 'MACTURKISH'; // Macintosh Turkish - case 10082: - return 'MACCROATIAN'; // Macintosh Croatian - case 21010: - return 'UTF-16LE'; // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE - case 32768: - return 'MAC'; // Apple Roman - case 32769: - throw new PhpSpreadsheetException('Code page 32769 not supported.'); // ANSI Latin I (BIFF2-BIFF3) - case 65000: - return 'UTF-7'; // Unicode (UTF-7) - case 65001: - return 'UTF-8'; // Unicode (UTF-8) + if (array_key_exists($codePage, self::$pageArray)) { + $value = self::$pageArray[$codePage]; + if (is_array($value)) { + foreach ($value as $encoding) { + if (@iconv('UTF-8', $encoding, ' ') !== false) { + self::$pageArray[$codePage] = $encoding; + + return $encoding; + } + } + + throw new PhpSpreadsheetException("Code page $codePage not implemented on this system."); + } else { + return $value; + } + } + if ($codePage == 720 || $codePage == 32769) { + throw new PhpSpreadsheetException("Code page $codePage not supported."); // OEM Arabic } throw new PhpSpreadsheetException('Unknown codepage: ' . $codePage); } + + public static function getEncodings(): array + { + return self::$pageArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php index 5d2deb32..87278073 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Date.php @@ -2,11 +2,16 @@ namespace PhpOffice\PhpSpreadsheet\Shared; +use DateTime; use DateTimeInterface; use DateTimeZone; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; +use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; +use PhpOffice\PhpSpreadsheet\Exception; +use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Date @@ -57,22 +62,24 @@ class Date /** * Default timezone to use for DateTime objects. * - * @var null|\DateTimeZone + * @var null|DateTimeZone */ protected static $defaultTimeZone; /** * Set the Excel calendar (Windows 1900 or Mac 1904). * - * @param int $baseDate Excel base date (1900 or 1904) + * @param int $baseYear Excel base date (1900 or 1904) * * @return bool Success or failure */ - public static function setExcelCalendar($baseDate) + public static function setExcelCalendar($baseYear) { - if (($baseDate == self::CALENDAR_WINDOWS_1900) || - ($baseDate == self::CALENDAR_MAC_1904)) { - self::$excelCalendar = $baseDate; + if ( + ($baseYear == self::CALENDAR_WINDOWS_1900) || + ($baseYear == self::CALENDAR_MAC_1904) + ) { + self::$excelCalendar = $baseYear; return true; } @@ -93,57 +100,94 @@ public static function getExcelCalendar() /** * Set the Default timezone to use for dates. * - * @param DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions + * @param null|DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions * - * @throws \Exception - * - * @return bool Success or failure * @return bool Success or failure */ public static function setDefaultTimezone($timeZone) { - if ($timeZone = self::validateTimeZone($timeZone)) { + try { + $timeZone = self::validateTimeZone($timeZone); self::$defaultTimeZone = $timeZone; - - return true; + $retval = true; + } catch (PhpSpreadsheetException $e) { + $retval = false; } - return false; + return $retval; } /** - * Return the Default timezone being used for dates. - * - * @return DateTimeZone The timezone being used as default for Excel timestamp to PHP DateTime object + * Return the Default timezone, or UTC if default not set. */ - public static function getDefaultTimezone() + public static function getDefaultTimezone(): DateTimeZone { - if (self::$defaultTimeZone === null) { - self::$defaultTimeZone = new DateTimeZone('UTC'); - } + return self::$defaultTimeZone ?? new DateTimeZone('UTC'); + } + + /** + * Return the Default timezone, or local timezone if default is not set. + */ + public static function getDefaultOrLocalTimezone(): DateTimeZone + { + return self::$defaultTimeZone ?? new DateTimeZone(date_default_timezone_get()); + } + /** + * Return the Default timezone even if null. + */ + public static function getDefaultTimezoneOrNull(): ?DateTimeZone + { return self::$defaultTimeZone; } /** * Validate a timezone. * - * @param DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object - * - * @throws \Exception + * @param null|DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object * - * @return DateTimeZone The timezone as a timezone object - * @return DateTimeZone The timezone as a timezone object + * @return ?DateTimeZone The timezone as a timezone object */ - protected static function validateTimeZone($timeZone) + private static function validateTimeZone($timeZone) { - if (is_object($timeZone) && $timeZone instanceof DateTimeZone) { + if ($timeZone instanceof DateTimeZone || $timeZone === null) { return $timeZone; - } elseif (is_string($timeZone)) { + } + if (in_array($timeZone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC))) { return new DateTimeZone($timeZone); } - throw new \Exception('Invalid timezone'); + throw new PhpSpreadsheetException('Invalid timezone'); + } + + /** + * @param mixed $value + * + * @return float|int + */ + public static function convertIsoDate($value) + { + if (!is_string($value)) { + throw new Exception('Non-string value supplied for Iso Date conversion'); + } + + $date = new DateTime($value); + $dateErrors = DateTime::getLastErrors(); + + if (is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0)) { + throw new Exception("Invalid string $value supplied for datatype Date"); + } + + $newValue = SharedDate::PHPToExcel($date); + if ($newValue === false) { + throw new Exception("Invalid string $value supplied for datatype Date"); + } + + if (preg_match('/^\\d\\d:\\d\\d:\\d\\d/', $value) == 1) { + $newValue = fmod($newValue, 1.0); + } + + return $newValue; } /** @@ -152,30 +196,28 @@ protected static function validateTimeZone($timeZone) * @param float|int $excelTimestamp MS Excel serialized date/time value * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp, * if you don't want to treat it as a UTC value - * Use the default (UST) unless you absolutely need a conversion + * Use the default (UTC) unless you absolutely need a conversion * - * @throws \Exception - * - * @return \DateTime PHP date/time object + * @return DateTime PHP date/time object */ public static function excelToDateTimeObject($excelTimestamp, $timeZone = null) { $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone); if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) { - if ($excelTimestamp < 1.0) { + if ($excelTimestamp < 1 && self::$excelCalendar === self::CALENDAR_WINDOWS_1900) { // Unix timestamp base date - $baseDate = new \DateTime('1970-01-01', $timeZone); + $baseDate = new DateTime('1970-01-01', $timeZone); } else { // MS Excel calendar base dates if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) { // Allow adjustment for 1900 Leap Year in MS Excel - $baseDate = ($excelTimestamp < 60) ? new \DateTime('1899-12-31', $timeZone) : new \DateTime('1899-12-30', $timeZone); + $baseDate = ($excelTimestamp < 60) ? new DateTime('1899-12-31', $timeZone) : new DateTime('1899-12-30', $timeZone); } else { - $baseDate = new \DateTime('1904-01-01', $timeZone); + $baseDate = new DateTime('1904-01-01', $timeZone); } } } else { - $baseDate = new \DateTime('1899-12-30', $timeZone); + $baseDate = new DateTime('1899-12-30', $timeZone); } $days = floor($excelTimestamp); @@ -197,13 +239,13 @@ public static function excelToDateTimeObject($excelTimestamp, $timeZone = null) /** * Convert a MS serialized datetime value from Excel to a unix timestamp. + * The use of Unix timestamps, and therefore this function, is discouraged. + * They are not Y2038-safe on a 32-bit system, and have no timezone info. * * @param float|int $excelTimestamp MS Excel serialized date/time value * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp, * if you don't want to treat it as a UTC value - * Use the default (UST) unless you absolutely need a conversion - * - * @throws \Exception + * Use the default (UTC) unless you absolutely need a conversion * * @return int Unix timetamp for this date/time */ @@ -216,9 +258,10 @@ public static function excelToTimestamp($excelTimestamp, $timeZone = null) /** * Convert a date from PHP to an MS Excel serialized date/time value. * - * @param mixed $dateValue Unix Timestamp or PHP DateTime object or a string + * @param mixed $dateValue PHP DateTime object or a string - Unix timestamp is also permitted, but discouraged; + * not Y2038-safe on a 32-bit system, and no timezone info * - * @return bool|float Excel date/time value + * @return false|float Excel date/time value * or boolean FALSE on failure */ public static function PHPToExcel($dateValue) @@ -255,18 +298,20 @@ public static function dateTimeToExcel(DateTimeInterface $dateValue) /** * Convert a Unix timestamp to an MS Excel serialized date/time value. + * The use of Unix timestamps, and therefore this function, is discouraged. + * They are not Y2038-safe on a 32-bit system, and have no timezone info. * - * @param int $dateValue Unix Timestamp + * @param int $unixTimestamp Unix Timestamp * - * @return float MS Excel serialized date/time value + * @return false|float MS Excel serialized date/time value */ - public static function timestampToExcel($dateValue) + public static function timestampToExcel($unixTimestamp) { - if (!is_numeric($dateValue)) { + if (!is_numeric($unixTimestamp)) { return false; } - return self::dateTimeToExcel(new \DateTime('@' . $dateValue)); + return self::dateTimeToExcel(new DateTime('@' . $unixTimestamp)); } /** @@ -307,8 +352,8 @@ public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $min } // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) - $century = substr($year, 0, 2); - $decade = substr($year, 2, 2); + $century = (int) substr($year, 0, 2); + $decade = (int) substr($year, 2, 2); $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; @@ -319,16 +364,14 @@ public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $min /** * Is a given cell a date/time? * - * @param Cell $pCell - * * @return bool */ - public static function isDateTime(Cell $pCell) + public static function isDateTime(Cell $cell) { - return is_numeric($pCell->getValue()) && + return is_numeric($cell->getCalculatedValue()) && self::isDateTimeFormat( - $pCell->getWorksheet()->getStyle( - $pCell->getCoordinate() + $cell->getWorksheet()->getStyle( + $cell->getCoordinate() )->getNumberFormat() ); } @@ -336,13 +379,11 @@ public static function isDateTime(Cell $pCell) /** * Is a given number format a date/time? * - * @param NumberFormat $pFormat - * * @return bool */ - public static function isDateTimeFormat(NumberFormat $pFormat) + public static function isDateTimeFormat(NumberFormat $excelFormatCode) { - return self::isDateTimeFormatCode($pFormat->getFormatCode()); + return self::isDateTimeFormatCode($excelFormatCode->getFormatCode()); } private static $possibleDateFormatCharacters = 'eymdHs'; @@ -350,23 +391,23 @@ public static function isDateTimeFormat(NumberFormat $pFormat) /** * Is a given number format code a date/time? * - * @param string $pFormatCode + * @param string $excelFormatCode * * @return bool */ - public static function isDateTimeFormatCode($pFormatCode) + public static function isDateTimeFormatCode($excelFormatCode) { - if (strtolower($pFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) { + if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) { // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) return false; } - if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) { + if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) { // Scientific format return false; } // Switch on formatcode - switch ($pFormatCode) { + switch ($excelFormatCode) { // Explicitly defined date formats case NumberFormat::FORMAT_DATE_YYYYMMDD: case NumberFormat::FORMAT_DATE_YYYYMMDD2: @@ -394,19 +435,26 @@ public static function isDateTimeFormatCode($pFormatCode) } // Typically number, currency or accounting (or occasionally fraction) formats - if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) { + if ((substr($excelFormatCode, 0, 1) == '_') || (substr($excelFormatCode, 0, 2) == '0 ')) { + return false; + } + // Some "special formats" provided in German Excel versions were detected as date time value, + // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany). + if (\strpos($excelFormatCode, '-00000') !== false) { return false; } // Try checking for any of the date formatting characters that don't appear within square braces - if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) { + if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $excelFormatCode)) { // We might also have a format mask containing quoted strings... // we don't want to test for any of our characters within the quoted blocks - if (strpos($pFormatCode, '"') !== false) { + if (strpos($excelFormatCode, '"') !== false) { $segMatcher = false; - foreach (explode('"', $pFormatCode) as $subVal) { + foreach (explode('"', $excelFormatCode) as $subVal) { // Only test in alternate array entries (the non-quoted blocks) - if (($segMatcher = !$segMatcher) && - (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $subVal))) { + if ( + ($segMatcher = !$segMatcher) && + (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $subVal)) + ) { return true; } } @@ -437,15 +485,15 @@ public static function stringToExcel($dateValue) return false; } - $dateValueNew = DateTime::DATEVALUE($dateValue); + $dateValueNew = DateTimeExcel\DateValue::fromString($dateValue); - if ($dateValueNew === Functions::VALUE()) { + if ($dateValueNew === ExcelError::VALUE()) { return false; } if (strpos($dateValue, ':') !== false) { - $timeValue = DateTime::TIMEVALUE($dateValue); - if ($timeValue === Functions::VALUE()) { + $timeValue = DateTimeExcel\TimeValue::fromString($dateValue); + if ($timeValue === ExcelError::VALUE()) { return false; } $dateValueNew += $timeValue; @@ -457,21 +505,21 @@ public static function stringToExcel($dateValue) /** * Converts a month name (either a long or a short name) to a month number. * - * @param string $month Month name or abbreviation + * @param string $monthName Month name or abbreviation * * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name */ - public static function monthStringToNumber($month) + public static function monthStringToNumber($monthName) { $monthIndex = 1; foreach (self::$monthNames as $shortMonthName => $longMonthName) { - if (($month === $longMonthName) || ($month === $shortMonthName)) { + if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) { return $monthIndex; } ++$monthIndex; } - return $month; + return $monthName; } /** @@ -490,4 +538,19 @@ public static function dayStringToNumber($day) return $day; } + + public static function dateTimeFromTimestamp(string $date, ?DateTimeZone $timeZone = null): DateTime + { + $dtobj = DateTime::createFromFormat('U', $date) ?: new DateTime(); + $dtobj->setTimeZone($timeZone ?? self::getDefaultOrLocalTimezone()); + + return $dtobj; + } + + public static function formattedDateTimeFromTimestamp(string $date, string $format, ?DateTimeZone $timeZone = null): string + { + $dtobj = self::dateTimeFromTimestamp($date, $timeZone); + + return $dtobj->format($format); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php index 25d6910d..3378958c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Drawing.php @@ -2,31 +2,35 @@ namespace PhpOffice\PhpSpreadsheet\Shared; +use GdImage; +use SimpleXMLElement; + class Drawing { /** * Convert pixels to EMU. * - * @param int $pValue Value in pixels + * @param int $pixelValue Value in pixels * * @return int Value in EMU */ - public static function pixelsToEMU($pValue) + public static function pixelsToEMU($pixelValue) { - return round($pValue * 9525); + return $pixelValue * 9525; } /** * Convert EMU to pixels. * - * @param int $pValue Value in EMU + * @param int|SimpleXMLElement $emuValue Value in EMU * * @return int Value in pixels */ - public static function EMUToPixels($pValue) + public static function EMUToPixels($emuValue) { - if ($pValue != 0) { - return round($pValue / 9525); + $emuValue = (int) $emuValue; + if ($emuValue != 0) { + return (int) round($emuValue / 9525); } return 0; @@ -37,50 +41,51 @@ public static function EMUToPixels($pValue) * By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875 * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. * - * @param int $pValue Value in pixels - * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook + * @param int $pixelValue Value in pixels * - * @return int Value in cell dimension + * @return float|int Value in cell dimension */ - public static function pixelsToCellDimension($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) + public static function pixelsToCellDimension($pixelValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont) { // Font name and size - $name = $pDefaultFont->getName(); - $size = $pDefaultFont->getSize(); + $name = $defaultFont->getName(); + $size = $defaultFont->getSize(); if (isset(Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['width'] / Font::$defaultColumnWidths[$name][$size]['px']; - } else { - // We don't have data for this particular font and size, use approximation by - // extrapolating from Calibri 11 - $colWidth = $pValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; + return $pixelValue * Font::$defaultColumnWidths[$name][$size]['width'] + / Font::$defaultColumnWidths[$name][$size]['px']; } - return $colWidth; + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + return $pixelValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] + / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; } /** * Convert column width from (intrinsic) Excel units to pixels. * - * @param float $pValue Value in cell dimension - * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook + * @param float $cellWidth Value in cell dimension + * @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook * * @return int Value in pixels */ - public static function cellDimensionToPixels($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) + public static function cellDimensionToPixels($cellWidth, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont) { // Font name and size - $name = $pDefaultFont->getName(); - $size = $pDefaultFont->getSize(); + $name = $defaultFont->getName(); + $size = $defaultFont->getSize(); if (isset(Font::$defaultColumnWidths[$name][$size])) { // Exact width can be determined - $colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['px'] / Font::$defaultColumnWidths[$name][$size]['width']; + $colWidth = $cellWidth * Font::$defaultColumnWidths[$name][$size]['px'] + / Font::$defaultColumnWidths[$name][$size]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $colWidth = $pValue * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; + $colWidth = $cellWidth * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] + / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; } // Round pixels to closest integer @@ -92,26 +97,26 @@ public static function cellDimensionToPixels($pValue, \PhpOffice\PhpSpreadsheet\ /** * Convert pixels to points. * - * @param int $pValue Value in pixels + * @param int $pixelValue Value in pixels * * @return float Value in points */ - public static function pixelsToPoints($pValue) + public static function pixelsToPoints($pixelValue) { - return $pValue * 0.67777777; + return $pixelValue * 0.75; } /** * Convert points to pixels. * - * @param int $pValue Value in points + * @param int $pointValue Value in points * * @return int Value in pixels */ - public static function pointsToPixels($pValue) + public static function pointsToPixels($pointValue) { - if ($pValue != 0) { - return (int) ceil($pValue * 1.333333333); + if ($pointValue != 0) { + return (int) ceil($pointValue / 0.75); } return 0; @@ -120,26 +125,27 @@ public static function pointsToPixels($pValue) /** * Convert degrees to angle. * - * @param int $pValue Degrees + * @param int $degrees Degrees * * @return int Angle */ - public static function degreesToAngle($pValue) + public static function degreesToAngle($degrees) { - return (int) round($pValue * 60000); + return (int) round($degrees * 60000); } /** * Convert angle to degrees. * - * @param int $pValue Angle + * @param int|SimpleXMLElement $angle Angle * * @return int Degrees */ - public static function angleToDegrees($pValue) + public static function angleToDegrees($angle) { - if ($pValue != 0) { - return round($pValue / 60000); + $angle = (int) $angle; + if ($angle != 0) { + return (int) round($angle / 60000); } return 0; @@ -150,25 +156,31 @@ public static function angleToDegrees($pValue) * * @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 * - * @param string $p_sFile Path to Windows DIB (BMP) image + * @param string $bmpFilename Path to Windows DIB (BMP) image * - * @return resource + * @return GdImage|resource */ - public static function imagecreatefrombmp($p_sFile) + public static function imagecreatefrombmp($bmpFilename) { // Load the image into a string - $file = fopen($p_sFile, 'rb'); + $file = fopen($bmpFilename, 'rb'); + /** @phpstan-ignore-next-line */ $read = fread($file, 10); + // @phpstan-ignore-next-line while (!feof($file) && ($read != '')) { + // @phpstan-ignore-next-line $read .= fread($file, 1024); } + /** @phpstan-ignore-next-line */ $temp = unpack('H*', $read); $hex = $temp[1]; $header = substr($hex, 0, 108); // Process the header // Structure: http://www.fastgraph.com/help/bmp_header_format.html + $width = 0; + $height = 0; if (substr($header, 0, 4) == '424d') { // Cut it in parts of 2 bytes $header_parts = str_split($header, 2); @@ -188,6 +200,8 @@ public static function imagecreatefrombmp($p_sFile) $y = 1; // Create newimage + + /** @phpstan-ignore-next-line */ $image = imagecreatetruecolor($width, $height); // Grab the body from the image @@ -233,7 +247,10 @@ public static function imagecreatefrombmp($p_sFile) $b = hexdec($body[$i_pos] . $body[$i_pos + 1]); // Calculate and draw the pixel + + /** @phpstan-ignore-next-line */ $color = imagecolorallocate($image, $r, $g, $b); + // @phpstan-ignore-next-line imagesetpixel($image, $x, $height - $y, $color); // Raise the horizontal position @@ -244,6 +261,7 @@ public static function imagecreatefrombmp($p_sFile) unset($body); // Return image-object + // @phpstan-ignore-next-line return $image; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer.php index e9d387da..b0d75d78 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer.php @@ -25,7 +25,7 @@ public function getDgId() return $this->dgId; } - public function setDgId($value) + public function setDgId($value): void { $this->dgId = $value; } @@ -35,7 +35,7 @@ public function getLastSpId() return $this->lastSpId; } - public function setLastSpId($value) + public function setLastSpId($value): void { $this->lastSpId = $value; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php index 7e2c3460..6bdc8f7d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer.php @@ -7,7 +7,7 @@ class SpgrContainer /** * Parent Shape Group Container. * - * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer + * @var null|SpgrContainer */ private $parent; @@ -20,20 +20,16 @@ class SpgrContainer /** * Set parent Shape Group Container. - * - * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer $parent */ - public function setParent($parent) + public function setParent(?self $parent): void { $this->parent = $parent; } /** * Get the parent Shape Group Container if any. - * - * @return null|\PhpOffice\PhpSpreadsheet\Shared\Escher\DgContainer\SpgrContainer */ - public function getParent() + public function getParent(): ?self { return $this->parent; } @@ -43,7 +39,7 @@ public function getParent() * * @param mixed $child */ - public function addChild($child) + public function addChild($child): void { $this->children[] = $child; $child->setParent($this); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php index bbf51df1..8a81ff57 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php @@ -95,7 +95,7 @@ class SpContainer * * @param SpgrContainer $parent */ - public function setParent($parent) + public function setParent($parent): void { $this->parent = $parent; } @@ -115,7 +115,7 @@ public function getParent() * * @param bool $value */ - public function setSpgr($value) + public function setSpgr($value): void { $this->spgr = $value; } @@ -135,7 +135,7 @@ public function getSpgr() * * @param int $value */ - public function setSpType($value) + public function setSpType($value): void { $this->spType = $value; } @@ -155,7 +155,7 @@ public function getSpType() * * @param int $value */ - public function setSpFlag($value) + public function setSpFlag($value): void { $this->spFlag = $value; } @@ -175,7 +175,7 @@ public function getSpFlag() * * @param int $value */ - public function setSpId($value) + public function setSpId($value): void { $this->spId = $value; } @@ -196,7 +196,7 @@ public function getSpId() * @param int $property The number specifies the option * @param mixed $value */ - public function setOPT($property, $value) + public function setOPT($property, $value): void { $this->OPT[$property] = $value; } @@ -232,7 +232,7 @@ public function getOPTCollection() * * @param string $value eg: 'A1' */ - public function setStartCoordinates($value) + public function setStartCoordinates($value): void { $this->startCoordinates = $value; } @@ -252,7 +252,7 @@ public function getStartCoordinates() * * @param int $startOffsetX */ - public function setStartOffsetX($startOffsetX) + public function setStartOffsetX($startOffsetX): void { $this->startOffsetX = $startOffsetX; } @@ -272,7 +272,7 @@ public function getStartOffsetX() * * @param int $startOffsetY */ - public function setStartOffsetY($startOffsetY) + public function setStartOffsetY($startOffsetY): void { $this->startOffsetY = $startOffsetY; } @@ -292,7 +292,7 @@ public function getStartOffsetY() * * @param string $value eg: 'A1' */ - public function setEndCoordinates($value) + public function setEndCoordinates($value): void { $this->endCoordinates = $value; } @@ -312,7 +312,7 @@ public function getEndCoordinates() * * @param int $endOffsetX */ - public function setEndOffsetX($endOffsetX) + public function setEndOffsetX($endOffsetX): void { $this->endOffsetX = $endOffsetX; } @@ -332,7 +332,7 @@ public function getEndOffsetX() * * @param int $endOffsetY */ - public function setEndOffsetY($endOffsetY) + public function setEndOffsetY($endOffsetY): void { $this->endOffsetY = $endOffsetY; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php index 96da3213..36806aa6 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer.php @@ -61,7 +61,7 @@ public function getSpIdMax() * * @param int $value */ - public function setSpIdMax($value) + public function setSpIdMax($value): void { $this->spIdMax = $value; } @@ -81,7 +81,7 @@ public function getCDgSaved() * * @param int $value */ - public function setCDgSaved($value) + public function setCDgSaved($value): void { $this->cDgSaved = $value; } @@ -101,7 +101,7 @@ public function getCSpSaved() * * @param int $value */ - public function setCSpSaved($value) + public function setCSpSaved($value): void { $this->cSpSaved = $value; } @@ -121,7 +121,7 @@ public function getBstoreContainer() * * @param DggContainer\BstoreContainer $bstoreContainer */ - public function setBstoreContainer($bstoreContainer) + public function setBstoreContainer($bstoreContainer): void { $this->bstoreContainer = $bstoreContainer; } @@ -132,7 +132,7 @@ public function setBstoreContainer($bstoreContainer) * @param int $property The number specifies the option * @param mixed $value */ - public function setOPT($property, $value) + public function setOPT($property, $value): void { $this->OPT[$property] = $value; } @@ -166,10 +166,10 @@ public function getIDCLs() /** * Set identifier clusters. [ => , ...]. * - * @param array $pValue + * @param array $IDCLs */ - public function setIDCLs($pValue) + public function setIDCLs($IDCLs): void { - $this->IDCLs = $pValue; + $this->IDCLs = $IDCLs; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php index 9d1e68ec..7203b66b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer.php @@ -7,16 +7,14 @@ class BstoreContainer /** * BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture). * - * @var array + * @var BstoreContainer\BSE[] */ private $BSECollection = []; /** * Add a BLIP Store Entry. - * - * @param BstoreContainer\BSE $BSE */ - public function addBSE($BSE) + public function addBSE(BstoreContainer\BSE $BSE): void { $this->BSECollection[] = $BSE; $BSE->setParent($this); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php index f83bdc7e..d24af3f7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; +use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer; + class BSE { const BLIPTYPE_ERROR = 0x00; @@ -18,7 +20,7 @@ class BSE /** * The parent BLIP Store Entry Container. * - * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer + * @var BstoreContainer */ private $parent; @@ -38,10 +40,8 @@ class BSE /** * Set parent BLIP Store Entry Container. - * - * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer $parent */ - public function setParent($parent) + public function setParent(BstoreContainer $parent): void { $this->parent = $parent; } @@ -58,10 +58,8 @@ public function getBlip() /** * Set the BLIP. - * - * @param BSE\Blip $blip */ - public function setBlip($blip) + public function setBlip(BSE\Blip $blip): void { $this->blip = $blip; $blip->setParent($this); @@ -82,7 +80,7 @@ public function getBlipType() * * @param int $blipType */ - public function setBlipType($blipType) + public function setBlipType($blipType): void { $this->blipType = $blipType; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php index 88bc117a..03b261f8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php @@ -2,12 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; +use PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE; + class Blip { /** * The parent BSE. * - * @var \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE + * @var BSE */ private $parent; @@ -33,27 +35,23 @@ public function getData() * * @param string $data */ - public function setData($data) + public function setData($data): void { $this->data = $data; } /** * Set parent BSE. - * - * @param \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE $parent */ - public function setParent($parent) + public function setParent(BSE $parent): void { $this->parent = $parent; } /** * Get parent BSE. - * - * @return \PhpOffice\PhpSpreadsheet\Shared\Escher\DggContainer\BstoreContainer\BSE $parent */ - public function getParent() + public function getParent(): BSE { return $this->parent; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php index 239c8375..f2fe8caa 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php @@ -2,7 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Shared; -use InvalidArgumentException; +use PhpOffice\PhpSpreadsheet\Exception; +use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException; use ZipArchive; class File @@ -16,75 +17,81 @@ class File /** * Set the flag indicating whether the File Upload Temp directory should be used for temporary files. - * - * @param bool $useUploadTempDir Use File Upload Temporary directory (true or false) */ - public static function setUseUploadTempDirectory($useUploadTempDir) + public static function setUseUploadTempDirectory(bool $useUploadTempDir): void { self::$useUploadTempDirectory = (bool) $useUploadTempDir; } /** * Get the flag indicating whether the File Upload Temp directory should be used for temporary files. - * - * @return bool Use File Upload Temporary directory (true or false) */ - public static function getUseUploadTempDirectory() + public static function getUseUploadTempDirectory(): bool { return self::$useUploadTempDirectory; } + // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT + // Section 4.3.7 + // Looks like there might be endian-ness considerations + private const ZIP_FIRST_4 = [ + "\x50\x4b\x03\x04", // what it looks like on my system + "\x04\x03\x4b\x50", // what it says in documentation + ]; + + private static function validateZipFirst4(string $zipFile): bool + { + $contents = @file_get_contents($zipFile, false, null, 0, 4); + + return in_array($contents, self::ZIP_FIRST_4, true); + } + /** * Verify if a file exists. - * - * @param string $pFilename Filename - * - * @return bool */ - public static function fileExists($pFilename) + public static function fileExists(string $filename): bool { // Sick construction, but it seems that // file_exists returns strange values when // doing the original file_exists on ZIP archives... - if (strtolower(substr($pFilename, 0, 3)) == 'zip') { + if (strtolower(substr($filename, 0, 6)) == 'zip://') { // Open ZIP file and verify if the file exists - $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); - $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); + $zipFile = substr($filename, 6, strrpos($filename, '#') - 6); + $archiveFile = substr($filename, strrpos($filename, '#') + 1); - $zip = new ZipArchive(); - if ($zip->open($zipFile) === true) { - $returnValue = ($zip->getFromName($archiveFile) !== false); - $zip->close(); + if (self::validateZipFirst4($zipFile)) { + $zip = new ZipArchive(); + $res = $zip->open($zipFile); + if ($res === true) { + $returnValue = ($zip->getFromName($archiveFile) !== false); + $zip->close(); - return $returnValue; + return $returnValue; + } } return false; } - return file_exists($pFilename); + return file_exists($filename); } /** * Returns canonicalized absolute pathname, also for ZIP archives. - * - * @param string $pFilename - * - * @return string */ - public static function realpath($pFilename) + public static function realpath(string $filename): string { // Returnvalue $returnValue = ''; // Try using realpath() - if (file_exists($pFilename)) { - $returnValue = realpath($pFilename); + if (file_exists($filename)) { + $returnValue = realpath($filename) ?: ''; } // Found something? - if ($returnValue == '' || ($returnValue === null)) { - $pathArray = explode('/', $pFilename); + if ($returnValue === '') { + $pathArray = explode('/', $filename); while (in_array('..', $pathArray) && $pathArray[0] != '..') { $iMax = count($pathArray); for ($i = 0; $i < $iMax; ++$i) { @@ -104,41 +111,75 @@ public static function realpath($pFilename) /** * Get the systems temporary directory. - * - * @return string */ - public static function sysGetTempDir() + public static function sysGetTempDir(): string { + $path = sys_get_temp_dir(); if (self::$useUploadTempDirectory) { // use upload-directory when defined to allow running on environments having very restricted // open_basedir configs if (ini_get('upload_tmp_dir') !== false) { if ($temp = ini_get('upload_tmp_dir')) { if (file_exists($temp)) { - return realpath($temp); + $path = $temp; } } } } - return realpath(sys_get_temp_dir()); + return realpath($path) ?: ''; + } + + public static function temporaryFilename(): string + { + $filename = tempnam(self::sysGetTempDir(), 'phpspreadsheet'); + if ($filename === false) { + throw new Exception('Could not create temporary file'); + } + + return $filename; } /** * Assert that given path is an existing file and is readable, otherwise throw exception. - * - * @param string $filename - * - * @throws InvalidArgumentException */ - public static function assertFile($filename) + public static function assertFile(string $filename, string $zipMember = ''): void { if (!is_file($filename)) { - throw new InvalidArgumentException('File "' . $filename . '" does not exist.'); + throw new ReaderException('File "' . $filename . '" does not exist.'); } if (!is_readable($filename)) { - throw new InvalidArgumentException('Could not open "' . $filename . '" for reading.'); + throw new ReaderException('Could not open "' . $filename . '" for reading.'); + } + + if ($zipMember !== '') { + $zipfile = "zip://$filename#$zipMember"; + if (!self::fileExists($zipfile)) { + throw new ReaderException("Could not find zip member $zipfile"); + } + } + } + + /** + * Same as assertFile, except return true/false and don't throw Exception. + */ + public static function testFileNoThrow(string $filename, ?string $zipMember = null): bool + { + if (!is_file($filename)) { + return false; + } + if (!is_readable($filename)) { + return false; + } + if ($zipMember === null) { + return true; } + // validate zip, but don't check specific member + if ($zipMember === '') { + return self::validateZipFirst4($filename); + } + + return self::fileExists("zip://$filename#$zipMember"); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php index bee13e29..3ee3d5a6 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Font.php @@ -4,6 +4,8 @@ use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Style\Alignment; +use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle; class Font { @@ -44,10 +46,10 @@ class Font const ARIAL_ITALIC = 'ariali.ttf'; const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; - const CALIBRI = 'CALIBRI.TTF'; - const CALIBRI_BOLD = 'CALIBRIB.TTF'; - const CALIBRI_ITALIC = 'CALIBRII.TTF'; - const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; + const CALIBRI = 'calibri.ttf'; + const CALIBRI_BOLD = 'calibrib.ttf'; + const CALIBRI_ITALIC = 'calibrii.ttf'; + const CALIBRI_BOLD_ITALIC = 'calibriz.ttf'; const COMIC_SANS_MS = 'comic.ttf'; const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; @@ -111,7 +113,7 @@ class Font * * @var string */ - private static $trueTypeFontPath = null; + private static $trueTypeFontPath; /** * How wide is a default column for a given default font and size? @@ -163,16 +165,16 @@ class Font /** * Set autoSize method. * - * @param string $pValue see self::AUTOSIZE_METHOD_* + * @param string $method see self::AUTOSIZE_METHOD_* * * @return bool Success or failure */ - public static function setAutoSizeMethod($pValue) + public static function setAutoSizeMethod($method) { - if (!in_array($pValue, self::$autoSizeMethods)) { + if (!in_array($method, self::$autoSizeMethods)) { return false; } - self::$autoSizeMethod = $pValue; + self::$autoSizeMethod = $method; return true; } @@ -196,11 +198,11 @@ public static function getAutoSizeMethod() *
      • ~/.fonts/
      • *
      . * - * @param string $pValue + * @param string $folderPath */ - public static function setTrueTypeFontPath($pValue) + public static function setTrueTypeFontPath($folderPath): void { - self::$trueTypeFontPath = $pValue; + self::$trueTypeFontPath = $folderPath; } /** @@ -216,26 +218,30 @@ public static function getTrueTypeFontPath() /** * Calculate an (approximate) OpenXML column width, based on font size and text contained. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font Font object + * @param FontStyle $font Font object * @param RichText|string $cellText Text to calculate width * @param int $rotation Rotation angle - * @param null|\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Font object - * - * @return int Column width + * @param null|FontStyle $defaultFont Font object + * @param bool $filterAdjustment Add space for Autofilter or Table dropdown */ - public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font $font, $cellText = '', $rotation = 0, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont = null) - { + public static function calculateColumnWidth( + FontStyle $font, + $cellText = '', + $rotation = 0, + ?FontStyle $defaultFont = null, + bool $filterAdjustment = false + ): int { // If it is rich text, use plain text if ($cellText instanceof RichText) { $cellText = $cellText->getPlainText(); } // Special case if there are one or more newline characters ("\n") - if (strpos($cellText, "\n") !== false) { + if (strpos($cellText ?? '', "\n") !== false) { $lineTexts = explode("\n", $cellText); $lineWidths = []; foreach ($lineTexts as $lineText) { - $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); + $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont, $filterAdjustment); } return max($lineWidths); // width of longest line in cell @@ -243,8 +249,15 @@ public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font // Try to get the exact text width in pixels $approximate = self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX; + $columnWidth = 0; if (!$approximate) { - $columnWidthAdjust = ceil(self::getTextWidthPixelsExact('n', $font, 0) * 1.07); + $columnWidthAdjust = ceil( + self::getTextWidthPixelsExact( + str_repeat('n', 1 * ($filterAdjustment ? 3 : 1)), + $font, + 0 + ) * 1.07 + ); try { // Width of text in pixels excl. padding @@ -256,31 +269,27 @@ public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font } if ($approximate) { - $columnWidthAdjust = self::getTextWidthPixelsApprox('n', $font, 0); + $columnWidthAdjust = self::getTextWidthPixelsApprox( + str_repeat('n', 1 * ($filterAdjustment ? 3 : 1)), + $font, + 0 + ); // Width of text in pixels excl. padding, approximation // and addition because Excel adds some padding, just use approx width of 'n' glyph $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust; } // Convert from pixel width to column width - $columnWidth = Drawing::pixelsToCellDimension($columnWidth, $defaultFont); + $columnWidth = Drawing::pixelsToCellDimension((int) $columnWidth, $defaultFont); // Return - return round($columnWidth, 6); + return (int) round($columnWidth, 6); } /** * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. - * - * @param string $text - * @param \PhpOffice\PhpSpreadsheet\Style\Font - * @param int $rotation - * - * @throws PhpSpreadsheetException - * - * @return int */ - public static function getTextWidthPixelsExact($text, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0) + public static function getTextWidthPixelsExact(string $text, FontStyle $font, int $rotation = 0): int { if (!function_exists('imagettfbbox')) { throw new PhpSpreadsheetException('GD library needs to be enabled'); @@ -305,12 +314,11 @@ public static function getTextWidthPixelsExact($text, \PhpOffice\PhpSpreadsheet\ * Get approximate width in pixels for a string of text in a certain font at a certain rotation angle. * * @param string $columnText - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font * @param int $rotation * * @return int Text width in pixels (no padding added) */ - public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0) + public static function getTextWidthPixelsApprox($columnText, FontStyle $font, $rotation = 0) { $fontName = $font->getName(); $fontSize = $font->getSize(); @@ -321,27 +329,31 @@ public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSprea // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font. $columnWidth = (int) (8.26 * StringHelper::countCharacters($columnText)); $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; case 'Arial': // value 8 was set because of experience in different exports at Arial 10 font. $columnWidth = (int) (8 * StringHelper::countCharacters($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; case 'Verdana': // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font. $columnWidth = (int) (8 * StringHelper::countCharacters($columnText)); $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; default: // just assume Calibri $columnWidth = (int) (8.26 * StringHelper::countCharacters($columnText)); $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; } // Calculate approximate rotated column width if ($rotation !== 0) { - if ($rotation == -165) { + if ($rotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { // stacked text $columnWidth = 4; // approximation } else { @@ -394,11 +406,9 @@ public static function centimeterSizeToPixels($sizeInCm) /** * Returns the font path given the font. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font - * * @return string Path to TrueType font file */ - public static function getTrueTypeFontFileFromFont($font) + public static function getTrueTypeFontFileFromFont(FontStyle $font) { if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) { throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); @@ -524,13 +534,13 @@ public static function getTrueTypeFontFileFromFont($font) /** * Returns the associated charset for the font name. * - * @param string $name Font name + * @param string $fontName Font name * * @return int Character set code */ - public static function getCharsetFromFontName($name) + public static function getCharsetFromFontName($fontName) { - switch ($name) { + switch ($fontName) { // Add more cases. Check FONT records in real Excel files. case 'EucrosiaUPC': return self::CHARSET_ANSI_THAI; @@ -549,28 +559,28 @@ public static function getCharsetFromFontName($name) * Get the effective column width for columns without a column dimension or column with width -1 * For example, for Calibri 11 this is 9.140625 (64 px). * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font - * @param bool $pPixels true = return column width in pixels, false = return in OOXML units + * @param FontStyle $font The workbooks default font + * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units * * @return mixed Column width */ - public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font, $pPixels = false) + public static function getDefaultColumnWidthByFont(FontStyle $font, $returnAsPixels = false) { if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) { // Exact width can be determined - $columnWidth = $pPixels ? + $columnWidth = $returnAsPixels ? self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; } else { // We don't have data for this particular font and size, use approximation by // extrapolating from Calibri 11 - $columnWidth = $pPixels ? + $columnWidth = $returnAsPixels ? self::$defaultColumnWidths['Calibri'][11]['px'] : self::$defaultColumnWidths['Calibri'][11]['width']; $columnWidth = $columnWidth * $font->getSize() / 11; // Round pixels to closest integer - if ($pPixels) { + if ($returnAsPixels) { $columnWidth = (int) round($columnWidth); } } @@ -582,11 +592,11 @@ public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Sty * Get the effective row height for rows without a row dimension or rows with height -1 * For example, for Calibri 11 this is 15 points. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font + * @param FontStyle $font The workbooks default font * * @return float Row height in points */ - public static function getDefaultRowHeightByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) + public static function getDefaultRowHeightByFont(FontStyle $font) { switch ($font->getName()) { case 'Arial': diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php new file mode 100644 index 00000000..060f09c8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/IntOrFloat.php @@ -0,0 +1,21 @@ +getRowDimension() == $this->m) { if ($this->isspd) { - $X = $B->getArrayCopy(); + $X = $B->getArray(); $nx = $B->getColumnDimension(); for ($k = 0; $k < $this->m; ++$k) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php index ba59e0e5..66111b6c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/EigenvalueDecomposition.php @@ -18,9 +18,9 @@ * conditioned, or even singular, so the validity of the equation * A = V*D*inverse(V) depends upon V.cond(). * - * @author Paul Meagher + * @author Paul Meagher * - * @version 1.1 + * @version 1.1 */ class EigenvalueDecomposition { @@ -70,16 +70,22 @@ class EigenvalueDecomposition private $cdivi; + /** + * @var array + */ + private $A; + /** * Symmetric Householder reduction to tridiagonal form. */ - private function tred2() + private function tred2(): void { // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. $this->d = $this->V[$this->n - 1]; + $j = 0; // Householder reduction to tridiagonal form. for ($i = $this->n - 1; $i > 0; --$i) { $i_ = $i - 1; @@ -96,7 +102,7 @@ private function tred2() // Generate Householder vector. for ($k = 0; $k < $i; ++$k) { $this->d[$k] /= $scale; - $h += pow($this->d[$k], 2); + $h += $this->d[$k] ** 2; } $f = $this->d[$i_]; $g = sqrt($h); @@ -180,7 +186,7 @@ private function tred2() * Auto. Comp., Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. */ - private function tql2() + private function tql2(): void { for ($i = 1; $i < $this->n; ++$i) { $this->e[$i - 1] = $this->e[$i]; @@ -188,7 +194,7 @@ private function tql2() $this->e[$this->n - 1] = 0.0; $f = 0.0; $tst1 = 0.0; - $eps = pow(2.0, -52.0); + $eps = 2.0 ** (-52.0); for ($l = 0; $l < $this->n; ++$l) { // Find small subdiagonal element @@ -206,7 +212,7 @@ private function tql2() $iter = 0; do { // Could check iteration count here. - $iter += 1; + ++$iter; // Compute implicit shift $g = $this->d[$l]; $p = ($this->d[$l + 1] - $g) / (2.0 * $this->e[$l]); @@ -287,7 +293,7 @@ private function tql2() * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutines in EISPACK. */ - private function orthes() + private function orthes(): void { $low = 0; $high = $this->n - 1; @@ -372,7 +378,7 @@ private function orthes() * @param mixed $yr * @param mixed $yi */ - private function cdiv($xr, $xi, $yr, $yi) + private function cdiv($xr, $xi, $yr, $yi): void { if (abs($yr) > abs($yi)) { $r = $yi / $yr; @@ -395,21 +401,21 @@ private function cdiv($xr, $xi, $yr, $yi) * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. */ - private function hqr2() + private function hqr2(): void { // Initialize $nn = $this->n; $n = $nn - 1; $low = 0; $high = $nn - 1; - $eps = pow(2.0, -52.0); + $eps = 2.0 ** (-52.0); $exshift = 0.0; $p = $q = $r = $s = $z = 0; // Store roots isolated by balanc and compute matrix norm $norm = 0.0; for ($i = 0; $i < $nn; ++$i) { - if (($i < $low) or ($i > $high)) { + if ($i > $high) { $this->d[$i] = $this->H[$i][$i]; $this->e[$i] = 0.0; } @@ -553,8 +559,10 @@ private function hqr2() if ($m == $l) { break; } - if (abs($this->H[$m][$m - 1]) * (abs($q) + abs($r)) < - $eps * (abs($p) * (abs($this->H[$m - 1][$m - 1]) + abs($z) + abs($this->H[$m + 1][$m + 1])))) { + if ( + abs($this->H[$m][$m - 1]) * (abs($q) + abs($r)) < + $eps * (abs($p) * (abs($this->H[$m - 1][$m - 1]) + abs($z) + abs($this->H[$m + 1][$m + 1]))) + ) { break; } --$m; @@ -754,7 +762,7 @@ private function hqr2() // Vectors of isolated roots for ($i = 0; $i < $nn; ++$i) { - if ($i < $low | $i > $high) { + if ($i > $high) { for ($j = $i; $j < $nn; ++$j) { $this->V[$i][$j] = $this->H[$i][$j]; } @@ -779,9 +787,9 @@ private function hqr2() /** * Constructor: Check for symmetry, then construct the eigenvalue decomposition. * - * @param mixed $Arg A Square matrix + * @param Matrix $Arg A Square matrix */ - public function __construct($Arg) + public function __construct(Matrix $Arg) { $this->A = $Arg->getArray(); $this->n = $Arg->getColumnDimension(); @@ -846,6 +854,7 @@ public function getImagEigenvalues() */ public function getD() { + $D = []; for ($i = 0; $i < $this->n; ++$i) { $D[$i] = array_fill(0, $this->n, 0.0); $D[$i][$i] = $this->d[$i]; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php index bb2b4b04..ecfe42ba 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/LUDecomposition.php @@ -135,6 +135,7 @@ public function __construct($A) */ public function getL() { + $L = []; for ($i = 0; $i < $this->m; ++$i) { for ($j = 0; $j < $this->n; ++$j) { if ($i > $j) { @@ -159,6 +160,7 @@ public function getL() */ public function getU() { + $U = []; for ($i = 0; $i < $this->n; ++$i) { for ($j = 0; $j < $this->n; ++$j) { if ($i <= $j) { @@ -219,7 +221,7 @@ public function isNonsingular() /** * Count determinants. * - * @return array d matrix deterninat + * @return float */ public function det() { @@ -240,14 +242,11 @@ public function det() /** * Solve A*X = B. * - * @param mixed $B a Matrix with as many rows as A and any number of columns - * - * @throws CalculationException illegalArgumentException Matrix row dimensions must agree - * @throws CalculationException runtimeException Matrix is singular + * @param Matrix $B a Matrix with as many rows as A and any number of columns * * @return Matrix X so that L*U*X = B(piv,:) */ - public function solve($B) + public function solve(Matrix $B) { if ($B->getRowDimension() == $this->m) { if ($this->isNonsingular()) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php index a67b6c2d..ab78ef18 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/Matrix.php @@ -3,7 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared\JAMA; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException; -use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; /** @@ -147,7 +147,7 @@ public function getColumnDimension() * @param int $i Row position * @param int $j Column position * - * @return mixed Element (int/float/double) + * @return float|int */ public function get($i = null, $j = null) { @@ -159,11 +159,6 @@ public function get($i = null, $j = null) * * Get a submatrix * - * @param int $i0 Initial row index - * @param int $iF Final row index - * @param int $j0 Initial column index - * @param int $jF Final column index - * * @return Matrix Submatrix */ public function getMatrix(...$args) @@ -328,11 +323,9 @@ public function checkMatrixDimensions($B = null) * * @param int $i Row position * @param int $j Column position - * @param mixed $c Int/float/double value - * - * @return mixed Element (int/float/double) + * @param float|int $c value */ - public function set($i = null, $j = null, $c = null) + public function set($i = null, $j = null, $c = null): void { // Optimized set version just has this $this->A[$i][$j] = $c; @@ -461,24 +454,11 @@ public function trace() return $s; } - /** - * uminus. - * - * Unary minus matrix -A - * - * @return Matrix Unary minus matrix - */ - public function uminus() - { - } - /** * plus. * * A + B * - * @param mixed $B Matrix/Array - * * @return Matrix Sum */ public function plus(...$args) @@ -522,8 +502,6 @@ public function plus(...$args) * * A = A + B * - * @param mixed $B Matrix/Array - * * @return $this */ public function plusEquals(...$args) @@ -565,7 +543,7 @@ public function plusEquals(...$args) if ($validValues) { $this->A[$i][$j] += $value; } else { - $this->A[$i][$j] = Functions::NAN(); + $this->A[$i][$j] = ExcelError::NAN(); } } } @@ -581,8 +559,6 @@ public function plusEquals(...$args) * * A - B * - * @param mixed $B Matrix/Array - * * @return Matrix Sum */ public function minus(...$args) @@ -626,8 +602,6 @@ public function minus(...$args) * * A = A - B * - * @param mixed $B Matrix/Array - * * @return $this */ public function minusEquals(...$args) @@ -669,7 +643,7 @@ public function minusEquals(...$args) if ($validValues) { $this->A[$i][$j] -= $value; } else { - $this->A[$i][$j] = Functions::NAN(); + $this->A[$i][$j] = ExcelError::NAN(); } } } @@ -686,8 +660,6 @@ public function minusEquals(...$args) * Element-by-element multiplication * Cij = Aij * Bij * - * @param mixed $B Matrix/Array - * * @return Matrix Matrix Cij */ public function arrayTimes(...$args) @@ -732,8 +704,6 @@ public function arrayTimes(...$args) * Element-by-element multiplication * Aij = Aij * Bij * - * @param mixed $B Matrix/Array - * * @return $this */ public function arrayTimesEquals(...$args) @@ -775,7 +745,7 @@ public function arrayTimesEquals(...$args) if ($validValues) { $this->A[$i][$j] *= $value; } else { - $this->A[$i][$j] = Functions::NAN(); + $this->A[$i][$j] = ExcelError::NAN(); } } } @@ -792,8 +762,6 @@ public function arrayTimesEquals(...$args) * Element-by-element right division * A / B * - * @param Matrix $B Matrix B - * * @return Matrix Division result */ public function arrayRightDivide(...$args) @@ -840,7 +808,7 @@ public function arrayRightDivide(...$args) $M->set($i, $j, $this->A[$i][$j] / $value); } } else { - $M->set($i, $j, Functions::NAN()); + $M->set($i, $j, ExcelError::NAN()); } } } @@ -857,8 +825,6 @@ public function arrayRightDivide(...$args) * Element-by-element right division * Aij = Aij / Bij * - * @param mixed $B Matrix/Array - * * @return Matrix Matrix Aij */ public function arrayRightDivideEquals(...$args) @@ -903,8 +869,6 @@ public function arrayRightDivideEquals(...$args) * Element-by-element Left division * A / B * - * @param Matrix $B Matrix B - * * @return Matrix Division result */ public function arrayLeftDivide(...$args) @@ -949,8 +913,6 @@ public function arrayLeftDivide(...$args) * Element-by-element Left division * Aij = Aij / Bij * - * @param mixed $B Matrix/Array - * * @return Matrix Matrix Aij */ public function arrayLeftDivideEquals(...$args) @@ -994,8 +956,6 @@ public function arrayLeftDivideEquals(...$args) * * Matrix multiplication * - * @param mixed $n Matrix/Array/Scalar - * * @return Matrix Product */ public function times(...$args) @@ -1089,8 +1049,6 @@ public function times(...$args) * * A = A ^ B * - * @param mixed $B Matrix/Array - * * @return $this */ public function power(...$args) @@ -1130,9 +1088,9 @@ public function power(...$args) $validValues &= StringHelper::convertToNumberIfFraction($value); } if ($validValues) { - $this->A[$i][$j] = pow($this->A[$i][$j], $value); + $this->A[$i][$j] = $this->A[$i][$j] ** $value; } else { - $this->A[$i][$j] = Functions::NAN(); + $this->A[$i][$j] = ExcelError::NAN(); } } } @@ -1148,8 +1106,6 @@ public function power(...$args) * * A = A & B * - * @param mixed $B Matrix/Array - * * @return $this */ public function concat(...$args) @@ -1178,6 +1134,7 @@ public function concat(...$args) $this->checkMatrixDimensions($M); for ($i = 0; $i < $this->m; ++$i) { for ($j = 0; $j < $this->n; ++$j) { + // @phpstan-ignore-next-line $this->A[$i][$j] = trim($this->A[$i][$j], '"') . trim($M->get($i, $j), '"'); } } @@ -1195,7 +1152,7 @@ public function concat(...$args) * * @return Matrix ... Solution if A is square, least squares solution otherwise */ - public function solve($B) + public function solve(self $B) { if ($this->m == $this->n) { $LU = new LUDecomposition($this); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php index 3bb8a10e..9b51f413 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/QRDecomposition.php @@ -15,9 +15,9 @@ * of simultaneous linear equations. This will fail if isFullRank() * returns false. * - * @author Paul Meagher + * @author Paul Meagher * - * @version 1.1 + * @version 1.1 */ class QRDecomposition { @@ -54,47 +54,43 @@ class QRDecomposition /** * QR Decomposition computed by Householder reflections. * - * @param matrix $A Rectangular matrix + * @param Matrix $A Rectangular matrix */ - public function __construct($A) + public function __construct(Matrix $A) { - if ($A instanceof Matrix) { - // Initialize. - $this->QR = $A->getArray(); - $this->m = $A->getRowDimension(); - $this->n = $A->getColumnDimension(); - // Main loop. - for ($k = 0; $k < $this->n; ++$k) { - // Compute 2-norm of k-th column without under/overflow. - $nrm = 0.0; + // Initialize. + $this->QR = $A->getArray(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + // Main loop. + for ($k = 0; $k < $this->n; ++$k) { + // Compute 2-norm of k-th column without under/overflow. + $nrm = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $nrm = hypo($nrm, $this->QR[$i][$k]); + } + if ($nrm != 0.0) { + // Form k-th Householder vector. + if ($this->QR[$k][$k] < 0) { + $nrm = -$nrm; + } for ($i = $k; $i < $this->m; ++$i) { - $nrm = hypo($nrm, $this->QR[$i][$k]); + $this->QR[$i][$k] /= $nrm; } - if ($nrm != 0.0) { - // Form k-th Householder vector. - if ($this->QR[$k][$k] < 0) { - $nrm = -$nrm; - } + $this->QR[$k][$k] += 1.0; + // Apply transformation to remaining columns. + for ($j = $k + 1; $j < $this->n; ++$j) { + $s = 0.0; for ($i = $k; $i < $this->m; ++$i) { - $this->QR[$i][$k] /= $nrm; + $s += $this->QR[$i][$k] * $this->QR[$i][$j]; } - $this->QR[$k][$k] += 1.0; - // Apply transformation to remaining columns. - for ($j = $k + 1; $j < $this->n; ++$j) { - $s = 0.0; - for ($i = $k; $i < $this->m; ++$i) { - $s += $this->QR[$i][$k] * $this->QR[$i][$j]; - } - $s = -$s / $this->QR[$k][$k]; - for ($i = $k; $i < $this->m; ++$i) { - $this->QR[$i][$j] += $s * $this->QR[$i][$k]; - } + $s = -$s / $this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$j] += $s * $this->QR[$i][$k]; } } - $this->Rdiag[$k] = -$nrm; } - } else { - throw new CalculationException(Matrix::ARGUMENT_TYPE_EXCEPTION); + $this->Rdiag[$k] = -$nrm; } } @@ -205,13 +201,13 @@ public function getQ() * * @return Matrix matrix that minimizes the two norm of Q*R*X-B */ - public function solve($B) + public function solve(Matrix $B) { if ($B->getRowDimension() == $this->m) { if ($this->isFullRank()) { // Copy right hand side $nx = $B->getColumnDimension(); - $X = $B->getArrayCopy(); + $X = $B->getArray(); // Compute Y = transpose(Q)*B for ($k = 0; $k < $this->n; ++$k) { for ($j = 0; $j < $nx; ++$j) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php index 3ca95619..6c8999d0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/SingularValueDecomposition.php @@ -65,7 +65,7 @@ class SingularValueDecomposition public function __construct($Arg) { // Initialize. - $A = $Arg->getArrayCopy(); + $A = $Arg->getArray(); $this->m = $Arg->getRowDimension(); $this->n = $Arg->getColumnDimension(); $nu = min($this->m, $this->n); @@ -117,7 +117,7 @@ public function __construct($Arg) } } - if ($wantu and ($k < $nct)) { + if ($wantu && ($k < $nct)) { // Place the transformation in U for subsequent back // multiplication. for ($i = $k; $i < $this->m; ++$i) { @@ -143,7 +143,7 @@ public function __construct($Arg) $e[$k + 1] += 1.0; } $e[$k] = -$e[$k]; - if (($k + 1 < $this->m) and ($e[$k] != 0.0)) { + if (($k + 1 < $this->m) && ($e[$k] != 0.0)) { // Apply the transformation. for ($i = $k + 1; $i < $this->m; ++$i) { $work[$i] = 0.0; @@ -221,7 +221,7 @@ public function __construct($Arg) // If required, generate V. if ($wantv) { for ($k = $this->n - 1; $k >= 0; --$k) { - if (($k < $nrt) and ($e[$k] != 0.0)) { + if (($k < $nrt) && ($e[$k] != 0.0)) { for ($j = $k + 1; $j < $nu; ++$j) { $t = 0; for ($i = $k + 1; $i < $this->n; ++$i) { @@ -243,7 +243,7 @@ public function __construct($Arg) // Main iteration loop for the singular values. $pp = $p - 1; $iter = 0; - $eps = pow(2.0, -52.0); + $eps = 2.0 ** (-52.0); while ($p > 0) { // Here is where a test for too many iterations would go. @@ -415,14 +415,14 @@ public function __construct($Arg) $t = $this->s[$k]; $this->s[$k] = $this->s[$k + 1]; $this->s[$k + 1] = $t; - if ($wantv and ($k < $this->n - 1)) { + if ($wantv && ($k < $this->n - 1)) { for ($i = 0; $i < $this->n; ++$i) { $t = $this->V[$i][$k + 1]; $this->V[$i][$k + 1] = $this->V[$i][$k]; $this->V[$i][$k] = $t; } } - if ($wantu and ($k < $this->m - 1)) { + if ($wantu && ($k < $this->m - 1)) { for ($i = 0; $i < $this->m; ++$i) { $t = $this->U[$i][$k + 1]; $this->U[$i][$k + 1] = $this->U[$i][$k]; @@ -476,6 +476,7 @@ public function getSingularValues() */ public function getS() { + $S = []; for ($i = 0; $i < $this->n; ++$i) { for ($j = 0; $j < $this->n; ++$j) { $S[$i][$j] = 0.0; @@ -513,7 +514,7 @@ public function cond() */ public function rank() { - $eps = pow(2.0, -52.0); + $eps = 2.0 ** (-52.0); $tol = max($this->m, $this->n) * $this->s[0] * $eps; $r = 0; $iMax = count($this->s); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/utils/Maths.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/utils/Maths.php index 68c38649..49877b23 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/utils/Maths.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/JAMA/utils/Maths.php @@ -1,4 +1,5 @@ * @author Christian Schmidt - * - * @category PhpSpreadsheet */ class OLE { @@ -111,17 +110,15 @@ class OLE * * @acces public * - * @param string $file - * - * @throws ReaderException + * @param string $filename * * @return bool true on success, PEAR_Error on failure */ - public function read($file) + public function read($filename) { - $fh = fopen($file, 'r'); + $fh = fopen($filename, 'rb'); if (!$fh) { - throw new ReaderException("Can't open file $file"); + throw new ReaderException("Can't open file $filename"); } $this->_file_handle = $fh; @@ -135,55 +132,55 @@ public function read($file) throw new ReaderException('Only Little-Endian encoding is supported.'); } // Size of blocks and short blocks in bytes - $this->bigBlockSize = pow(2, self::_readInt2($fh)); - $this->smallBlockSize = pow(2, self::_readInt2($fh)); + $this->bigBlockSize = 2 ** self::readInt2($fh); + $this->smallBlockSize = 2 ** self::readInt2($fh); // Skip UID, revision number and version number fseek($fh, 44); // Number of blocks in Big Block Allocation Table - $bbatBlockCount = self::_readInt4($fh); + $bbatBlockCount = self::readInt4($fh); // Root chain 1st block - $directoryFirstBlockId = self::_readInt4($fh); + $directoryFirstBlockId = self::readInt4($fh); // Skip unused bytes fseek($fh, 56); // Streams shorter than this are stored using small blocks - $this->bigBlockThreshold = self::_readInt4($fh); + $this->bigBlockThreshold = self::readInt4($fh); // Block id of first sector in Short Block Allocation Table - $sbatFirstBlockId = self::_readInt4($fh); + $sbatFirstBlockId = self::readInt4($fh); // Number of blocks in Short Block Allocation Table - $sbbatBlockCount = self::_readInt4($fh); + $sbbatBlockCount = self::readInt4($fh); // Block id of first sector in Master Block Allocation Table - $mbatFirstBlockId = self::_readInt4($fh); + $mbatFirstBlockId = self::readInt4($fh); // Number of blocks in Master Block Allocation Table - $mbbatBlockCount = self::_readInt4($fh); + $mbbatBlockCount = self::readInt4($fh); $this->bbat = []; // Remaining 4 * 109 bytes of current block is beginning of Master // Block Allocation Table $mbatBlocks = []; for ($i = 0; $i < 109; ++$i) { - $mbatBlocks[] = self::_readInt4($fh); + $mbatBlocks[] = self::readInt4($fh); } // Read rest of Master Block Allocation Table (if any is left) - $pos = $this->_getBlockOffset($mbatFirstBlockId); + $pos = $this->getBlockOffset($mbatFirstBlockId); for ($i = 0; $i < $mbbatBlockCount; ++$i) { fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) { - $mbatBlocks[] = self::_readInt4($fh); + $mbatBlocks[] = self::readInt4($fh); } // Last block id in each block points to next block - $pos = $this->_getBlockOffset(self::_readInt4($fh)); + $pos = $this->getBlockOffset(self::readInt4($fh)); } // Read Big Block Allocation Table according to chain specified by $mbatBlocks for ($i = 0; $i < $bbatBlockCount; ++$i) { - $pos = $this->_getBlockOffset($mbatBlocks[$i]); + $pos = $this->getBlockOffset($mbatBlocks[$i]); fseek($fh, $pos); for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) { - $this->bbat[] = self::_readInt4($fh); + $this->bbat[] = self::readInt4($fh); } } @@ -192,11 +189,11 @@ public function read($file) $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; $sbatFh = $this->getStream($sbatFirstBlockId); for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { - $this->sbat[$blockId] = self::_readInt4($sbatFh); + $this->sbat[$blockId] = self::readInt4($sbatFh); } fclose($sbatFh); - $this->_readPpsWks($directoryFirstBlockId); + $this->readPpsWks($directoryFirstBlockId); return true; } @@ -206,7 +203,7 @@ public function read($file) * * @return int */ - public function _getBlockOffset($blockId) + public function getBlockOffset($blockId) { return 512 + $blockId * $this->bigBlockSize; } @@ -231,7 +228,8 @@ public function getStream($blockIdOrPps) // in OLE_ChainedBlockStream::stream_open(). // Object is removed from self::$instances in OLE_Stream::close(). $GLOBALS['_OLE_INSTANCES'][] = $this; - $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES'])); + $keys = array_keys($GLOBALS['_OLE_INSTANCES']); + $instanceId = end($keys); $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; if ($blockIdOrPps instanceof OLE\PPS) { @@ -241,19 +239,20 @@ public function getStream($blockIdOrPps) $path .= '&blockId=' . $blockIdOrPps; } - return fopen($path, 'r'); + return fopen($path, 'rb'); } /** * Reads a signed char. * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @return int */ - private static function _readInt1($fh) + private static function readInt1($fileHandle) { - [, $tmp] = unpack('c', fread($fh, 1)); + // @phpstan-ignore-next-line + [, $tmp] = unpack('c', fread($fileHandle, 1)); return $tmp; } @@ -261,13 +260,14 @@ private static function _readInt1($fh) /** * Reads an unsigned short (2 octets). * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @return int */ - private static function _readInt2($fh) + private static function readInt2($fileHandle) { - [, $tmp] = unpack('v', fread($fh, 2)); + // @phpstan-ignore-next-line + [, $tmp] = unpack('v', fread($fileHandle, 2)); return $tmp; } @@ -275,13 +275,14 @@ private static function _readInt2($fh) /** * Reads an unsigned long (4 octets). * - * @param resource $fh file handle + * @param resource $fileHandle file handle * * @return int */ - private static function _readInt4($fh) + private static function readInt4($fileHandle) { - [, $tmp] = unpack('V', fread($fh, 4)); + // @phpstan-ignore-next-line + [, $tmp] = unpack('V', fread($fileHandle, 4)); return $tmp; } @@ -294,17 +295,17 @@ private static function _readInt4($fh) * * @return bool true on success, PEAR_Error on failure */ - public function _readPpsWks($blockId) + public function readPpsWks($blockId) { $fh = $this->getStream($blockId); for ($pos = 0; true; $pos += 128) { fseek($fh, $pos, SEEK_SET); $nameUtf16 = fread($fh, 64); - $nameLength = self::_readInt2($fh); + $nameLength = self::readInt2($fh); $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); // Simple conversion from UTF-16LE to ISO-8859-1 $name = str_replace("\x00", '', $nameUtf16); - $type = self::_readInt1($fh); + $type = self::readInt1($fh); switch ($type) { case self::OLE_PPS_TYPE_ROOT: $pps = new OLE\PPS\Root(null, null, []); @@ -320,24 +321,24 @@ public function _readPpsWks($blockId) break; default: - break; + throw new Exception('Unsupported PPS type'); } fseek($fh, 1, SEEK_CUR); $pps->Type = $type; $pps->Name = $name; - $pps->PrevPps = self::_readInt4($fh); - $pps->NextPps = self::_readInt4($fh); - $pps->DirPps = self::_readInt4($fh); + $pps->PrevPps = self::readInt4($fh); + $pps->NextPps = self::readInt4($fh); + $pps->DirPps = self::readInt4($fh); fseek($fh, 20, SEEK_CUR); $pps->Time1st = self::OLE2LocalDate(fread($fh, 8)); $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8)); - $pps->startBlock = self::_readInt4($fh); - $pps->Size = self::_readInt4($fh); + $pps->startBlock = self::readInt4($fh); + $pps->Size = self::readInt4($fh); $pps->No = count($this->_list); $this->_list[] = $pps; // check if the PPS tree (starting from root) is complete - if (isset($this->root) && $this->_ppsTreeComplete($this->root->No)) { + if (isset($this->root) && $this->ppsTreeComplete($this->root->No)) { break; } } @@ -371,16 +372,16 @@ public function _readPpsWks($blockId) * * @return bool Whether the PPS tree for the given PPS is complete */ - public function _ppsTreeComplete($index) + private function ppsTreeComplete($index) { return isset($this->_list[$index]) && ($pps = $this->_list[$index]) && ($pps->PrevPps == -1 || - $this->_ppsTreeComplete($pps->PrevPps)) && + $this->ppsTreeComplete($pps->PrevPps)) && ($pps->NextPps == -1 || - $this->_ppsTreeComplete($pps->NextPps)) && + $this->ppsTreeComplete($pps->NextPps)) && ($pps->DirPps == -1 || - $this->_ppsTreeComplete($pps->DirPps)); + $this->ppsTreeComplete($pps->DirPps)); } /** @@ -493,42 +494,33 @@ public static function ascToUcs($ascii) * Utility function * Returns a string for the OLE container with the date given. * - * @param int $date A timestamp + * @param float|int $date A timestamp * * @return string The string for the OLE container */ public static function localDateToOLE($date) { - if (!isset($date)) { + if (!$date) { return "\x00\x00\x00\x00\x00\x00\x00\x00"; } - - // factor used for separating numbers into 4 bytes parts - $factor = pow(2, 32); + $dateTime = Date::dateTimeFromTimestamp("$date"); // days from 1-1-1601 until the beggining of UNIX era $days = 134774; // calculate seconds - $big_date = $days * 24 * 3600 + gmmktime(date('H', $date), date('i', $date), date('s', $date), date('m', $date), date('d', $date), date('Y', $date)); + $big_date = $days * 24 * 3600 + (float) $dateTime->format('U'); // multiply just to make MS happy $big_date *= 10000000; - $high_part = floor($big_date / $factor); - // lower 4 bytes - $low_part = floor((($big_date / $factor) - $high_part) * $factor); - // Make HEX string $res = ''; - for ($i = 0; $i < 4; ++$i) { - $hex = $low_part % 0x100; - $res .= pack('c', $hex); - $low_part /= 0x100; - } - for ($i = 0; $i < 4; ++$i) { - $hex = $high_part % 0x100; - $res .= pack('c', $hex); - $high_part /= 0x100; + $factor = 2 ** 56; + while ($factor >= 1) { + $hex = (int) floor($big_date / $factor); + $res = pack('c', $hex) . $res; + $big_date = fmod($big_date, $factor); + $factor /= 256; } return $res; @@ -539,9 +531,7 @@ public static function localDateToOLE($date) * * @param string $oleTimestamp A binary string with the encoded date * - * @throws ReaderException - * - * @return int The Unix timestamp corresponding to the string + * @return float|int The Unix timestamp corresponding to the string */ public static function OLE2LocalDate($oleTimestamp) { @@ -564,10 +554,6 @@ public static function OLE2LocalDate($oleTimestamp) // translate to seconds since 1970: $unixTimestamp = floor(65536.0 * 65536.0 * $timestampHigh + $timestampLow - $days * 24 * 3600 + 0.5); - if ((int) $unixTimestamp == $unixTimestamp) { - return (int) $unixTimestamp; - } - - return $unixTimestamp >= 0.0 ? PHP_INT_MAX : PHP_INT_MIN; + return IntOrFloat::evaluate($unixTimestamp); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php index e6ba7242..ac9fcb00 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/ChainedBlockStream.php @@ -9,7 +9,7 @@ class ChainedBlockStream /** * The OLE container of the file that is being read. * - * @var OLE + * @var null|OLE */ public $ole; @@ -42,7 +42,7 @@ class ChainedBlockStream * ole-chainedblockstream://oleInstanceId=1 * @param string $mode only "r" is supported * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH - * @param string &$openedPath absolute path of the opened stream (out parameter) + * @param string $openedPath absolute path of the opened stream (out parameter) * * @return bool true on success */ @@ -71,7 +71,7 @@ public function stream_open($path, $mode, $options, &$openedPath) // @codingStan $this->data = ''; if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->startBlock) { // Block id refers to small blocks - $rootPos = $this->ole->_getBlockOffset($this->ole->root->startBlock); + $rootPos = $this->ole->getBlockOffset($this->ole->root->startBlock); while ($blockId != -2) { $pos = $rootPos + $blockId * $this->ole->bigBlockSize; $blockId = $this->ole->sbat[$blockId]; @@ -81,7 +81,7 @@ public function stream_open($path, $mode, $options, &$openedPath) // @codingStan } else { // Block id refers to big blocks while ($blockId != -2) { - $pos = $this->ole->_getBlockOffset($blockId); + $pos = $this->ole->getBlockOffset($blockId); fseek($this->ole->_file_handle, $pos); $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); $blockId = $this->ole->bbat[$blockId]; @@ -101,7 +101,7 @@ public function stream_open($path, $mode, $options, &$openedPath) // @codingStan /** * Implements support for fclose(). */ - public function stream_close() // @codingStandardsIgnoreLine + public function stream_close(): void // @codingStandardsIgnoreLine { $this->ole = null; unset($GLOBALS['_OLE_INSTANCES']); @@ -112,7 +112,7 @@ public function stream_close() // @codingStandardsIgnoreLine * * @param int $count maximum number of bytes to read * - * @return string + * @return false|string */ public function stream_read($count) // @codingStandardsIgnoreLine { @@ -160,6 +160,7 @@ public function stream_seek($offset, $whence) // @codingStandardsIgnoreLine $this->pos = $offset; } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) { $this->pos += $offset; + // @phpstan-ignore-next-line } elseif ($whence == SEEK_END && -$offset <= count($this->data)) { $this->pos = strlen($this->data) + $offset; } else { @@ -179,7 +180,7 @@ public function stream_stat() // @codingStandardsIgnoreLine { return [ 'size' => strlen($this->data), - ]; + ]; } // Methods used by stream_wrapper_register() that are not implemented: diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php index e53f2575..8b9e92a8 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS.php @@ -26,8 +26,6 @@ * Class for creating PPS's for OLE containers. * * @author Xavier Noguer - * - * @category PhpSpreadsheet */ class PPS { @@ -76,14 +74,14 @@ class PPS /** * A timestamp. * - * @var int + * @var float|int */ public $Time1st; /** * A timestamp. * - * @var int + * @var float|int */ public $Time2nd; @@ -131,8 +129,8 @@ class PPS * @param int $prev The index of the previous PPS * @param int $next The index of the next PPS * @param int $dir The index of it's first child if this is a Dir or Root PPS - * @param int $time_1st A timestamp - * @param int $time_2nd A timestamp + * @param null|float|int $time_1st A timestamp + * @param null|float|int $time_2nd A timestamp * @param string $data The (usually binary) source data of the PPS * @param array $children Array containing children PPS for this PPS */ @@ -144,8 +142,8 @@ public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $t $this->PrevPps = $prev; $this->NextPps = $next; $this->DirPps = $dir; - $this->Time1st = $time_1st; - $this->Time2nd = $time_2nd; + $this->Time1st = $time_1st ?? 0; + $this->Time2nd = $time_2nd ?? 0; $this->_data = $data; $this->children = $children; if ($data != '') { @@ -174,7 +172,7 @@ public function getDataLen() * * @return string The binary string */ - public function _getPpsWk() + public function getPpsWk() { $ret = str_pad($this->Name, 64, "\x00"); @@ -191,9 +189,10 @@ public function _getPpsWk() . "\x00\x00\x00\x00" // 100 . OLE::localDateToOLE($this->Time1st) // 108 . OLE::localDateToOLE($this->Time2nd) // 116 - . pack('V', isset($this->startBlock) ? $this->startBlock : 0) // 120 + . pack('V', $this->startBlock ?? 0) // 120 . pack('V', $this->Size) // 124 . pack('V', 0); // 128 + return $ret; } @@ -201,14 +200,14 @@ public function _getPpsWk() * Updates index and pointers to previous, next and children PPS's for this * PPS. I don't think it'll work with Dir PPS's. * - * @param array &$raList Reference to the array of PPS's for the whole OLE + * @param array $raList Reference to the array of PPS's for the whole OLE * container * @param mixed $to_save * @param mixed $depth * * @return int The index for this PPS */ - public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) + public static function savePpsSetPnt(&$raList, $to_save, $depth = 0) { if (!is_array($to_save) || (empty($to_save))) { return 0xFFFFFFFF; @@ -219,7 +218,7 @@ public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) $raList[$cnt]->No = $cnt; $raList[$cnt]->PrevPps = 0xFFFFFFFF; $raList[$cnt]->NextPps = 0xFFFFFFFF; - $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } else { $iPos = floor(count($to_save) / 2); $aPrev = array_slice($to_save, 0, $iPos); @@ -228,9 +227,9 @@ public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) // If the first entry, it's the root... Don't clone it! $raList[$cnt] = ($depth == 0) ? $to_save[$iPos] : clone $to_save[$iPos]; $raList[$cnt]->No = $cnt; - $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++); - $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++); - $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + $raList[$cnt]->PrevPps = self::savePpsSetPnt($raList, $aPrev, $depth++); + $raList[$cnt]->NextPps = self::savePpsSetPnt($raList, $aNext, $depth++); + $raList[$cnt]->DirPps = self::savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); } return $cnt; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php index 68f50a5c..dd1cda2d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/File.php @@ -27,8 +27,6 @@ * Class for creating File PPS's for OLE containers. * * @author Xavier Noguer - * - * @category PhpSpreadsheet */ class File extends PPS { @@ -59,7 +57,7 @@ public function init() * * @param string $data The data to append */ - public function append($data) + public function append($data): void { $this->_data .= $data; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php index c52cea23..fa92fd5d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLE/PPS/Root.php @@ -22,34 +22,19 @@ // use PhpOffice\PhpSpreadsheet\Shared\OLE; use PhpOffice\PhpSpreadsheet\Shared\OLE\PPS; -use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; /** * Class for creating Root PPS's for OLE containers. * * @author Xavier Noguer - * - * @category PhpSpreadsheet */ class Root extends PPS { - /** - * Directory for temporary files. - * - * @var string - */ - protected $tempDirectory; - /** * @var resource */ private $fileHandle; - /** - * @var string - */ - private $tempFilename; - /** * @var int */ @@ -61,14 +46,12 @@ class Root extends PPS private $bigBlockSize; /** - * @param int $time_1st A timestamp - * @param int $time_2nd A timestamp + * @param null|float|int $time_1st A timestamp + * @param null|float|int $time_2nd A timestamp * @param File[] $raChild */ public function __construct($time_1st, $time_2nd, $raChild) { - $this->tempDirectory = \PhpOffice\PhpSpreadsheet\Shared\File::sysGetTempDir(); - parent::__construct(null, OLE::ascToUcs('Root Entry'), OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild); } @@ -79,62 +62,39 @@ public function __construct($time_1st, $time_2nd, $raChild) * If a resource pointer to a stream created by fopen() is passed * it will be used, but you have to close such stream by yourself. * - * @param resource|string $filename the name of the file or stream where to save the OLE container - * - * @throws WriterException + * @param resource $fileHandle the name of the file or stream where to save the OLE container * * @return bool true on success */ - public function save($filename) + public function save($fileHandle) { + $this->fileHandle = $fileHandle; + // Initial Setting for saving - $this->bigBlockSize = pow( - 2, + $this->bigBlockSize = (int) (2 ** ( (isset($this->bigBlockSize)) ? self::adjust2($this->bigBlockSize) : 9 - ); - $this->smallBlockSize = pow( - 2, + )); + $this->smallBlockSize = (int) (2 ** ( (isset($this->smallBlockSize)) ? self::adjust2($this->smallBlockSize) : 6 - ); + )); - if (is_resource($filename)) { - $this->fileHandle = $filename; - } elseif ($filename == '-' || $filename == '') { - if ($this->tempDirectory === null) { - $this->tempDirectory = \PhpOffice\PhpSpreadsheet\Shared\File::sysGetTempDir(); - } - $this->tempFilename = tempnam($this->tempDirectory, 'OLE_PPS_Root'); - $this->fileHandle = fopen($this->tempFilename, 'w+b'); - if ($this->fileHandle == false) { - throw new WriterException("Can't create temporary file."); - } - } else { - $this->fileHandle = fopen($filename, 'wb'); - } - if ($this->fileHandle == false) { - throw new WriterException("Can't open $filename. It may be in use or protected."); - } // Make an array of PPS's (for Save) $aList = []; - PPS::_savePpsSetPnt($aList, [$this]); + PPS::savePpsSetPnt($aList, [$this]); // calculate values for header - [$iSBDcnt, $iBBcnt, $iPPScnt] = $this->_calcSize($aList); //, $rhInfo); + [$iSBDcnt, $iBBcnt, $iPPScnt] = $this->calcSize($aList); //, $rhInfo); // Save Header - $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt); + $this->saveHeader($iSBDcnt, $iBBcnt, $iPPScnt); // Make Small Data string (write SBD) - $this->_data = $this->_makeSmallData($aList); + $this->_data = $this->makeSmallData($aList); // Write BB - $this->_saveBigData($iSBDcnt, $aList); + $this->saveBigData($iSBDcnt, $aList); // Write PPS - $this->_savePps($aList); + $this->savePps($aList); // Write Big Block Depot and BDList and Adding Header informations - $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt); - - if (!is_resource($filename)) { - fclose($this->fileHandle); - } + $this->saveBbd($iSBDcnt, $iBBcnt, $iPPScnt); return true; } @@ -146,7 +106,7 @@ public function save($filename) * * @return float[] The array of numbers */ - public function _calcSize(&$raList) + private function calcSize(&$raList) { // Calculate Basic Setting [$iSBDcnt, $iBBcnt, $iPPScnt] = [0, 0, 0]; @@ -158,7 +118,7 @@ public function _calcSize(&$raList) $raList[$i]->Size = $raList[$i]->getDataLen(); if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSBcnt += floor($raList[$i]->Size / $this->smallBlockSize) - + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); + + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); } else { $iBBcnt += (floor($raList[$i]->Size / $this->bigBlockSize) + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); @@ -169,7 +129,7 @@ public function _calcSize(&$raList) $iSlCnt = floor($this->bigBlockSize / OLE::OLE_LONG_INT_SIZE); $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt) ? 1 : 0); $iBBcnt += (floor($iSmallLen / $this->bigBlockSize) + - (($iSmallLen % $this->bigBlockSize) ? 1 : 0)); + (($iSmallLen % $this->bigBlockSize) ? 1 : 0)); $iCnt = count($raList); $iBdCnt = $this->bigBlockSize / OLE::OLE_PPS_SIZE; $iPPScnt = (floor($iCnt / $iBdCnt) + (($iCnt % $iBdCnt) ? 1 : 0)); @@ -182,9 +142,9 @@ public function _calcSize(&$raList) * * @param int $i2 The argument * - * @see save() - * * @return float + * + * @see save() */ private static function adjust2($i2) { @@ -200,7 +160,7 @@ private static function adjust2($i2) * @param int $iBBcnt * @param int $iPPScnt */ - public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) + private function saveHeader($iSBDcnt, $iBBcnt, $iPPScnt): void { $FILE = $this->fileHandle; @@ -277,9 +237,9 @@ public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) * Saving big data (PPS's with data bigger than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * * @param int $iStBlk - * @param array &$raList Reference to array of PPS's + * @param array $raList Reference to array of PPS's */ - public function _saveBigData($iStBlk, &$raList) + private function saveBigData($iStBlk, &$raList): void { $FILE = $this->fileHandle; @@ -297,8 +257,8 @@ public function _saveBigData($iStBlk, &$raList) // Set For PPS $raList[$i]->startBlock = $iStBlk; $iStBlk += - (floor($raList[$i]->Size / $this->bigBlockSize) + - (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); + (floor($raList[$i]->Size / $this->bigBlockSize) + + (($raList[$i]->Size % $this->bigBlockSize) ? 1 : 0)); } } } @@ -307,11 +267,11 @@ public function _saveBigData($iStBlk, &$raList) /** * get small data (PPS's with data smaller than \PhpOffice\PhpSpreadsheet\Shared\OLE::OLE_DATA_SIZE_SMALL). * - * @param array &$raList Reference to array of PPS's + * @param array $raList Reference to array of PPS's * * @return string */ - public function _makeSmallData(&$raList) + private function makeSmallData(&$raList) { $sRes = ''; $FILE = $this->fileHandle; @@ -326,7 +286,7 @@ public function _makeSmallData(&$raList) } if ($raList[$i]->Size < OLE::OLE_DATA_SIZE_SMALL) { $iSmbCnt = floor($raList[$i]->Size / $this->smallBlockSize) - + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); + + (($raList[$i]->Size % $this->smallBlockSize) ? 1 : 0); // Add to SBD $jB = $iSmbCnt - 1; for ($j = 0; $j < $jB; ++$j) { @@ -361,12 +321,12 @@ public function _makeSmallData(&$raList) * * @param array $raList Reference to an array with all PPS's */ - public function _savePps(&$raList) + private function savePps(&$raList): void { // Save each PPS WK $iC = count($raList); for ($i = 0; $i < $iC; ++$i) { - fwrite($this->fileHandle, $raList[$i]->_getPpsWk()); + fwrite($this->fileHandle, $raList[$i]->getPpsWk()); } // Adjust for Block $iCnt = count($raList); @@ -383,7 +343,7 @@ public function _savePps(&$raList) * @param int $iBsize * @param int $iPpsCnt */ - public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt) + private function saveBbd($iSbdSize, $iBsize, $iPpsCnt): void { $FILE = $this->fileHandle; // Calculate Basic Setting diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php index 3af39700..91f1d044 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/OLERead.php @@ -92,27 +92,23 @@ class OLERead /** * Read the file. - * - * @param $pFilename string Filename - * - * @throws ReaderException */ - public function read($pFilename) + public function read(string $filename): void { - File::assertFile($pFilename); + File::assertFile($filename); // Get the file identifier // Don't bother reading the whole file until we know it's a valid OLE file - $this->data = file_get_contents($pFilename, false, null, 0, 8); + $this->data = file_get_contents($filename, false, null, 0, 8); // Check OLE identifier $identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1); if ($this->data != $identifierOle) { - throw new ReaderException('The filename ' . $pFilename . ' is not recognised as an OLE file'); + throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file'); } // Get the file data - $this->data = file_get_contents($pFilename); + $this->data = file_get_contents($filename); // Total number of sectors used for the SAT $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); @@ -182,7 +178,7 @@ public function read($pFilename) // read the directory stream $block = $this->rootStartBlock; - $this->entry = $this->_readData($block); + $this->entry = $this->readData($block); $this->readPropertySets(); } @@ -192,7 +188,7 @@ public function read($pFilename) * * @param int $stream * - * @return string + * @return null|string */ public function getStream($stream) { @@ -203,7 +199,7 @@ public function getStream($stream) $streamData = ''; if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) { - $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']); + $rootdata = $this->readData($this->props[$this->rootentry]['startBlock']); $block = $this->props[$stream]['startBlock']; @@ -239,13 +235,12 @@ public function getStream($stream) /** * Read a standard stream (by joining sectors using information from SAT). * - * @param int $bl Sector ID where the stream starts + * @param int $block Sector ID where the stream starts * * @return string Data for standard stream */ - private function _readData($bl) + private function readData($block) { - $block = $bl; $data = ''; while ($block != -2) { @@ -260,7 +255,7 @@ private function _readData($bl) /** * Read entries in the directory stream. */ - private function readPropertySets() + private function readPropertySets(): void { $offset = 0; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php index 9b0080b9..0d58a868 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/PasswordHasher.php @@ -2,36 +2,108 @@ namespace PhpOffice\PhpSpreadsheet\Shared; +use PhpOffice\PhpSpreadsheet\Exception as SpException; +use PhpOffice\PhpSpreadsheet\Worksheet\Protection; + class PasswordHasher { + const MAX_PASSWORD_LENGTH = 255; + + /** + * Get algorithm name for PHP. + */ + private static function getAlgorithm(string $algorithmName): string + { + if (!$algorithmName) { + return ''; + } + + // Mapping between algorithm name in Excel and algorithm name in PHP + $mapping = [ + Protection::ALGORITHM_MD2 => 'md2', + Protection::ALGORITHM_MD4 => 'md4', + Protection::ALGORITHM_MD5 => 'md5', + Protection::ALGORITHM_SHA_1 => 'sha1', + Protection::ALGORITHM_SHA_256 => 'sha256', + Protection::ALGORITHM_SHA_384 => 'sha384', + Protection::ALGORITHM_SHA_512 => 'sha512', + Protection::ALGORITHM_RIPEMD_128 => 'ripemd128', + Protection::ALGORITHM_RIPEMD_160 => 'ripemd160', + Protection::ALGORITHM_WHIRLPOOL => 'whirlpool', + ]; + + if (array_key_exists($algorithmName, $mapping)) { + return $mapping[$algorithmName]; + } + + throw new SpException('Unsupported password algorithm: ' . $algorithmName); + } + /** * Create a password hash from a given string. * - * This method is based on the algorithm provided by + * This method is based on the spec at: + * https://interoperability.blob.core.windows.net/files/MS-OFFCRYPTO/[MS-OFFCRYPTO].pdf + * 2.3.7.1 Binary Document Password Verifier Derivation Method 1 + * + * It replaces a method based on the algorithm provided by * Daniel Rentz of OpenOffice and the PEAR package * Spreadsheet_Excel_Writer by Xavier Noguer . * - * @param string $pPassword Password to hash + * Scrutinizer will squawk at the use of bitwise operations here, + * but it should ultimately pass. + * + * @param string $password Password to hash + */ + private static function defaultHashPassword(string $password): string + { + $verifier = 0; + $pwlen = strlen($password); + $passwordArray = pack('c', $pwlen) . $password; + for ($i = $pwlen; $i >= 0; --$i) { + $intermediate1 = (($verifier & 0x4000) === 0) ? 0 : 1; + $intermediate2 = 2 * $verifier; + $intermediate2 = $intermediate2 & 0x7fff; + $intermediate3 = $intermediate1 | $intermediate2; + $verifier = $intermediate3 ^ ord($passwordArray[$i]); + } + $verifier ^= 0xCE4B; + + return strtoupper(dechex($verifier)); + } + + /** + * Create a password hash from a given string by a specific algorithm. + * + * 2.4.2.4 ISO Write Protection Method + * + * @see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/1357ea58-646e-4483-92ef-95d718079d6f + * + * @param string $password Password to hash + * @param string $algorithm Hash algorithm used to compute the password hash value + * @param string $salt Pseudorandom string + * @param int $spinCount Number of times to iterate on a hash of a password * * @return string Hashed password */ - public static function hashPassword($pPassword) + public static function hashPassword(string $password, string $algorithm = '', string $salt = '', int $spinCount = 10000): string { - $password = 0x0000; - $charPos = 1; // char position - - // split the plain text password in its component characters - $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY); - foreach ($chars as $char) { - $value = ord($char) << $charPos++; // shifted ASCII value - $rotated_bits = $value >> 15; // rotated bits beyond bit 15 - $value &= 0x7fff; // first 15 bits - $password ^= ($value | $rotated_bits); + if (strlen($password) > self::MAX_PASSWORD_LENGTH) { + throw new SpException('Password exceeds ' . self::MAX_PASSWORD_LENGTH . ' characters'); } + $phpAlgorithm = self::getAlgorithm($algorithm); + if (!$phpAlgorithm) { + return self::defaultHashPassword($password); + } + + $saltValue = base64_decode($salt); + $encodedPassword = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8'); - $password ^= strlen($pPassword); - $password ^= 0xCE4B; + $hashValue = hash($phpAlgorithm, $saltValue . $encodedPassword, true); + for ($i = 0; $i < $spinCount; ++$i) { + $hashValue = hash($phpAlgorithm, $hashValue . pack('L', $i), true); + } - return strtoupper(dechex($password)); + return base64_encode($hashValue); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php index d949203b..9970a211 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/StringHelper.php @@ -49,7 +49,7 @@ class StringHelper /** * Is iconv extension avalable? * - * @var bool + * @var ?bool */ private static $isIconvEnabled; @@ -63,7 +63,7 @@ class StringHelper /** * Build control characters array. */ - private static function buildControlCharacters() + private static function buildControlCharacters(): void { for ($i = 0; $i <= 31; ++$i) { if ($i != 9 && $i != 10 && $i != 13) { @@ -77,7 +77,7 @@ private static function buildControlCharacters() /** * Build SYLK characters array. */ - private static function buildSYLKCharacters() + private static function buildSYLKCharacters(): void { self::$SYLKCharacters = [ "\x1B 0" => chr(0), @@ -272,7 +272,7 @@ public static function getIsIconvEnabled() return self::$isIconvEnabled; } - private static function buildCharacterSets() + private static function buildCharacterSets(): void { if (empty(self::$controlCharacters)) { self::buildControlCharacters(); @@ -294,15 +294,15 @@ private static function buildCharacterSets() * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * - * @param string $value Value to unescape + * @param string $textValue Value to unescape * * @return string */ - public static function controlCharacterOOXML2PHP($value) + public static function controlCharacterOOXML2PHP($textValue) { self::buildCharacterSets(); - return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value); + return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue); } /** @@ -316,64 +316,64 @@ public static function controlCharacterOOXML2PHP($value) * So you could end up with something like _x0008_ in a string (either in a cell value () * element or in the shared string element. * - * @param string $value Value to escape + * @param string $textValue Value to escape * * @return string */ - public static function controlCharacterPHP2OOXML($value) + public static function controlCharacterPHP2OOXML($textValue) { self::buildCharacterSets(); - return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value); + return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue); } /** * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters. * - * @param string $value + * @param string $textValue * * @return string */ - public static function sanitizeUTF8($value) + public static function sanitizeUTF8($textValue) { if (self::getIsIconvEnabled()) { - $value = @iconv('UTF-8', 'UTF-8', $value); + $textValue = @iconv('UTF-8', 'UTF-8', $textValue); - return $value; + return $textValue; } - $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); + $textValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8'); - return $value; + return $textValue; } /** * Check if a string contains UTF8 data. * - * @param string $value + * @param string $textValue * * @return bool */ - public static function isUTF8($value) + public static function isUTF8($textValue) { - return $value === '' || preg_match('/^./su', $value) === 1; + return $textValue === '' || preg_match('/^./su', $textValue) === 1; } /** * Formats a numeric value as a string for output in various output writers forcing * point as decimal separator in case locale is other than English. * - * @param mixed $value + * @param mixed $numericValue * * @return string */ - public static function formatNumber($value) + public static function formatNumber($numericValue) { - if (is_float($value)) { - return str_replace(',', '.', $value); + if (is_float($numericValue)) { + return str_replace(',', '.', $numericValue); } - return (string) $value; + return (string) $numericValue; } /** @@ -383,25 +383,25 @@ public static function formatNumber($value) * although this will give wrong results for non-ASCII strings * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * - * @param string $value UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * @param mixed[] $arrcRuns Details of rich text runs in $value * * @return string */ - public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) + public static function UTF8toBIFF8UnicodeShort($textValue, $arrcRuns = []) { // character count - $ln = self::countCharacters($value, 'UTF-8'); + $ln = self::countCharacters($textValue, 'UTF-8'); // option flags if (empty($arrcRuns)) { $data = pack('CC', $ln, 0x0001); // characters - $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); } else { $data = pack('vC', $ln, 0x09); $data .= pack('v', count($arrcRuns)); // characters - $data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); foreach ($arrcRuns as $cRun) { $data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['fontidx']); @@ -418,17 +418,17 @@ public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) * although this will give wrong results for non-ASCII strings * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * - * @param string $value UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function UTF8toBIFF8UnicodeLong($value) + public static function UTF8toBIFF8UnicodeLong($textValue) { // character count - $ln = self::countCharacters($value, 'UTF-8'); + $ln = self::countCharacters($textValue, 'UTF-8'); // characters - $chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); + $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8'); return pack('vC', $ln, 0x0001) . $chars; } @@ -436,91 +436,91 @@ public static function UTF8toBIFF8UnicodeLong($value) /** * Convert string from one encoding to another. * - * @param string $value + * @param string $textValue * @param string $to Encoding to convert to, e.g. 'UTF-8' * @param string $from Encoding to convert from, e.g. 'UTF-16LE' * * @return string */ - public static function convertEncoding($value, $to, $from) + public static function convertEncoding($textValue, $to, $from) { if (self::getIsIconvEnabled()) { - $result = iconv($from, $to . self::$iconvOptions, $value); + $result = iconv($from, $to . self::$iconvOptions, $textValue); if (false !== $result) { return $result; } } - return mb_convert_encoding($value, $to, $from); + return mb_convert_encoding($textValue, $to, $from); } /** * Get character count. * - * @param string $value - * @param string $enc Encoding + * @param string $textValue + * @param string $encoding Encoding * * @return int Character count */ - public static function countCharacters($value, $enc = 'UTF-8') + public static function countCharacters($textValue, $encoding = 'UTF-8') { - return mb_strlen($value, $enc); + return mb_strlen($textValue ?? '', $encoding); } /** * Get a substring of a UTF-8 encoded string. * - * @param string $pValue UTF-8 encoded string - * @param int $pStart Start offset - * @param int $pLength Maximum number of characters in substring + * @param string $textValue UTF-8 encoded string + * @param int $offset Start offset + * @param int $length Maximum number of characters in substring * * @return string */ - public static function substring($pValue, $pStart, $pLength = 0) + public static function substring($textValue, $offset, $length = 0) { - return mb_substr($pValue, $pStart, $pLength, 'UTF-8'); + return mb_substr($textValue, $offset, $length, 'UTF-8'); } /** * Convert a UTF-8 encoded string to upper case. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function strToUpper($pValue) + public static function strToUpper($textValue) { - return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8'); + return mb_convert_case($textValue ?? '', MB_CASE_UPPER, 'UTF-8'); } /** * Convert a UTF-8 encoded string to lower case. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function strToLower($pValue) + public static function strToLower($textValue) { - return mb_convert_case($pValue, MB_CASE_LOWER, 'UTF-8'); + return mb_convert_case($textValue ?? '', MB_CASE_LOWER, 'UTF-8'); } /** * Convert a UTF-8 encoded string to title/proper case * (uppercase every first character in each word, lower case all other characters). * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function strToTitle($pValue) + public static function strToTitle($textValue) { - return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8'); + return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8'); } - public static function mbIsUpper($char) + public static function mbIsUpper($character) { - return mb_strtolower($char, 'UTF-8') != $char; + return mb_strtolower($character, 'UTF-8') != $character; } public static function mbStrSplit($string) @@ -534,13 +534,13 @@ public static function mbStrSplit($string) * Reverse the case of a string, so that all uppercase characters become lowercase * and all lowercase characters become uppercase. * - * @param string $pValue UTF-8 encoded string + * @param string $textValue UTF-8 encoded string * * @return string */ - public static function strCaseReverse($pValue) + public static function strCaseReverse($textValue) { - $characters = self::mbStrSplit($pValue); + $characters = self::mbStrSplit($textValue); foreach ($characters as &$character) { if (self::mbIsUpper($character)) { $character = mb_strtolower($character, 'UTF-8'); @@ -556,7 +556,7 @@ public static function strCaseReverse($pValue) * Identify whether a string contains a fractional numeric value, * and convert it to a numeric if it is. * - * @param string &$operand string value to test + * @param string $operand string value to test * * @return bool */ @@ -601,11 +601,11 @@ public static function getDecimalSeparator() * Set the decimal separator. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * - * @param string $pValue Character for decimal separator + * @param string $separator Character for decimal separator */ - public static function setDecimalSeparator($pValue) + public static function setDecimalSeparator($separator): void { - self::$decimalSeparator = $pValue; + self::$decimalSeparator = $separator; } /** @@ -634,11 +634,11 @@ public static function getThousandsSeparator() * Set the thousands separator. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * - * @param string $pValue Character for thousands separator + * @param string $separator Character for thousands separator */ - public static function setThousandsSeparator($pValue) + public static function setThousandsSeparator($separator): void { - self::$thousandsSeparator = $pValue; + self::$thousandsSeparator = $separator; } /** @@ -672,51 +672,51 @@ public static function getCurrencyCode() * Set the currency code. Only used by NumberFormat::toFormattedString() * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * - * @param string $pValue Character for currency code + * @param string $currencyCode Character for currency code */ - public static function setCurrencyCode($pValue) + public static function setCurrencyCode($currencyCode): void { - self::$currencyCode = $pValue; + self::$currencyCode = $currencyCode; } /** * Convert SYLK encoded string to UTF-8. * - * @param string $pValue + * @param string $textValue * * @return string UTF-8 encoded string */ - public static function SYLKtoUTF8($pValue) + public static function SYLKtoUTF8($textValue) { self::buildCharacterSets(); // If there is no escape character in the string there is nothing to do - if (strpos($pValue, '') === false) { - return $pValue; + if (strpos($textValue, '') === false) { + return $textValue; } foreach (self::$SYLKCharacters as $k => $v) { - $pValue = str_replace($k, $v, $pValue); + $textValue = str_replace($k, $v, $textValue); } - return $pValue; + return $textValue; } /** * Retrieve any leading numeric part of a string, or return the full string if no leading numeric * (handles basic integer or float, but not exponent or non decimal). * - * @param string $value + * @param string $textValue * * @return mixed string or only the leading numeric part of the string */ - public static function testStringAsNumeric($value) + public static function testStringAsNumeric($textValue) { - if (is_numeric($value)) { - return $value; + if (is_numeric($textValue)) { + return $textValue; } - $v = (float) $value; + $v = (float) $textValue; - return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value; + return (is_numeric(substr($textValue, 0, strlen($v)))) ? $v : $textValue; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php index e5a99b9b..dabb88f2 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/TimeZone.php @@ -17,26 +17,26 @@ class TimeZone /** * Validate a Timezone name. * - * @param string $timezone Time zone (e.g. 'Europe/London') + * @param string $timezoneName Time zone (e.g. 'Europe/London') * * @return bool Success or failure */ - private static function validateTimeZone($timezone) + private static function validateTimeZone($timezoneName) { - return in_array($timezone, DateTimeZone::listIdentifiers()); + return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC)); } /** * Set the Default Timezone used for date/time conversions. * - * @param string $timezone Time zone (e.g. 'Europe/London') + * @param string $timezoneName Time zone (e.g. 'Europe/London') * * @return bool Success or failure */ - public static function setTimeZone($timezone) + public static function setTimeZone($timezoneName) { - if (self::validateTimezone($timezone)) { - self::$timezone = $timezone; + if (self::validateTimezone($timezoneName)) { + self::$timezone = $timezoneName; return true; } @@ -58,30 +58,20 @@ public static function getTimeZone() * Return the Timezone offset used for date/time conversions to/from UST * This requires both the timezone and the calculated date/time to allow for local DST. * - * @param string $timezone The timezone for finding the adjustment to UST - * @param int $timestamp PHP date/time value - * - * @throws PhpSpreadsheetException + * @param ?string $timezoneName The timezone for finding the adjustment to UST + * @param float|int $timestamp PHP date/time value * * @return int Number of seconds for timezone adjustment */ - public static function getTimeZoneAdjustment($timezone, $timestamp) + public static function getTimeZoneAdjustment($timezoneName, $timestamp) { - if ($timezone !== null) { - if (!self::validateTimezone($timezone)) { - throw new PhpSpreadsheetException('Invalid timezone ' . $timezone); - } - } else { - $timezone = self::$timezone; - } - - if ($timezone == 'UST') { - return 0; + $timezoneName = $timezoneName ?? self::$timezone; + $dtobj = Date::dateTimeFromTimestamp("$timestamp"); + if (!self::validateTimezone($timezoneName)) { + throw new PhpSpreadsheetException("Invalid timezone $timezoneName"); } + $dtobj->setTimeZone(new DateTimeZone($timezoneName)); - $objTimezone = new DateTimeZone($timezone); - $transitions = $objTimezone->getTransitions($timestamp, $timestamp); - - return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; + return $dtobj->getOffset(); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php index d8e63d5e..7df48953 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/BestFit.php @@ -2,7 +2,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared\Trend; -class BestFit +abstract class BestFit { /** * Indicator flag for a calculation error. @@ -96,24 +96,18 @@ public function getBestFitType() * * @param float $xValue X-Value * - * @return bool Y-Value + * @return float Y-Value */ - public function getValueOfYForX($xValue) - { - return false; - } + abstract public function getValueOfYForX($xValue); /** * Return the X-Value for a specified value of Y. * * @param float $yValue Y-Value * - * @return bool X-Value + * @return float X-Value */ - public function getValueOfXForY($yValue) - { - return false; - } + abstract public function getValueOfXForY($yValue); /** * Return the original set of X-Values. @@ -130,12 +124,9 @@ public function getXValues() * * @param int $dp Number of places of decimal precision to display * - * @return bool + * @return string */ - public function getEquation($dp = 0) - { - return false; - } + abstract public function getEquation($dp = 0); /** * Return the Slope of the line. @@ -341,20 +332,20 @@ public function getYBestFitValues() return $this->yBestFitValues; } - protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, $meanX, $meanY, $const) + protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, $meanX, $meanY, $const): void { $SSres = $SScov = $SScor = $SStot = $SSsex = 0.0; foreach ($this->xValues as $xKey => $xValue) { $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY); - if ($const) { + if ($const === true) { $SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY); } else { $SStot += $this->yValues[$xKey] * $this->yValues[$xKey]; } $SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY); - if ($const) { + if ($const === true) { $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX); } else { $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey]; @@ -362,7 +353,7 @@ protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, } $this->SSResiduals = $SSres; - $this->DFResiduals = $this->valueCount - 1 - $const; + $this->DFResiduals = $this->valueCount - 1 - ($const === true ? 1 : 0); if ($this->DFResiduals == 0.0) { $this->stdevOfResiduals = 0.0; @@ -377,7 +368,7 @@ protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, $this->SSRegression = $this->goodnessOfFit * $SStot; $this->covariance = $SScov / $this->valueCount; - $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - pow($sumX, 2)) * ($this->valueCount * $sumY2 - pow($sumY, 2))); + $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - $sumX ** 2) * ($this->valueCount * $sumY2 - $sumY ** 2)); $this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex); $this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2)); if ($this->SSResiduals != 0.0) { @@ -395,27 +386,39 @@ protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, } } + private function sumSquares(array $values) + { + return array_sum( + array_map( + function ($value) { + return $value ** 2; + }, + $values + ) + ); + } + /** * @param float[] $yValues * @param float[] $xValues - * @param bool $const */ - protected function leastSquareFit(array $yValues, array $xValues, $const) + protected function leastSquareFit(array $yValues, array $xValues, bool $const): void { // calculate sums - $x_sum = array_sum($xValues); - $y_sum = array_sum($yValues); - $meanX = $x_sum / $this->valueCount; - $meanY = $y_sum / $this->valueCount; - $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0; + $sumValuesX = array_sum($xValues); + $sumValuesY = array_sum($yValues); + $meanValueX = $sumValuesX / $this->valueCount; + $meanValueY = $sumValuesY / $this->valueCount; + $sumSquaresX = $this->sumSquares($xValues); + $sumSquaresY = $this->sumSquares($yValues); + $mBase = $mDivisor = 0.0; + $xy_sum = 0.0; for ($i = 0; $i < $this->valueCount; ++$i) { $xy_sum += $xValues[$i] * $yValues[$i]; - $xx_sum += $xValues[$i] * $xValues[$i]; - $yy_sum += $yValues[$i] * $yValues[$i]; - if ($const) { - $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY); - $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX); + if ($const === true) { + $mBase += ($xValues[$i] - $meanValueX) * ($yValues[$i] - $meanValueY); + $mDivisor += ($xValues[$i] - $meanValueX) * ($xValues[$i] - $meanValueX); } else { $mBase += $xValues[$i] * $yValues[$i]; $mDivisor += $xValues[$i] * $xValues[$i]; @@ -426,13 +429,9 @@ protected function leastSquareFit(array $yValues, array $xValues, $const) $this->slope = $mBase / $mDivisor; // calculate intersect - if ($const) { - $this->intersect = $meanY - ($this->slope * $meanX); - } else { - $this->intersect = 0; - } + $this->intersect = ($const === true) ? $meanValueY - ($this->slope * $meanValueX) : 0.0; - $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, $meanX, $meanY, $const); + $this->calculateGoodnessOfFit($sumValuesX, $sumValuesY, $sumSquaresX, $sumSquaresY, $xy_sum, $meanValueX, $meanValueY, $const); } /** @@ -440,23 +439,22 @@ protected function leastSquareFit(array $yValues, array $xValues, $const) * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - public function __construct($yValues, $xValues = [], $const = true) + public function __construct($yValues, $xValues = []) { // Calculate number of points - $nY = count($yValues); - $nX = count($xValues); + $yValueCount = count($yValues); + $xValueCount = count($xValues); // Define X Values if necessary - if ($nX == 0) { - $xValues = range(1, $nY); - } elseif ($nY != $nX) { + if ($xValueCount === 0) { + $xValues = range(1, $yValueCount); + } elseif ($yValueCount !== $xValueCount) { // Ensure both arrays of points are the same size $this->error = true; } - $this->valueCount = $nY; + $this->valueCount = $yValueCount; $this->xValues = $xValues; $this->yValues = $yValues; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php index 5b57f4b7..eb8cd746 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/ExponentialBestFit.php @@ -21,7 +21,7 @@ class ExponentialBestFit extends BestFit */ public function getValueOfYForX($xValue) { - return $this->getIntersect() * pow($this->getSlope(), ($xValue - $this->xOffset)); + return $this->getIntersect() * $this->getSlope() ** ($xValue - $this->xOffset); } /** @@ -88,20 +88,17 @@ public function getIntersect($dp = 0) * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function exponentialRegression($yValues, $xValues, $const) + private function exponentialRegression(array $yValues, array $xValues, bool $const): void { - foreach ($yValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** @@ -116,7 +113,7 @@ public function __construct($yValues, $xValues = [], $const = true) parent::__construct($yValues, $xValues); if (!$this->error) { - $this->exponentialRegression($yValues, $xValues, $const); + $this->exponentialRegression($yValues, $xValues, (bool) $const); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php index 217f0964..65d6b4ff 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LinearBestFit.php @@ -56,9 +56,8 @@ public function getEquation($dp = 0) * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function linearRegression($yValues, $xValues, $const) + private function linearRegression(array $yValues, array $xValues, bool $const): void { $this->leastSquareFit($yValues, $xValues, $const); } @@ -75,7 +74,7 @@ public function __construct($yValues, $xValues = [], $const = true) parent::__construct($yValues, $xValues); if (!$this->error) { - $this->linearRegression($yValues, $xValues, $const); + $this->linearRegression($yValues, $xValues, (bool) $const); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php index 96ca2ed8..2366dc63 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/LogarithmicBestFit.php @@ -48,7 +48,7 @@ public function getEquation($dp = 0) $slope = $this->getSlope($dp); $intersect = $this->getIntersect($dp); - return 'Y = ' . $intersect . ' + ' . $slope . ' * log(X)'; + return 'Y = ' . $slope . ' * log(' . $intersect . ' * X)'; } /** @@ -56,20 +56,17 @@ public function getEquation($dp = 0) * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function logarithmicRegression($yValues, $xValues, $const) + private function logarithmicRegression(array $yValues, array $xValues, bool $const): void { - foreach ($xValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $xValues, $const); } /** @@ -84,7 +81,7 @@ public function __construct($yValues, $xValues = [], $const = true) parent::__construct($yValues, $xValues); if (!$this->error) { - $this->logarithmicRegression($yValues, $xValues, $const); + $this->logarithmicRegression($yValues, $xValues, (bool) $const); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php index a1510491..b10a0a10 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PolynomialBestFit.php @@ -42,9 +42,10 @@ public function getValueOfYForX($xValue) { $retVal = $this->getIntersect(); $slope = $this->getSlope(); + // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { - $retVal += $value * pow($xValue, $key + 1); + $retVal += $value * $xValue ** ($key + 1); } } @@ -76,6 +77,7 @@ public function getEquation($dp = 0) $intersect = $this->getIntersect($dp); $equation = 'Y = ' . $intersect; + // @phpstan-ignore-next-line foreach ($slope as $key => $value) { if ($value != 0.0) { $equation .= ' + ' . $value . ' * X'; @@ -93,7 +95,7 @@ public function getEquation($dp = 0) * * @param int $dp Number of places of decimal precision to display * - * @return string + * @return float */ public function getSlope($dp = 0) { @@ -103,6 +105,7 @@ public function getSlope($dp = 0) $coefficients[] = round($coefficient, $dp); } + // @phpstan-ignore-next-line return $coefficients; } @@ -111,6 +114,7 @@ public function getSlope($dp = 0) public function getCoefficients($dp = 0) { + // @phpstan-ignore-next-line return array_merge([$this->getIntersect($dp)], $this->getSlope($dp)); } @@ -121,7 +125,7 @@ public function getCoefficients($dp = 0) * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression */ - private function polynomialRegression($order, $yValues, $xValues) + private function polynomialRegression($order, $yValues, $xValues): void { // calculate sums $x_sum = array_sum($xValues); @@ -144,7 +148,7 @@ private function polynomialRegression($order, $yValues, $xValues) $B = []; for ($i = 0; $i < $this->valueCount; ++$i) { for ($j = 0; $j <= $order; ++$j) { - $A[$i][$j] = pow($xValues[$i], $j); + $A[$i][$j] = $xValues[$i] ** $j; } } for ($i = 0; $i < $this->valueCount; ++$i) { @@ -157,7 +161,7 @@ private function polynomialRegression($order, $yValues, $xValues) $coefficients = []; for ($i = 0; $i < $C->getRowDimension(); ++$i) { $r = $C->get($i, 0); - if (abs($r) <= pow(10, -9)) { + if (abs($r) <= 10 ** (-9)) { $r = 0; } $coefficients[] = $r; @@ -178,9 +182,8 @@ private function polynomialRegression($order, $yValues, $xValues) * @param int $order Order of Polynomial for this regression * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - public function __construct($order, $yValues, $xValues = [], $const = true) + public function __construct($order, $yValues, $xValues = []) { parent::__construct($yValues, $xValues); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php index 4eefec82..cafd0115 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/PowerBestFit.php @@ -21,7 +21,7 @@ class PowerBestFit extends BestFit */ public function getValueOfYForX($xValue) { - return $this->getIntersect() * pow(($xValue - $this->xOffset), $this->getSlope()); + return $this->getIntersect() * ($xValue - $this->xOffset) ** $this->getSlope(); } /** @@ -33,7 +33,7 @@ public function getValueOfYForX($xValue) */ public function getValueOfXForY($yValue) { - return pow((($yValue + $this->yOffset) / $this->getIntersect()), (1 / $this->getSlope())); + return (($yValue + $this->yOffset) / $this->getIntersect()) ** (1 / $this->getSlope()); } /** @@ -72,28 +72,23 @@ public function getIntersect($dp = 0) * * @param float[] $yValues The set of Y-values for this regression * @param float[] $xValues The set of X-values for this regression - * @param bool $const */ - private function powerRegression($yValues, $xValues, $const) + private function powerRegression(array $yValues, array $xValues, bool $const): void { - foreach ($xValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); - foreach ($yValues as &$value) { - if ($value < 0.0) { - $value = 0 - log(abs($value)); - } elseif ($value > 0.0) { - $value = log($value); - } - } - unset($value); + $adjustedYValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $yValues + ); + $adjustedXValues = array_map( + function ($value) { + return ($value < 0.0) ? 0 - log(abs($value)) : log($value); + }, + $xValues + ); - $this->leastSquareFit($yValues, $xValues, $const); + $this->leastSquareFit($adjustedYValues, $adjustedXValues, $const); } /** @@ -108,7 +103,7 @@ public function __construct($yValues, $xValues = [], $const = true) parent::__construct($yValues, $xValues); if (!$this->error) { - $this->powerRegression($yValues, $xValues, $const); + $this->powerRegression($yValues, $xValues, (bool) $const); } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php index 1b7b3901..929f59b9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Trend/Trend.php @@ -44,7 +44,7 @@ class Trend /** * Cached results for each method when trying to identify which provides the best fit. * - * @var bestFit[] + * @var BestFit[] */ private static $trendCache = []; @@ -55,10 +55,9 @@ public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [ $nX = count($xValues); // Define X Values if necessary - if ($nX == 0) { + if ($nX === 0) { $xValues = range(1, $nY); - $nX = $nY; - } elseif ($nY != $nX) { + } elseif ($nY !== $nX) { // Ensure both arrays of points are the same size trigger_error('Trend(): Number of elements in coordinate arrays do not match.', E_USER_ERROR); } @@ -73,6 +72,7 @@ public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [ case self::TREND_POWER: if (!isset(self::$trendCache[$key])) { $className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; + // @phpstan-ignore-next-line self::$trendCache[$key] = new $className($yValues, $xValues, $const); } @@ -83,8 +83,8 @@ public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [ case self::TREND_POLYNOMIAL_5: case self::TREND_POLYNOMIAL_6: if (!isset(self::$trendCache[$key])) { - $order = substr($trendType, -1); - self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues, $const); + $order = (int) substr($trendType, -1); + self::$trendCache[$key] = new PolynomialBestFit($order, $yValues, $xValues); } return self::$trendCache[$key]; @@ -92,6 +92,8 @@ public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [ case self::TREND_BEST_FIT_NO_POLY: // If the request is to determine the best fit regression, then we test each Trend line in turn // Start by generating an instance of each available Trend method + $bestFit = []; + $bestFitValue = []; foreach (self::$trendTypes as $trendMethod) { $className = '\PhpOffice\PhpSpreadsheet\Shared\Trend\\' . $trendType . 'BestFit'; $bestFit[$trendMethod] = new $className($yValues, $xValues, $const); @@ -99,8 +101,8 @@ public static function calculate($trendType = self::TREND_BEST_FIT, $yValues = [ } if ($trendType != self::TREND_BEST_FIT_NO_POLY) { foreach (self::$trendTypePolynomialOrders as $trendMethod) { - $order = substr($trendMethod, -1); - $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues, $const); + $order = (int) substr($trendMethod, -1); + $bestFit[$trendMethod] = new PolynomialBestFit($order, $yValues, $xValues); if ($bestFit[$trendMethod]->getError()) { unset($bestFit[$trendMethod]); } else { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php index 4f7a6a06..3dc0aad9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/XMLWriter.php @@ -20,20 +20,20 @@ class XMLWriter extends \XMLWriter /** * Create a new XMLWriter instance. * - * @param int $pTemporaryStorage Temporary storage location - * @param string $pTemporaryStorageFolder Temporary storage folder + * @param int $temporaryStorage Temporary storage location + * @param string $temporaryStorageFolder Temporary storage folder */ - public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = null) + public function __construct($temporaryStorage = self::STORAGE_MEMORY, $temporaryStorageFolder = null) { // Open temporary storage - if ($pTemporaryStorage == self::STORAGE_MEMORY) { + if ($temporaryStorage == self::STORAGE_MEMORY) { $this->openMemory(); } else { // Create temporary filename - if ($pTemporaryStorageFolder === null) { - $pTemporaryStorageFolder = File::sysGetTempDir(); + if ($temporaryStorageFolder === null) { + $temporaryStorageFolder = File::sysGetTempDir(); } - $this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); + $this->tempFileName = @tempnam($temporaryStorageFolder, 'xml'); // Open storage if ($this->openUri($this->tempFileName) === false) { @@ -54,7 +54,9 @@ public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTempora public function __destruct() { // Unlink temporary files + // There is nothing reasonable to do if unlink fails. if ($this->tempFileName != '') { + /** @scrutinizer ignore-unhandled */ @unlink($this->tempFileName); } } @@ -77,16 +79,16 @@ public function getData() /** * Wrapper method for writeRaw. * - * @param string|string[] $text + * @param null|string|string[] $rawTextData * * @return bool */ - public function writeRawData($text) + public function writeRawData($rawTextData) { - if (is_array($text)) { - $text = implode("\n", $text); + if (is_array($rawTextData)) { + $rawTextData = implode("\n", $rawTextData); } - return $this->writeRaw(htmlspecialchars($text)); + return $this->writeRaw(htmlspecialchars($rawTextData ?? '')); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xls.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xls.php index b8ce5e2d..2c3198b0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xls.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/Xls.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Helper\Dimension; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Xls @@ -12,27 +13,27 @@ class Xls * x is the width in intrinsic Excel units (measuring width in number of normal characters) * This holds for Arial 10. * - * @param Worksheet $sheet The sheet + * @param Worksheet $worksheet The sheet * @param string $col The column * * @return int The width in pixels */ - public static function sizeCol($sheet, $col = 'A') + public static function sizeCol(Worksheet $worksheet, $col = 'A') { // default font of the workbook - $font = $sheet->getParent()->getDefaultStyle()->getFont(); + $font = $worksheet->getParent()->getDefaultStyle()->getFont(); - $columnDimensions = $sheet->getColumnDimensions(); + $columnDimensions = $worksheet->getColumnDimensions(); // first find the true column width in pixels (uncollapsed and unhidden) - if (isset($columnDimensions[$col]) and $columnDimensions[$col]->getWidth() != -1) { + if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { // then we have column dimension with explicit width $columnDimension = $columnDimensions[$col]; $width = $columnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); - } elseif ($sheet->getDefaultColumnDimension()->getWidth() != -1) { + } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) { // then we have default column dimension with explicit width - $defaultColumnDimension = $sheet->getDefaultColumnDimension(); + $defaultColumnDimension = $worksheet->getDefaultColumnDimension(); $width = $defaultColumnDimension->getWidth(); $pixelWidth = Drawing::cellDimensionToPixels($width, $font); } else { @@ -41,7 +42,7 @@ public static function sizeCol($sheet, $col = 'A') } // now find the effective column width in pixels - if (isset($columnDimensions[$col]) and !$columnDimensions[$col]->getVisible()) { + if (isset($columnDimensions[$col]) && !$columnDimensions[$col]->getVisible()) { $effectivePixelWidth = 0; } else { $effectivePixelWidth = $pixelWidth; @@ -55,50 +56,48 @@ public static function sizeCol($sheet, $col = 'A') * the relationship is: y = 4/3x. If the height hasn't been set by the user we * use the default value. If the row is hidden we use a value of zero. * - * @param Worksheet $sheet The sheet + * @param Worksheet $worksheet The sheet * @param int $row The row index (1-based) * * @return int The width in pixels */ - public static function sizeRow($sheet, $row = 1) + public static function sizeRow(Worksheet $worksheet, $row = 1) { // default font of the workbook - $font = $sheet->getParent()->getDefaultStyle()->getFont(); + $font = $worksheet->getParent()->getDefaultStyle()->getFont(); - $rowDimensions = $sheet->getRowDimensions(); + $rowDimensions = $worksheet->getRowDimensions(); // first find the true row height in pixels (uncollapsed and unhidden) - if (isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) { + if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { // then we have a row dimension $rowDimension = $rowDimensions[$row]; $rowHeight = $rowDimension->getRowHeight(); $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 - } elseif ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { + } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) { // then we have a default row dimension with explicit height - $defaultRowDimension = $sheet->getDefaultRowDimension(); - $rowHeight = $defaultRowDimension->getRowHeight(); - $pixelRowHeight = Drawing::pointsToPixels($rowHeight); + $defaultRowDimension = $worksheet->getDefaultRowDimension(); + $pixelRowHeight = $defaultRowDimension->getRowHeight(Dimension::UOM_PIXELS); } else { // we don't even have any default row dimension. Height depends on default font $pointRowHeight = Font::getDefaultRowHeightByFont($font); - $pixelRowHeight = Font::fontSizeToPixels($pointRowHeight); + $pixelRowHeight = Font::fontSizeToPixels((int) $pointRowHeight); } // now find the effective row height in pixels - if (isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible()) { + if (isset($rowDimensions[$row]) && !$rowDimensions[$row]->getVisible()) { $effectivePixelRowHeight = 0; } else { $effectivePixelRowHeight = $pixelRowHeight; } - return $effectivePixelRowHeight; + return (int) $effectivePixelRowHeight; } /** * Get the horizontal distance in pixels between two anchors * The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets. * - * @param Worksheet $sheet * @param string $startColumn * @param int $startOffsetX Offset within start cell measured in 1/1024 of the cell width * @param string $endColumn @@ -106,7 +105,7 @@ public static function sizeRow($sheet, $row = 1) * * @return int Horizontal measured in pixels */ - public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) + public static function getDistanceX(Worksheet $worksheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) { $distanceX = 0; @@ -114,14 +113,14 @@ public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $start $startColumnIndex = Coordinate::columnIndexFromString($startColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn); for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { - $distanceX += self::sizeCol($sheet, Coordinate::stringFromColumnIndex($i)); + $distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i)); } // correct for offsetX in startcell - $distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); + $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024); // correct for offsetX in endcell - $distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024)); + $distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024)); return $distanceX; } @@ -130,7 +129,6 @@ public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $start * Get the vertical distance in pixels between two anchors * The distanceY is found as sum of all the spanning rows minus two offsets. * - * @param Worksheet $sheet * @param int $startRow (1-based) * @param int $startOffsetY Offset within start cell measured in 1/256 of the cell height * @param int $endRow (1-based) @@ -138,20 +136,20 @@ public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $start * * @return int Vertical distance measured in pixels */ - public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) + public static function getDistanceY(Worksheet $worksheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) { $distanceY = 0; // add the widths of the spanning rows for ($row = $startRow; $row <= $endRow; ++$row) { - $distanceY += self::sizeRow($sheet, $row); + $distanceY += self::sizeRow($worksheet, $row); } // correct for offsetX in startcell - $distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256); + $distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256); // correct for offsetX in endcell - $distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); + $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256)); return $distanceY; } @@ -200,19 +198,17 @@ public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffse * W is the width of the cell * H is the height of the cell * - * @param Worksheet $sheet * @param string $coordinates E.g. 'A1' * @param int $offsetX Horizontal offset in pixels * @param int $offsetY Vertical offset in pixels * @param int $width Width in pixels * @param int $height Height in pixels * - * @return array + * @return null|array */ - public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) + public static function oneAnchor2twoAnchor(Worksheet $worksheet, $coordinates, $offsetX, $offsetY, $width, $height) { - [$column, $row] = Coordinate::coordinateFromString($coordinates); - $col_start = Coordinate::columnIndexFromString($column); + [$col_start, $row] = Coordinate::indexesFromString($coordinates); $row_start = $row - 1; $x1 = $offsetX; @@ -223,10 +219,10 @@ public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offs $row_end = $row_start; // Row containing bottom right corner of object // Zero the specified offset if greater than the cell dimensions - if ($x1 >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start))) { + if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) { $x1 = 0; } - if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { + if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) { $y1 = 0; } @@ -234,37 +230,37 @@ public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offs $height = $height + $y1 - 1; // Subtract the underlying cell widths to find the end cell of the image - while ($width >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end))) { - $width -= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)); + while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) { + $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)); ++$col_end; } // Subtract the underlying cell heights to find the end cell of the image - while ($height >= self::sizeRow($sheet, $row_end + 1)) { - $height -= self::sizeRow($sheet, $row_end + 1); + while ($height >= self::sizeRow($worksheet, $row_end + 1)) { + $height -= self::sizeRow($worksheet, $row_end + 1); ++$row_end; } // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // with zero height or width. - if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { - return; + if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { + return null; } - if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { - return; + if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { + return null; } - if (self::sizeRow($sheet, $row_start + 1) == 0) { - return; + if (self::sizeRow($worksheet, $row_start + 1) == 0) { + return null; } - if (self::sizeRow($sheet, $row_end + 1) == 0) { - return; + if (self::sizeRow($worksheet, $row_end + 1) == 0) { + return null; } // Convert the pixel values to the percentage value expected by Excel - $x1 = $x1 / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; - $y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; - $x2 = ($width + 1) / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object - $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object + $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256; + $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object $startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php index d33a9871..33b4fe0c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; +use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Iterator; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; @@ -14,6 +15,9 @@ class Spreadsheet const VISIBILITY_HIDDEN = 'hidden'; const VISIBILITY_VERY_HIDDEN = 'veryHidden'; + private const DEFINED_NAME_IS_RANGE = false; + private const DEFINED_NAME_IS_FORMULA = true; + private static $workbookViewVisibilityValues = [ self::VISIBILITY_VISIBLE, self::VISIBILITY_HIDDEN, @@ -51,7 +55,7 @@ class Spreadsheet /** * Calculation Engine. * - * @var Calculation + * @var null|Calculation */ private $calculationEngine; @@ -65,9 +69,9 @@ class Spreadsheet /** * Named ranges. * - * @var NamedRange[] + * @var DefinedName[] */ - private $namedRanges = []; + private $definedNames = []; /** * CellXf supervisor. @@ -100,21 +104,21 @@ class Spreadsheet /** * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro. * - * @var string + * @var null|string */ private $macrosCode; /** * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed. * - * @var string + * @var null|string */ private $macrosCertificate; /** * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI. * - * @var null|string + * @var null|array{target: string, data: string} */ private $ribbonXMLData; @@ -210,7 +214,7 @@ public function hasMacros() * * @param bool $hasMacros true|false */ - public function setHasMacros($hasMacros) + public function setHasMacros($hasMacros): void { $this->hasMacros = (bool) $hasMacros; } @@ -220,7 +224,7 @@ public function setHasMacros($hasMacros) * * @param string $macroCode string|null */ - public function setMacrosCode($macroCode) + public function setMacrosCode($macroCode): void { $this->macrosCode = $macroCode; $this->setHasMacros($macroCode !== null); @@ -241,7 +245,7 @@ public function getMacrosCode() * * @param null|string $certificate */ - public function setMacrosCertificate($certificate) + public function setMacrosCertificate($certificate): void { $this->macrosCertificate = $certificate; } @@ -269,7 +273,7 @@ public function getMacrosCertificate() /** * Remove all macros, certificate from spreadsheet. */ - public function discardMacros() + public function discardMacros(): void { $this->hasMacros = false; $this->macrosCode = null; @@ -282,7 +286,7 @@ public function discardMacros() * @param null|mixed $target * @param null|mixed $xmlData */ - public function setRibbonXMLData($target, $xmlData) + public function setRibbonXMLData($target, $xmlData): void { if ($target !== null && $xmlData !== null) { $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData]; @@ -294,11 +298,9 @@ public function setRibbonXMLData($target, $xmlData) /** * retrieve ribbon XML Data. * - * return string|null|array - * * @param string $what * - * @return string + * @return null|array|string */ public function getRibbonXMLData($what = 'all') //we need some constants here... { @@ -311,7 +313,7 @@ public function getRibbonXMLData($what = 'all') //we need some constants here... break; case 'target': case 'data': - if (is_array($this->ribbonXMLData) && isset($this->ribbonXMLData[$what])) { + if (is_array($this->ribbonXMLData)) { $returnData = $this->ribbonXMLData[$what]; } @@ -327,7 +329,7 @@ public function getRibbonXMLData($what = 'all') //we need some constants here... * @param null|mixed $BinObjectsNames * @param null|mixed $BinObjectsData */ - public function setRibbonBinObjects($BinObjectsNames, $BinObjectsData) + public function setRibbonBinObjects($BinObjectsNames, $BinObjectsData): void { if ($BinObjectsNames !== null && $BinObjectsData !== null) { $this->ribbonBinObjects = ['names' => $BinObjectsNames, 'data' => $BinObjectsData]; @@ -354,10 +356,8 @@ public function getUnparsedLoadedData() * It has to be minimized when the library start to support currently unparsed data. * * @internal - * - * @param array $unparsedLoadedData */ - public function setUnparsedLoadedData(array $unparsedLoadedData) + public function setUnparsedLoadedData(array $unparsedLoadedData): void { $this->unparsedLoadedData = $unparsedLoadedData; } @@ -371,7 +371,9 @@ public function setUnparsedLoadedData(array $unparsedLoadedData) */ private function getExtensionOnly($path) { - return pathinfo($path, PATHINFO_EXTENSION); + $extension = pathinfo($path, PATHINFO_EXTENSION); + + return is_array($extension) ? '' : $extension; } /** @@ -398,8 +400,10 @@ public function getRibbonBinObjects($what = 'all') break; case 'types': - if (is_array($this->ribbonBinObjects) && - isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data'])) { + if ( + is_array($this->ribbonBinObjects) && + isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data']) + ) { $tmpTypes = array_keys($this->ribbonBinObjects['data']); $ReturnData = array_unique(array_map([$this, 'getExtensionOnly'], $tmpTypes)); } else { @@ -435,27 +439,27 @@ public function hasRibbonBinObjects() /** * Check if a sheet with a specified code name already exists. * - * @param string $pSheetCodeName Name of the worksheet to check + * @param string $codeName Name of the worksheet to check * * @return bool */ - public function sheetCodeNameExists($pSheetCodeName) + public function sheetCodeNameExists($codeName) { - return $this->getSheetByCodeName($pSheetCodeName) !== null; + return $this->getSheetByCodeName($codeName) !== null; } /** * Get sheet by code name. Warning : sheet don't have always a code name ! * - * @param string $pName Sheet name + * @param string $codeName Sheet name * - * @return Worksheet + * @return null|Worksheet */ - public function getSheetByCodeName($pName) + public function getSheetByCodeName($codeName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { - if ($this->workSheetCollection[$i]->getCodeName() == $pName) { + if ($this->workSheetCollection[$i]->getCodeName() == $codeName) { return $this->workSheetCollection[$i]; } } @@ -482,8 +486,8 @@ public function __construct() // Create document security $this->security = new Document\Security(); - // Set named ranges - $this->namedRanges = []; + // Set defined names + $this->definedNames = []; // Create the cellXf supervisor $this->cellXfSupervisor = new Style(true); @@ -499,29 +503,29 @@ public function __construct() */ public function __destruct() { - $this->calculationEngine = null; $this->disconnectWorksheets(); + $this->calculationEngine = null; + $this->cellXfCollection = []; + $this->cellStyleXfCollection = []; } /** * Disconnect all worksheets from this PhpSpreadsheet workbook object, * typically so that the PhpSpreadsheet object can be unset. */ - public function disconnectWorksheets() + public function disconnectWorksheets(): void { - $worksheet = null; - foreach ($this->workSheetCollection as $k => &$worksheet) { + foreach ($this->workSheetCollection as $worksheet) { $worksheet->disconnectCells(); - $this->workSheetCollection[$k] = null; + unset($worksheet); } - unset($worksheet); $this->workSheetCollection = []; } /** * Return the calculation engine for this worksheet. * - * @return Calculation + * @return null|Calculation */ public function getCalculationEngine() { @@ -540,12 +544,10 @@ public function getProperties() /** * Set properties. - * - * @param Document\Properties $pValue */ - public function setProperties(Document\Properties $pValue) + public function setProperties(Document\Properties $documentProperties): void { - $this->properties = $pValue; + $this->properties = $documentProperties; } /** @@ -560,19 +562,15 @@ public function getSecurity() /** * Set security. - * - * @param Document\Security $pValue */ - public function setSecurity(Document\Security $pValue) + public function setSecurity(Document\Security $documentSecurity): void { - $this->security = $pValue; + $this->security = $documentSecurity; } /** * Get active sheet. * - * @throws Exception - * * @return Worksheet */ public function getActiveSheet() @@ -585,8 +583,6 @@ public function getActiveSheet() * * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * - * @throws Exception - * * @return Worksheet */ public function createSheet($sheetIndex = null) @@ -600,80 +596,78 @@ public function createSheet($sheetIndex = null) /** * Check if a sheet with a specified name already exists. * - * @param string $pSheetName Name of the worksheet to check + * @param string $worksheetName Name of the worksheet to check * * @return bool */ - public function sheetNameExists($pSheetName) + public function sheetNameExists($worksheetName) { - return $this->getSheetByName($pSheetName) !== null; + return $this->getSheetByName($worksheetName) !== null; } /** * Add sheet. * - * @param Worksheet $pSheet - * @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last) - * - * @throws Exception + * @param Worksheet $worksheet The worksheet to add + * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * * @return Worksheet */ - public function addSheet(Worksheet $pSheet, $iSheetIndex = null) + public function addSheet(Worksheet $worksheet, $sheetIndex = null) { - if ($this->sheetNameExists($pSheet->getTitle())) { + if ($this->sheetNameExists($worksheet->getTitle())) { throw new Exception( - "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first." + "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first." ); } - if ($iSheetIndex === null) { + if ($sheetIndex === null) { if ($this->activeSheetIndex < 0) { $this->activeSheetIndex = 0; } - $this->workSheetCollection[] = $pSheet; + $this->workSheetCollection[] = $worksheet; } else { // Insert the sheet at the requested index array_splice( $this->workSheetCollection, - $iSheetIndex, + $sheetIndex, 0, - [$pSheet] + [$worksheet] ); // Adjust active sheet index if necessary - if ($this->activeSheetIndex >= $iSheetIndex) { + if ($this->activeSheetIndex >= $sheetIndex) { ++$this->activeSheetIndex; } } - if ($pSheet->getParent() === null) { - $pSheet->rebindParent($this); + if ($worksheet->getParent() === null) { + $worksheet->rebindParent($this); } - return $pSheet; + return $worksheet; } /** * Remove sheet by index. * - * @param int $pIndex Active sheet index - * - * @throws Exception + * @param int $sheetIndex Index position of the worksheet to remove */ - public function removeSheetByIndex($pIndex) + public function removeSheetByIndex($sheetIndex): void { $numSheets = count($this->workSheetCollection); - if ($pIndex > $numSheets - 1) { + if ($sheetIndex > $numSheets - 1) { throw new Exception( - "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}." ); } - array_splice($this->workSheetCollection, $pIndex, 1); + array_splice($this->workSheetCollection, $sheetIndex, 1); // Adjust active sheet index if necessary - if (($this->activeSheetIndex >= $pIndex) && - ($pIndex > count($this->workSheetCollection) - 1)) { + if ( + ($this->activeSheetIndex >= $sheetIndex) && + ($this->activeSheetIndex > 0 || $numSheets <= 1) + ) { --$this->activeSheetIndex; } } @@ -681,23 +675,21 @@ public function removeSheetByIndex($pIndex) /** * Get sheet by index. * - * @param int $pIndex Sheet index - * - * @throws Exception + * @param int $sheetIndex Sheet index * * @return Worksheet */ - public function getSheet($pIndex) + public function getSheet($sheetIndex) { - if (!isset($this->workSheetCollection[$pIndex])) { + if (!isset($this->workSheetCollection[$sheetIndex])) { $numSheets = $this->getSheetCount(); throw new Exception( - "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}." + "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}." ); } - return $this->workSheetCollection[$pIndex]; + return $this->workSheetCollection[$sheetIndex]; } /** @@ -713,15 +705,15 @@ public function getAllSheets() /** * Get sheet by name. * - * @param string $pName Sheet name + * @param string $worksheetName Sheet name * * @return null|Worksheet */ - public function getSheetByName($pName) + public function getSheetByName($worksheetName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { - if ($this->workSheetCollection[$i]->getTitle() === trim($pName, "'")) { + if ($this->workSheetCollection[$i]->getTitle() === trim($worksheetName, "'")) { return $this->workSheetCollection[$i]; } } @@ -732,16 +724,12 @@ public function getSheetByName($pName) /** * Get index for sheet. * - * @param Worksheet $pSheet - * - * @throws Exception - * * @return int index */ - public function getIndex(Worksheet $pSheet) + public function getIndex(Worksheet $worksheet) { foreach ($this->workSheetCollection as $key => $value) { - if ($value->getHashCode() == $pSheet->getHashCode()) { + if ($value->getHashCode() === $worksheet->getHashCode()) { return $key; } } @@ -752,29 +740,27 @@ public function getIndex(Worksheet $pSheet) /** * Set index for sheet by sheet name. * - * @param string $sheetName Sheet name to modify index for - * @param int $newIndex New index for the sheet - * - * @throws Exception + * @param string $worksheetName Sheet name to modify index for + * @param int $newIndexPosition New index for the sheet * * @return int New sheet index */ - public function setIndexByName($sheetName, $newIndex) + public function setIndexByName($worksheetName, $newIndexPosition) { - $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); - $pSheet = array_splice( + $oldIndex = $this->getIndex($this->getSheetByName($worksheetName)); + $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, - $newIndex, + $newIndexPosition, 0, - $pSheet + $worksheet ); - return $newIndex; + return $newIndexPosition; } /** @@ -800,22 +786,20 @@ public function getActiveSheetIndex() /** * Set active sheet index. * - * @param int $pIndex Active sheet index - * - * @throws Exception + * @param int $worksheetIndex Active sheet index * * @return Worksheet */ - public function setActiveSheetIndex($pIndex) + public function setActiveSheetIndex($worksheetIndex) { $numSheets = count($this->workSheetCollection); - if ($pIndex > $numSheets - 1) { + if ($worksheetIndex > $numSheets - 1) { throw new Exception( - "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}." ); } - $this->activeSheetIndex = $pIndex; + $this->activeSheetIndex = $worksheetIndex; return $this->getActiveSheet(); } @@ -823,21 +807,19 @@ public function setActiveSheetIndex($pIndex) /** * Set active sheet index by name. * - * @param string $pValue Sheet title - * - * @throws Exception + * @param string $worksheetName Sheet title * * @return Worksheet */ - public function setActiveSheetIndexByName($pValue) + public function setActiveSheetIndexByName($worksheetName) { - if (($worksheet = $this->getSheetByName($pValue)) instanceof Worksheet) { + if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } - throw new Exception('Workbook does not contain sheet:' . $pValue); + throw new Exception('Workbook does not contain sheet:' . $worksheetName); } /** @@ -859,90 +841,204 @@ public function getSheetNames() /** * Add external sheet. * - * @param Worksheet $pSheet External sheet to add - * @param null|int $iSheetIndex Index where sheet should go (0,1,..., or null for last) - * - * @throws Exception + * @param Worksheet $worksheet External sheet to add + * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * * @return Worksheet */ - public function addExternalSheet(Worksheet $pSheet, $iSheetIndex = null) + public function addExternalSheet(Worksheet $worksheet, $sheetIndex = null) { - if ($this->sheetNameExists($pSheet->getTitle())) { - throw new Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); + if ($this->sheetNameExists($worksheet->getTitle())) { + throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first."); } // count how many cellXfs there are in this workbook currently, we will need this below $countCellXfs = count($this->cellXfCollection); // copy all the shared cellXfs from the external workbook and append them to the current - foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { + foreach ($worksheet->getParent()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook - $pSheet->rebindParent($this); + $worksheet->rebindParent($this); // update the cellXfs - foreach ($pSheet->getCoordinates(false) as $coordinate) { - $cell = $pSheet->getCell($coordinate); + foreach ($worksheet->getCoordinates(false) as $coordinate) { + $cell = $worksheet->getCell($coordinate); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } - return $this->addSheet($pSheet, $iSheetIndex); + // update the column dimensions Xfs + foreach ($worksheet->getColumnDimensions() as $columnDimension) { + $columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs); + } + + // update the row dimensions Xfs + foreach ($worksheet->getRowDimensions() as $rowDimension) { + $xfIndex = $rowDimension->getXfIndex(); + if ($xfIndex !== null) { + $rowDimension->setXfIndex($xfIndex + $countCellXfs); + } + } + + return $this->addSheet($worksheet, $sheetIndex); } /** - * Get named ranges. + * Get an array of all Named Ranges. * - * @return NamedRange[] + * @return DefinedName[] */ - public function getNamedRanges() + public function getNamedRanges(): array { - return $this->namedRanges; + return array_filter( + $this->definedNames, + function (DefinedName $definedName) { + return $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE; + } + ); } /** - * Add named range. + * Get an array of all Named Formulae. * - * @param NamedRange $namedRange + * @return DefinedName[] + */ + public function getNamedFormulae(): array + { + return array_filter( + $this->definedNames, + function (DefinedName $definedName) { + return $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA; + } + ); + } + + /** + * Get an array of all Defined Names (both named ranges and named formulae). * - * @return bool + * @return DefinedName[] + */ + public function getDefinedNames(): array + { + return $this->definedNames; + } + + /** + * Add a named range. + * If a named range with this name already exists, then this will replace the existing value. + */ + public function addNamedRange(NamedRange $namedRange): void + { + $this->addDefinedName($namedRange); + } + + /** + * Add a named formula. + * If a named formula with this name already exists, then this will replace the existing value. + */ + public function addNamedFormula(NamedFormula $namedFormula): void + { + $this->addDefinedName($namedFormula); + } + + /** + * Add a defined name (either a named range or a named formula). + * If a defined named with this name already exists, then this will replace the existing value. */ - public function addNamedRange(NamedRange $namedRange) + public function addDefinedName(DefinedName $definedName): void { - if ($namedRange->getScope() == null) { + $upperCaseName = StringHelper::strToUpper($definedName->getName()); + if ($definedName->getScope() == null) { // global scope - $this->namedRanges[$namedRange->getName()] = $namedRange; + $this->definedNames[$upperCaseName] = $definedName; } else { // local scope - $this->namedRanges[$namedRange->getScope()->getTitle() . '!' . $namedRange->getName()] = $namedRange; + $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName; } - - return true; } /** * Get named range. * - * @param string $namedRange - * @param null|Worksheet $pSheet Scope. Use null for global scope + * @param null|Worksheet $worksheet Scope. Use null for global scope + */ + public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange + { + $returnValue = null; + + if ($namedRange !== '') { + $namedRange = StringHelper::strToUpper($namedRange); + // first look for global named range + $returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE); + // then look for local named range (has priority over global named range if both names exist) + $returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue; + } + + return $returnValue instanceof NamedRange ? $returnValue : null; + } + + /** + * Get named formula. + * + * @param null|Worksheet $worksheet Scope. Use null for global scope + */ + public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula + { + $returnValue = null; + + if ($namedFormula !== '') { + $namedFormula = StringHelper::strToUpper($namedFormula); + // first look for global named formula + $returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA); + // then look for local named formula (has priority over global named formula if both names exist) + $returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue; + } + + return $returnValue instanceof NamedFormula ? $returnValue : null; + } + + private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName + { + if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) { + return $this->definedNames[$name]; + } + + return null; + } + + private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName + { + if ( + ($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name]) + && $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type + ) { + return $this->definedNames[$worksheet->getTitle() . '!' . $name]; + } + + return null; + } + + /** + * Get named range. * - * @return null|NamedRange + * @param null|Worksheet $worksheet Scope. Use null for global scope */ - public function getNamedRange($namedRange, Worksheet $pSheet = null) + public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName { $returnValue = null; - if ($namedRange != '' && ($namedRange !== null)) { + if ($definedName !== '') { + $definedName = StringHelper::strToUpper($definedName); // first look for global defined name - if (isset($this->namedRanges[$namedRange])) { - $returnValue = $this->namedRanges[$namedRange]; + if (isset($this->definedNames[$definedName])) { + $returnValue = $this->definedNames[$definedName]; } // then look for local defined name (has priority over global defined name if both names exist) - if (($pSheet !== null) && isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { - $returnValue = $this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]; + if (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { + $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName]; } } @@ -952,20 +1048,55 @@ public function getNamedRange($namedRange, Worksheet $pSheet = null) /** * Remove named range. * - * @param string $namedRange - * @param null|Worksheet $pSheet scope: use null for global scope + * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ - public function removeNamedRange($namedRange, Worksheet $pSheet = null) + public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self { - if ($pSheet === null) { - if (isset($this->namedRanges[$namedRange])) { - unset($this->namedRanges[$namedRange]); + if ($this->getNamedRange($namedRange, $worksheet) === null) { + return $this; + } + + return $this->removeDefinedName($namedRange, $worksheet); + } + + /** + * Remove named formula. + * + * @param null|Worksheet $worksheet scope: use null for global scope + * + * @return $this + */ + public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self + { + if ($this->getNamedFormula($namedFormula, $worksheet) === null) { + return $this; + } + + return $this->removeDefinedName($namedFormula, $worksheet); + } + + /** + * Remove defined name. + * + * @param null|Worksheet $worksheet scope: use null for global scope + * + * @return $this + */ + public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self + { + $definedName = StringHelper::strToUpper($definedName); + + if ($worksheet === null) { + if (isset($this->definedNames[$definedName])) { + unset($this->definedNames[$definedName]); } } else { - if (isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { - unset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]); + if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { + unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]); + } elseif (isset($this->definedNames[$definedName])) { + unset($this->definedNames[$definedName]); } } @@ -1005,6 +1136,7 @@ public function copy() */ public function __clone() { + // @phpstan-ignore-next-line foreach ($this as $key => $val) { if (is_object($val) || (is_array($val))) { $this->{$key} = unserialize(serialize($val)); @@ -1025,26 +1157,26 @@ public function getCellXfCollection() /** * Get cellXf by index. * - * @param int $pIndex + * @param int $cellStyleIndex * * @return Style */ - public function getCellXfByIndex($pIndex) + public function getCellXfByIndex($cellStyleIndex) { - return $this->cellXfCollection[$pIndex]; + return $this->cellXfCollection[$cellStyleIndex]; } /** * Get cellXf by hash code. * - * @param string $pValue + * @param string $hashcode * * @return false|Style */ - public function getCellXfByHashCode($pValue) + public function getCellXfByHashCode($hashcode) { foreach ($this->cellXfCollection as $cellXf) { - if ($cellXf->getHashCode() == $pValue) { + if ($cellXf->getHashCode() === $hashcode) { return $cellXf; } } @@ -1055,20 +1187,16 @@ public function getCellXfByHashCode($pValue) /** * Check if style exists in style collection. * - * @param Style $pCellStyle - * * @return bool */ - public function cellXfExists($pCellStyle) + public function cellXfExists(Style $cellStyleIndex) { - return in_array($pCellStyle, $this->cellXfCollection, true); + return in_array($cellStyleIndex, $this->cellXfCollection, true); } /** * Get default style. * - * @throws Exception - * * @return Style */ public function getDefaultStyle() @@ -1082,10 +1210,8 @@ public function getDefaultStyle() /** * Add a cellXf to the workbook. - * - * @param Style $style */ - public function addCellXf(Style $style) + public function addCellXf(Style $style): void { $this->cellXfCollection[] = $style; $style->setIndex(count($this->cellXfCollection) - 1); @@ -1094,28 +1220,26 @@ public function addCellXf(Style $style) /** * Remove cellXf by index. It is ensured that all cells get their xf index updated. * - * @param int $pIndex Index to cellXf - * - * @throws Exception + * @param int $cellStyleIndex Index to cellXf */ - public function removeCellXfByIndex($pIndex) + public function removeCellXfByIndex($cellStyleIndex): void { - if ($pIndex > count($this->cellXfCollection) - 1) { + if ($cellStyleIndex > count($this->cellXfCollection) - 1) { throw new Exception('CellXf index is out of bounds.'); } // first remove the cellXf - array_splice($this->cellXfCollection, $pIndex, 1); + array_splice($this->cellXfCollection, $cellStyleIndex, 1); // then update cellXf indexes for cells foreach ($this->workSheetCollection as $worksheet) { foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $xfIndex = $cell->getXfIndex(); - if ($xfIndex > $pIndex) { + if ($xfIndex > $cellStyleIndex) { // decrease xf index by 1 $cell->setXfIndex($xfIndex - 1); - } elseif ($xfIndex == $pIndex) { + } elseif ($xfIndex == $cellStyleIndex) { // set to default xf index 0 $cell->setXfIndex(0); } @@ -1146,26 +1270,26 @@ public function getCellStyleXfCollection() /** * Get cellStyleXf by index. * - * @param int $pIndex Index to cellXf + * @param int $cellStyleIndex Index to cellXf * * @return Style */ - public function getCellStyleXfByIndex($pIndex) + public function getCellStyleXfByIndex($cellStyleIndex) { - return $this->cellStyleXfCollection[$pIndex]; + return $this->cellStyleXfCollection[$cellStyleIndex]; } /** * Get cellStyleXf by hash code. * - * @param string $pValue + * @param string $hashcode * * @return false|Style */ - public function getCellStyleXfByHashCode($pValue) + public function getCellStyleXfByHashCode($hashcode) { foreach ($this->cellStyleXfCollection as $cellStyleXf) { - if ($cellStyleXf->getHashCode() == $pValue) { + if ($cellStyleXf->getHashCode() === $hashcode) { return $cellStyleXf; } } @@ -1175,35 +1299,31 @@ public function getCellStyleXfByHashCode($pValue) /** * Add a cellStyleXf to the workbook. - * - * @param Style $pStyle */ - public function addCellStyleXf(Style $pStyle) + public function addCellStyleXf(Style $style): void { - $this->cellStyleXfCollection[] = $pStyle; - $pStyle->setIndex(count($this->cellStyleXfCollection) - 1); + $this->cellStyleXfCollection[] = $style; + $style->setIndex(count($this->cellStyleXfCollection) - 1); } /** * Remove cellStyleXf by index. * - * @param int $pIndex Index to cellXf - * - * @throws Exception + * @param int $cellStyleIndex Index to cellXf */ - public function removeCellStyleXfByIndex($pIndex) + public function removeCellStyleXfByIndex($cellStyleIndex): void { - if ($pIndex > count($this->cellStyleXfCollection) - 1) { + if ($cellStyleIndex > count($this->cellStyleXfCollection) - 1) { throw new Exception('CellStyleXf index is out of bounds.'); } - array_splice($this->cellStyleXfCollection, $pIndex, 1); + array_splice($this->cellStyleXfCollection, $cellStyleIndex, 1); } /** * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells * and columns in the workbook. */ - public function garbageCollect() + public function garbageCollect(): void { // how many references are there to each cellXf ? $countReferencesCellXf = []; @@ -1234,6 +1354,7 @@ public function garbageCollect() // remove cellXfs without references and create mapping so we can update xfIndex // for all cells and columns $countNeededCellXfs = 0; + $map = []; foreach ($this->cellXfCollection as $index => $cellXf) { if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf ++$countNeededCellXfs; @@ -1304,7 +1425,7 @@ public function getShowHorizontalScroll() * * @param bool $showHorizontalScroll True if horizonal scroll bar is visible */ - public function setShowHorizontalScroll($showHorizontalScroll) + public function setShowHorizontalScroll($showHorizontalScroll): void { $this->showHorizontalScroll = (bool) $showHorizontalScroll; } @@ -1324,7 +1445,7 @@ public function getShowVerticalScroll() * * @param bool $showVerticalScroll True if vertical scroll bar is visible */ - public function setShowVerticalScroll($showVerticalScroll) + public function setShowVerticalScroll($showVerticalScroll): void { $this->showVerticalScroll = (bool) $showVerticalScroll; } @@ -1344,7 +1465,7 @@ public function getShowSheetTabs() * * @param bool $showSheetTabs True if sheet tabs are visible */ - public function setShowSheetTabs($showSheetTabs) + public function setShowSheetTabs($showSheetTabs): void { $this->showSheetTabs = (bool) $showSheetTabs; } @@ -1364,7 +1485,7 @@ public function getMinimized() * * @param bool $minimized true if workbook window is minimized */ - public function setMinimized($minimized) + public function setMinimized($minimized): void { $this->minimized = (bool) $minimized; } @@ -1386,7 +1507,7 @@ public function getAutoFilterDateGrouping() * * @param bool $autoFilterDateGrouping true if workbook window is minimized */ - public function setAutoFilterDateGrouping($autoFilterDateGrouping) + public function setAutoFilterDateGrouping($autoFilterDateGrouping): void { $this->autoFilterDateGrouping = (bool) $autoFilterDateGrouping; } @@ -1405,10 +1526,8 @@ public function getFirstSheetIndex() * Set the first sheet in the book view. * * @param int $firstSheetIndex First sheet in book view - * - * @throws Exception if the given value is invalid */ - public function setFirstSheetIndex($firstSheetIndex) + public function setFirstSheetIndex($firstSheetIndex): void { if ($firstSheetIndex >= 0) { $this->firstSheetIndex = (int) $firstSheetIndex; @@ -1444,10 +1563,8 @@ public function getVisibility() * user interface. * * @param string $visibility visibility status of the workbook - * - * @throws Exception if the given value is invalid */ - public function setVisibility($visibility) + public function setVisibility($visibility): void { if ($visibility === null) { $visibility = self::VISIBILITY_VISIBLE; @@ -1476,10 +1593,8 @@ public function getTabRatio() * TabRatio is assumed to be out of 1000 of the horizontal window width. * * @param int $tabRatio Ratio between the tabs bar and the horizontal scroll bar - * - * @throws Exception if the given value is invalid */ - public function setTabRatio($tabRatio) + public function setTabRatio($tabRatio): void { if ($tabRatio >= 0 || $tabRatio <= 1000) { $this->tabRatio = (int) $tabRatio; @@ -1487,4 +1602,27 @@ public function setTabRatio($tabRatio) throw new Exception('Tab ratio must be between 0 and 1000.'); } } + + public function reevaluateAutoFilters(bool $resetToMax): void + { + foreach ($this->workSheetCollection as $sheet) { + $filter = $sheet->getAutoFilter(); + if (!empty($filter->getRange())) { + if ($resetToMax) { + $filter->setRangeToMaxRow(); + } + $filter->showHideRows(); + } + } + } + + /** + * Silliness to mollify Scrutinizer. + * + * @codeCoverageIgnore + */ + public function getSharedComponent(): Style + { + return new Style(); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php index 5eb7c2b0..83ac5b0d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php @@ -28,24 +28,28 @@ class Alignment extends Supervisor const READORDER_LTR = 1; const READORDER_RTL = 2; + // Special value for Text Rotation + const TEXTROTATION_STACK_EXCEL = 255; + const TEXTROTATION_STACK_PHPSPREADSHEET = -165; // 90 - 255 + /** * Horizontal alignment. * - * @var string + * @var null|string */ protected $horizontal = self::HORIZONTAL_GENERAL; /** * Vertical alignment. * - * @var string + * @var null|string */ protected $vertical = self::VERTICAL_BOTTOM; /** * Text rotation. * - * @var int + * @var null|int */ protected $textRotation = 0; @@ -107,7 +111,10 @@ public function __construct($isSupervisor = false, $isConditional = false) */ public function getSharedComponent() { - return $this->parent->getSharedComponent()->getAlignment(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getAlignment(); } /** @@ -136,38 +143,36 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells()) - ->applyFromArray($this->getStyleArray($pStyles)); + ->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['horizontal'])) { - $this->setHorizontal($pStyles['horizontal']); + if (isset($styleArray['horizontal'])) { + $this->setHorizontal($styleArray['horizontal']); } - if (isset($pStyles['vertical'])) { - $this->setVertical($pStyles['vertical']); + if (isset($styleArray['vertical'])) { + $this->setVertical($styleArray['vertical']); } - if (isset($pStyles['textRotation'])) { - $this->setTextRotation($pStyles['textRotation']); + if (isset($styleArray['textRotation'])) { + $this->setTextRotation($styleArray['textRotation']); } - if (isset($pStyles['wrapText'])) { - $this->setWrapText($pStyles['wrapText']); + if (isset($styleArray['wrapText'])) { + $this->setWrapText($styleArray['wrapText']); } - if (isset($pStyles['shrinkToFit'])) { - $this->setShrinkToFit($pStyles['shrinkToFit']); + if (isset($styleArray['shrinkToFit'])) { + $this->setShrinkToFit($styleArray['shrinkToFit']); } - if (isset($pStyles['indent'])) { - $this->setIndent($pStyles['indent']); + if (isset($styleArray['indent'])) { + $this->setIndent($styleArray['indent']); } - if (isset($pStyles['readOrder'])) { - $this->setReadOrder($pStyles['readOrder']); + if (isset($styleArray['readOrder'])) { + $this->setReadOrder($styleArray['readOrder']); } } @@ -177,7 +182,7 @@ public function applyFromArray(array $pStyles) /** * Get Horizontal. * - * @return string + * @return null|string */ public function getHorizontal() { @@ -191,21 +196,21 @@ public function getHorizontal() /** * Set Horizontal. * - * @param string $pValue see self::HORIZONTAL_* + * @param string $horizontalAlignment see self::HORIZONTAL_* * * @return $this */ - public function setHorizontal($pValue) + public function setHorizontal(string $horizontalAlignment) { - if ($pValue == '') { - $pValue = self::HORIZONTAL_GENERAL; + if ($horizontalAlignment == '') { + $horizontalAlignment = self::HORIZONTAL_GENERAL; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['horizontal' => $pValue]); + $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->horizontal = $pValue; + $this->horizontal = $horizontalAlignment; } return $this; @@ -214,7 +219,7 @@ public function setHorizontal($pValue) /** * Get Vertical. * - * @return string + * @return null|string */ public function getVertical() { @@ -228,21 +233,21 @@ public function getVertical() /** * Set Vertical. * - * @param string $pValue see self::VERTICAL_* + * @param string $verticalAlignment see self::VERTICAL_* * * @return $this */ - public function setVertical($pValue) + public function setVertical($verticalAlignment) { - if ($pValue == '') { - $pValue = self::VERTICAL_BOTTOM; + if ($verticalAlignment == '') { + $verticalAlignment = self::VERTICAL_BOTTOM; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['vertical' => $pValue]); + $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->vertical = $pValue; + $this->vertical = $verticalAlignment; } return $this; @@ -251,7 +256,7 @@ public function setVertical($pValue) /** * Get TextRotation. * - * @return int + * @return null|int */ public function getTextRotation() { @@ -265,26 +270,24 @@ public function getTextRotation() /** * Set TextRotation. * - * @param int $pValue - * - * @throws PhpSpreadsheetException + * @param int $angleInDegrees * * @return $this */ - public function setTextRotation($pValue) + public function setTextRotation($angleInDegrees) { // Excel2007 value 255 => PhpSpreadsheet value -165 - if ($pValue == 255) { - $pValue = -165; + if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) { + $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET; } // Set rotation - if (($pValue >= -90 && $pValue <= 90) || $pValue == -165) { + if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['textRotation' => $pValue]); + $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->textRotation = $pValue; + $this->textRotation = $angleInDegrees; } } else { throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.'); @@ -310,20 +313,20 @@ public function getWrapText() /** * Set Wrap Text. * - * @param bool $pValue + * @param bool $wrapped * * @return $this */ - public function setWrapText($pValue) + public function setWrapText($wrapped) { - if ($pValue == '') { - $pValue = false; + if ($wrapped == '') { + $wrapped = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['wrapText' => $pValue]); + $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->wrapText = $pValue; + $this->wrapText = $wrapped; } return $this; @@ -346,20 +349,20 @@ public function getShrinkToFit() /** * Set Shrink to fit. * - * @param bool $pValue + * @param bool $shrink * * @return $this */ - public function setShrinkToFit($pValue) + public function setShrinkToFit($shrink) { - if ($pValue == '') { - $pValue = false; + if ($shrink == '') { + $shrink = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['shrinkToFit' => $pValue]); + $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->shrinkToFit = $pValue; + $this->shrinkToFit = $shrink; } return $this; @@ -382,24 +385,27 @@ public function getIndent() /** * Set indent. * - * @param int $pValue + * @param int $indent * * @return $this */ - public function setIndent($pValue) + public function setIndent($indent) { - if ($pValue > 0) { - if ($this->getHorizontal() != self::HORIZONTAL_GENERAL && + if ($indent > 0) { + if ( + $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && - $this->getHorizontal() != self::HORIZONTAL_RIGHT) { - $pValue = 0; // indent not supported + $this->getHorizontal() != self::HORIZONTAL_RIGHT && + $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED + ) { + $indent = 0; // indent not supported } } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['indent' => $pValue]); + $styleArray = $this->getStyleArray(['indent' => $indent]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->indent = $pValue; + $this->indent = $indent; } return $this; @@ -422,20 +428,20 @@ public function getReadOrder() /** * Set read order. * - * @param int $pValue + * @param int $readOrder * * @return $this */ - public function setReadOrder($pValue) + public function setReadOrder($readOrder) { - if ($pValue < 0 || $pValue > 2) { - $pValue = 0; + if ($readOrder < 0 || $readOrder > 2) { + $readOrder = 0; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['readOrder' => $pValue]); + $styleArray = $this->getStyleArray(['readOrder' => $readOrder]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->readOrder = $pValue; + $this->readOrder = $readOrder; } return $this; @@ -463,4 +469,18 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'horizontal', $this->getHorizontal()); + $this->exportArray2($exportedArray, 'indent', $this->getIndent()); + $this->exportArray2($exportedArray, 'readOrder', $this->getReadOrder()); + $this->exportArray2($exportedArray, 'shrinkToFit', $this->getShrinkToFit()); + $this->exportArray2($exportedArray, 'textRotation', $this->getTextRotation()); + $this->exportArray2($exportedArray, 'vertical', $this->getVertical()); + $this->exportArray2($exportedArray, 'wrapText', $this->getWrapText()); + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php index 5fa0cae7..a5ec980a 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php @@ -37,7 +37,7 @@ class Border extends Supervisor protected $color; /** - * @var int + * @var null|int */ public $colorIndex; @@ -47,11 +47,8 @@ class Border extends Supervisor * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param bool $isConditional Flag indicating if this is a conditional style or not - * Leave this value at default unless you understand exactly what - * its ramifications are */ - public function __construct($isSupervisor = false, $isConditional = false) + public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); @@ -69,32 +66,29 @@ public function __construct($isSupervisor = false, $isConditional = false) * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getSharedComponent() { + /** @var Style */ + $parent = $this->parent; + + /** @var Borders $sharedComponent */ + $sharedComponent = $parent->getSharedComponent(); switch ($this->parentPropertyName) { - case 'allBorders': - case 'horizontal': - case 'inside': - case 'outline': - case 'vertical': - throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'); - - break; case 'bottom': - return $this->parent->getSharedComponent()->getBottom(); + return $sharedComponent->getBottom(); case 'diagonal': - return $this->parent->getSharedComponent()->getDiagonal(); + return $sharedComponent->getDiagonal(); case 'left': - return $this->parent->getSharedComponent()->getLeft(); + return $sharedComponent->getLeft(); case 'right': - return $this->parent->getSharedComponent()->getRight(); + return $sharedComponent->getRight(); case 'top': - return $this->parent->getSharedComponent()->getTop(); + return $sharedComponent->getTop(); } + + throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'); } /** @@ -106,7 +100,10 @@ public function getSharedComponent() */ public function getStyleArray($array) { - return $this->parent->getStyleArray([$this->parentPropertyName => $array]); + /** @var Style */ + $parent = $this->parent; + + return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** @@ -123,22 +120,20 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['borderStyle'])) { - $this->setBorderStyle($pStyles['borderStyle']); + if (isset($styleArray['borderStyle'])) { + $this->setBorderStyle($styleArray['borderStyle']); } - if (isset($pStyles['color'])) { - $this->getColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getColor()->applyFromArray($styleArray['color']); } } @@ -162,24 +157,25 @@ public function getBorderStyle() /** * Set Border style. * - * @param bool|string $pValue + * @param bool|string $style * When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * * @return $this */ - public function setBorderStyle($pValue) + public function setBorderStyle($style) { - if (empty($pValue)) { - $pValue = self::BORDER_NONE; - } elseif (is_bool($pValue) && $pValue) { - $pValue = self::BORDER_MEDIUM; + if (empty($style)) { + $style = self::BORDER_NONE; + } elseif (is_bool($style)) { + $style = self::BORDER_MEDIUM; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['borderStyle' => $pValue]); + $styleArray = $this->getStyleArray(['borderStyle' => $style]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->borderStyle = $pValue; + $this->borderStyle = $style; } return $this; @@ -198,16 +194,12 @@ public function getColor() /** * Set Border Color. * - * @param Color $pValue - * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setColor(Color $pValue) + public function setColor(Color $color) { // make sure parameter is a real color and not a supervisor - $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); @@ -236,4 +228,13 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'borderStyle', $this->getBorderStyle()); + $this->exportArray2($exportedArray, 'color', $this->getColor()); + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php index 8f005a99..56a52709 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php @@ -95,21 +95,18 @@ class Borders extends Supervisor * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are - * @param bool $isConditional Flag indicating if this is a conditional style or not - * Leave this value at default unless you understand exactly what - * its ramifications are */ - public function __construct($isSupervisor = false, $isConditional = false) + public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values - $this->left = new Border($isSupervisor, $isConditional); - $this->right = new Border($isSupervisor, $isConditional); - $this->top = new Border($isSupervisor, $isConditional); - $this->bottom = new Border($isSupervisor, $isConditional); - $this->diagonal = new Border($isSupervisor, $isConditional); + $this->left = new Border($isSupervisor); + $this->right = new Border($isSupervisor); + $this->top = new Border($isSupervisor); + $this->bottom = new Border($isSupervisor); + $this->diagonal = new Border($isSupervisor); $this->diagonalDirection = self::DIAGONAL_NONE; // Specially for supervisor @@ -143,7 +140,10 @@ public function __construct($isSupervisor = false, $isConditional = false) */ public function getSharedComponent() { - return $this->parent->getSharedComponent()->getBorders(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getBorders(); } /** @@ -193,40 +193,38 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['left'])) { - $this->getLeft()->applyFromArray($pStyles['left']); + if (isset($styleArray['left'])) { + $this->getLeft()->applyFromArray($styleArray['left']); } - if (isset($pStyles['right'])) { - $this->getRight()->applyFromArray($pStyles['right']); + if (isset($styleArray['right'])) { + $this->getRight()->applyFromArray($styleArray['right']); } - if (isset($pStyles['top'])) { - $this->getTop()->applyFromArray($pStyles['top']); + if (isset($styleArray['top'])) { + $this->getTop()->applyFromArray($styleArray['top']); } - if (isset($pStyles['bottom'])) { - $this->getBottom()->applyFromArray($pStyles['bottom']); + if (isset($styleArray['bottom'])) { + $this->getBottom()->applyFromArray($styleArray['bottom']); } - if (isset($pStyles['diagonal'])) { - $this->getDiagonal()->applyFromArray($pStyles['diagonal']); + if (isset($styleArray['diagonal'])) { + $this->getDiagonal()->applyFromArray($styleArray['diagonal']); } - if (isset($pStyles['diagonalDirection'])) { - $this->setDiagonalDirection($pStyles['diagonalDirection']); + if (isset($styleArray['diagonalDirection'])) { + $this->setDiagonalDirection($styleArray['diagonalDirection']); } - if (isset($pStyles['allBorders'])) { - $this->getLeft()->applyFromArray($pStyles['allBorders']); - $this->getRight()->applyFromArray($pStyles['allBorders']); - $this->getTop()->applyFromArray($pStyles['allBorders']); - $this->getBottom()->applyFromArray($pStyles['allBorders']); + if (isset($styleArray['allBorders'])) { + $this->getLeft()->applyFromArray($styleArray['allBorders']); + $this->getRight()->applyFromArray($styleArray['allBorders']); + $this->getTop()->applyFromArray($styleArray['allBorders']); + $this->getBottom()->applyFromArray($styleArray['allBorders']); } } @@ -286,8 +284,6 @@ public function getDiagonal() /** * Get AllBorders (pseudo-border). Only applies to supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getAllBorders() @@ -302,8 +298,6 @@ public function getAllBorders() /** * Get Outline (pseudo-border). Only applies to supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getOutline() @@ -318,8 +312,6 @@ public function getOutline() /** * Get Inside (pseudo-border). Only applies to supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getInside() @@ -334,8 +326,6 @@ public function getInside() /** * Get Vertical (pseudo-border). Only applies to supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getVertical() @@ -350,8 +340,6 @@ public function getVertical() /** * Get Horizontal (pseudo-border). Only applies to supervisor. * - * @throws PhpSpreadsheetException - * * @return Border */ public function getHorizontal() @@ -380,20 +368,20 @@ public function getDiagonalDirection() /** * Set DiagonalDirection. * - * @param int $pValue see self::DIAGONAL_* + * @param int $direction see self::DIAGONAL_* * * @return $this */ - public function setDiagonalDirection($pValue) + public function setDiagonalDirection($direction) { - if ($pValue == '') { - $pValue = self::DIAGONAL_NONE; + if ($direction == '') { + $direction = self::DIAGONAL_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['diagonalDirection' => $pValue]); + $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->diagonalDirection = $pValue; + $this->diagonalDirection = $direction; } return $this; @@ -420,4 +408,17 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'bottom', $this->getBottom()); + $this->exportArray2($exportedArray, 'diagonal', $this->getDiagonal()); + $this->exportArray2($exportedArray, 'diagonalDirection', $this->getDiagonalDirection()); + $this->exportArray2($exportedArray, 'left', $this->getLeft()); + $this->exportArray2($exportedArray, 'right', $this->getRight()); + $this->exportArray2($exportedArray, 'top', $this->getTop()); + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php index ab22cbe3..9ab0c98f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php @@ -2,8 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Style; -use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; - class Color extends Supervisor { const NAMED_COLORS = [ @@ -28,25 +26,98 @@ class Color extends Supervisor const COLOR_DARKGREEN = 'FF008000'; const COLOR_YELLOW = 'FFFFFF00'; const COLOR_DARKYELLOW = 'FF808000'; + const COLOR_MAGENTA = 'FFFF00FF'; + const COLOR_CYAN = 'FF00FFFF'; + + const NAMED_COLOR_TRANSLATIONS = [ + 'Black' => self::COLOR_BLACK, + 'White' => self::COLOR_WHITE, + 'Red' => self::COLOR_RED, + 'Green' => self::COLOR_GREEN, + 'Blue' => self::COLOR_BLUE, + 'Yellow' => self::COLOR_YELLOW, + 'Magenta' => self::COLOR_MAGENTA, + 'Cyan' => self::COLOR_CYAN, + ]; - /** - * Indexed colors array. - * - * @var array - */ - protected static $indexedColors; + const VALIDATE_ARGB_SIZE = 8; + const VALIDATE_RGB_SIZE = 6; + const VALIDATE_COLOR_6 = '/^[A-F0-9]{6}$/i'; + const VALIDATE_COLOR_8 = '/^[A-F0-9]{8}$/i'; + + private const INDEXED_COLORS = [ + 1 => 'FF000000', // System Colour #1 - Black + 2 => 'FFFFFFFF', // System Colour #2 - White + 3 => 'FFFF0000', // System Colour #3 - Red + 4 => 'FF00FF00', // System Colour #4 - Green + 5 => 'FF0000FF', // System Colour #5 - Blue + 6 => 'FFFFFF00', // System Colour #6 - Yellow + 7 => 'FFFF00FF', // System Colour #7- Magenta + 8 => 'FF00FFFF', // System Colour #8- Cyan + 9 => 'FF800000', // Standard Colour #9 + 10 => 'FF008000', // Standard Colour #10 + 11 => 'FF000080', // Standard Colour #11 + 12 => 'FF808000', // Standard Colour #12 + 13 => 'FF800080', // Standard Colour #13 + 14 => 'FF008080', // Standard Colour #14 + 15 => 'FFC0C0C0', // Standard Colour #15 + 16 => 'FF808080', // Standard Colour #16 + 17 => 'FF9999FF', // Chart Fill Colour #17 + 18 => 'FF993366', // Chart Fill Colour #18 + 19 => 'FFFFFFCC', // Chart Fill Colour #19 + 20 => 'FFCCFFFF', // Chart Fill Colour #20 + 21 => 'FF660066', // Chart Fill Colour #21 + 22 => 'FFFF8080', // Chart Fill Colour #22 + 23 => 'FF0066CC', // Chart Fill Colour #23 + 24 => 'FFCCCCFF', // Chart Fill Colour #24 + 25 => 'FF000080', // Chart Line Colour #25 + 26 => 'FFFF00FF', // Chart Line Colour #26 + 27 => 'FFFFFF00', // Chart Line Colour #27 + 28 => 'FF00FFFF', // Chart Line Colour #28 + 29 => 'FF800080', // Chart Line Colour #29 + 30 => 'FF800000', // Chart Line Colour #30 + 31 => 'FF008080', // Chart Line Colour #31 + 32 => 'FF0000FF', // Chart Line Colour #32 + 33 => 'FF00CCFF', // Standard Colour #33 + 34 => 'FFCCFFFF', // Standard Colour #34 + 35 => 'FFCCFFCC', // Standard Colour #35 + 36 => 'FFFFFF99', // Standard Colour #36 + 37 => 'FF99CCFF', // Standard Colour #37 + 38 => 'FFFF99CC', // Standard Colour #38 + 39 => 'FFCC99FF', // Standard Colour #39 + 40 => 'FFFFCC99', // Standard Colour #40 + 41 => 'FF3366FF', // Standard Colour #41 + 42 => 'FF33CCCC', // Standard Colour #42 + 43 => 'FF99CC00', // Standard Colour #43 + 44 => 'FFFFCC00', // Standard Colour #44 + 45 => 'FFFF9900', // Standard Colour #45 + 46 => 'FFFF6600', // Standard Colour #46 + 47 => 'FF666699', // Standard Colour #47 + 48 => 'FF969696', // Standard Colour #48 + 49 => 'FF003366', // Standard Colour #49 + 50 => 'FF339966', // Standard Colour #50 + 51 => 'FF003300', // Standard Colour #51 + 52 => 'FF333300', // Standard Colour #52 + 53 => 'FF993300', // Standard Colour #53 + 54 => 'FF993366', // Standard Colour #54 + 55 => 'FF333399', // Standard Colour #55 + 56 => 'FF333333', // Standard Colour #56 + ]; /** * ARGB - Alpha RGB. * - * @var string + * @var null|string */ protected $argb; + /** @var bool */ + private $hasChanged = false; + /** * Create a new Color. * - * @param string $pARGB ARGB value for the colour + * @param string $colorValue ARGB value for the colour, or named colour * @param bool $isSupervisor Flag indicating if this is a supervisor or not * Leave this value at default unless you understand exactly what * its ramifications are @@ -54,14 +125,14 @@ class Color extends Supervisor * Leave this value at default unless you understand exactly what * its ramifications are */ - public function __construct($pARGB = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false) + public function __construct($colorValue = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { - $this->argb = $pARGB; + $this->argb = $this->validateColor($colorValue) ?: self::COLOR_BLACK; } } @@ -73,14 +144,19 @@ public function __construct($pARGB = self::COLOR_BLACK, $isSupervisor = false, $ */ public function getSharedComponent() { - switch ($this->parentPropertyName) { - case 'endColor': - return $this->parent->getSharedComponent()->getEndColor(); - case 'color': - return $this->parent->getSharedComponent()->getColor(); - case 'startColor': - return $this->parent->getSharedComponent()->getStartColor(); + /** @var Style */ + $parent = $this->parent; + /** @var Border|Fill $sharedComponent */ + $sharedComponent = $parent->getSharedComponent(); + if ($sharedComponent instanceof Fill) { + if ($this->parentPropertyName === 'endColor') { + return $sharedComponent->getEndColor(); + } + + return $sharedComponent->getStartColor(); } + + return $sharedComponent->getColor(); } /** @@ -92,7 +168,10 @@ public function getSharedComponent() */ public function getStyleArray($array) { - return $this->parent->getStyleArray([$this->parentPropertyName => $array]); + /** @var Style */ + $parent = $this->parent; + + return $parent->getStyleArray([$this->parentPropertyName => $array]); } /** @@ -102,34 +181,49 @@ public function getStyleArray($array) * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['rgb'])) { - $this->setRGB($pStyles['rgb']); + if (isset($styleArray['rgb'])) { + $this->setRGB($styleArray['rgb']); } - if (isset($pStyles['argb'])) { - $this->setARGB($pStyles['argb']); + if (isset($styleArray['argb'])) { + $this->setARGB($styleArray['argb']); } } return $this; } + private function validateColor(?string $colorValue): string + { + if ($colorValue === null || $colorValue === '') { + return self::COLOR_BLACK; + } + $named = ucfirst(strtolower($colorValue)); + if (array_key_exists($named, self::NAMED_COLOR_TRANSLATIONS)) { + return self::NAMED_COLOR_TRANSLATIONS[$named]; + } + if (preg_match(self::VALIDATE_COLOR_8, $colorValue) === 1) { + return $colorValue; + } + if (preg_match(self::VALIDATE_COLOR_6, $colorValue) === 1) { + return 'FF' . $colorValue; + } + + return ''; + } + /** * Get ARGB. - * - * @return string */ - public function getARGB() + public function getARGB(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); @@ -141,20 +235,23 @@ public function getARGB() /** * Set ARGB. * - * @param string $pValue see self::COLOR_* + * @param string $colorValue ARGB value, or a named color * * @return $this */ - public function setARGB($pValue) + public function setARGB(?string $colorValue = self::COLOR_BLACK) { - if ($pValue == '') { - $pValue = self::COLOR_BLACK; + $this->hasChanged = true; + $colorValue = $this->validateColor($colorValue); + if ($colorValue === '') { + return $this; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['argb' => $pValue]); + $styleArray = $this->getStyleArray(['argb' => $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->argb = $pValue; + $this->argb = $colorValue; } return $this; @@ -162,114 +259,109 @@ public function setARGB($pValue) /** * Get RGB. - * - * @return string */ - public function getRGB() + public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } - return substr($this->argb, 2); + return substr($this->argb ?? '', 2); } /** * Set RGB. * - * @param string $pValue RGB value + * @param string $colorValue RGB value, or a named color * * @return $this */ - public function setRGB($pValue) + public function setRGB(?string $colorValue = self::COLOR_BLACK) { - if ($pValue == '') { - $pValue = '000000'; - } - if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['argb' => 'FF' . $pValue]); - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); - } else { - $this->argb = 'FF' . $pValue; - } - - return $this; + return $this->setARGB($colorValue); } /** * Get a specified colour component of an RGB value. * - * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param int $offset Position within the RGB value to extract * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The extracted colour component + * @return int|string The extracted colour component */ - private static function getColourComponent($RGB, $offset, $hex = true) + private static function getColourComponent($rgbValue, $offset, $hex = true) { - $colour = substr($RGB, $offset, 2); + $colour = substr($rgbValue, $offset, 2) ?: ''; + if (preg_match('/^[0-9a-f]{2}$/i', $colour) !== 1) { + $colour = '00'; + } - return ($hex) ? $colour : hexdec($colour); + return ($hex) ? $colour : (int) hexdec($colour); } /** * Get the red colour component of an RGB value. * - * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The red colour component + * @return int|string The red colour component */ - public static function getRed($RGB, $hex = true) + public static function getRed($rgbValue, $hex = true) { - return self::getColourComponent($RGB, strlen($RGB) - 6, $hex); + return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex); } /** * Get the green colour component of an RGB value. * - * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The green colour component + * @return int|string The green colour component */ - public static function getGreen($RGB, $hex = true) + public static function getGreen($rgbValue, $hex = true) { - return self::getColourComponent($RGB, strlen($RGB) - 4, $hex); + return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex); } /** * Get the blue colour component of an RGB value. * - * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE * @param bool $hex Flag indicating whether the component should be returned as a hex or a * decimal value * - * @return string The blue colour component + * @return int|string The blue colour component */ - public static function getBlue($RGB, $hex = true) + public static function getBlue($rgbValue, $hex = true) { - return self::getColourComponent($RGB, strlen($RGB) - 2, $hex); + return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex); } /** * Adjust the brightness of a color. * - * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) + * @param string $hexColourValue The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1 * * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) */ - public static function changeBrightness($hex, $adjustPercentage) + public static function changeBrightness($hexColourValue, $adjustPercentage) { - $rgba = (strlen($hex) === 8); - - $red = self::getRed($hex, false); - $green = self::getGreen($hex, false); - $blue = self::getBlue($hex, false); + $rgba = (strlen($hexColourValue) === 8); + $adjustPercentage = max(-1.0, min(1.0, $adjustPercentage)); + + /** @var int $red */ + $red = self::getRed($hexColourValue, false); + /** @var int $green */ + $green = self::getGreen($hexColourValue, false); + /** @var int $blue */ + $blue = self::getBlue($hexColourValue, false); if ($adjustPercentage > 0) { $red += (255 - $red) * $adjustPercentage; $green += (255 - $green) * $adjustPercentage; @@ -280,22 +372,6 @@ public static function changeBrightness($hex, $adjustPercentage) $blue += $blue * $adjustPercentage; } - if ($red < 0) { - $red = 0; - } elseif ($red > 255) { - $red = 255; - } - if ($green < 0) { - $green = 0; - } elseif ($green > 255) { - $green = 255; - } - if ($blue < 0) { - $blue = 0; - } elseif ($blue > 255) { - $blue = 255; - } - $rgb = strtoupper( str_pad(dechex((int) $red), 2, '0', 0) . str_pad(dechex((int) $green), 2, '0', 0) . @@ -308,88 +384,28 @@ public static function changeBrightness($hex, $adjustPercentage) /** * Get indexed color. * - * @param int $pIndex Index entry point into the colour array + * @param int $colorIndex Index entry point into the colour array * @param bool $background Flag to indicate whether default background or foreground colour * should be returned if the indexed colour doesn't exist * - * @return self + * @return Color */ - public static function indexedColor($pIndex, $background = false) + public static function indexedColor($colorIndex, $background = false, ?array $palette = null): self { // Clean parameter - $pIndex = (int) $pIndex; - - // Indexed colors - if (self::$indexedColors === null) { - self::$indexedColors = [ - 1 => 'FF000000', // System Colour #1 - Black - 2 => 'FFFFFFFF', // System Colour #2 - White - 3 => 'FFFF0000', // System Colour #3 - Red - 4 => 'FF00FF00', // System Colour #4 - Green - 5 => 'FF0000FF', // System Colour #5 - Blue - 6 => 'FFFFFF00', // System Colour #6 - Yellow - 7 => 'FFFF00FF', // System Colour #7- Magenta - 8 => 'FF00FFFF', // System Colour #8- Cyan - 9 => 'FF800000', // Standard Colour #9 - 10 => 'FF008000', // Standard Colour #10 - 11 => 'FF000080', // Standard Colour #11 - 12 => 'FF808000', // Standard Colour #12 - 13 => 'FF800080', // Standard Colour #13 - 14 => 'FF008080', // Standard Colour #14 - 15 => 'FFC0C0C0', // Standard Colour #15 - 16 => 'FF808080', // Standard Colour #16 - 17 => 'FF9999FF', // Chart Fill Colour #17 - 18 => 'FF993366', // Chart Fill Colour #18 - 19 => 'FFFFFFCC', // Chart Fill Colour #19 - 20 => 'FFCCFFFF', // Chart Fill Colour #20 - 21 => 'FF660066', // Chart Fill Colour #21 - 22 => 'FFFF8080', // Chart Fill Colour #22 - 23 => 'FF0066CC', // Chart Fill Colour #23 - 24 => 'FFCCCCFF', // Chart Fill Colour #24 - 25 => 'FF000080', // Chart Line Colour #25 - 26 => 'FFFF00FF', // Chart Line Colour #26 - 27 => 'FFFFFF00', // Chart Line Colour #27 - 28 => 'FF00FFFF', // Chart Line Colour #28 - 29 => 'FF800080', // Chart Line Colour #29 - 30 => 'FF800000', // Chart Line Colour #30 - 31 => 'FF008080', // Chart Line Colour #31 - 32 => 'FF0000FF', // Chart Line Colour #32 - 33 => 'FF00CCFF', // Standard Colour #33 - 34 => 'FFCCFFFF', // Standard Colour #34 - 35 => 'FFCCFFCC', // Standard Colour #35 - 36 => 'FFFFFF99', // Standard Colour #36 - 37 => 'FF99CCFF', // Standard Colour #37 - 38 => 'FFFF99CC', // Standard Colour #38 - 39 => 'FFCC99FF', // Standard Colour #39 - 40 => 'FFFFCC99', // Standard Colour #40 - 41 => 'FF3366FF', // Standard Colour #41 - 42 => 'FF33CCCC', // Standard Colour #42 - 43 => 'FF99CC00', // Standard Colour #43 - 44 => 'FFFFCC00', // Standard Colour #44 - 45 => 'FFFF9900', // Standard Colour #45 - 46 => 'FFFF6600', // Standard Colour #46 - 47 => 'FF666699', // Standard Colour #47 - 48 => 'FF969696', // Standard Colour #48 - 49 => 'FF003366', // Standard Colour #49 - 50 => 'FF339966', // Standard Colour #50 - 51 => 'FF003300', // Standard Colour #51 - 52 => 'FF333300', // Standard Colour #52 - 53 => 'FF993300', // Standard Colour #53 - 54 => 'FF993366', // Standard Colour #54 - 55 => 'FF333399', // Standard Colour #55 - 56 => 'FF333333', // Standard Colour #56 - ]; - } - - if (isset(self::$indexedColors[$pIndex])) { - return new self(self::$indexedColors[$pIndex]); - } + $colorIndex = (int) $colorIndex; - if ($background) { - return new self(self::COLOR_WHITE); + if (empty($palette)) { + if (isset(self::INDEXED_COLORS[$colorIndex])) { + return new self(self::INDEXED_COLORS[$colorIndex]); + } + } else { + if (isset($palette[$colorIndex])) { + return new self($palette[$colorIndex]); + } } - return new self(self::COLOR_BLACK); + return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK); } /** @@ -397,7 +413,7 @@ public static function indexedColor($pIndex, $background = false) * * @return string Hash code */ - public function getHashCode() + public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); @@ -408,4 +424,21 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'argb', $this->getARGB()); + + return $exportedArray; + } + + public function getHasChanged(): bool + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->hasChanged; + } + + return $this->hasChanged; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php index ec8c858b..019c0648 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php @@ -3,16 +3,44 @@ namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\IComparable; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; class Conditional implements IComparable { // Condition types const CONDITION_NONE = 'none'; + const CONDITION_BEGINSWITH = 'beginsWith'; const CONDITION_CELLIS = 'cellIs'; + const CONDITION_CONTAINSBLANKS = 'containsBlanks'; + const CONDITION_CONTAINSERRORS = 'containsErrors'; const CONDITION_CONTAINSTEXT = 'containsText'; + const CONDITION_DATABAR = 'dataBar'; + const CONDITION_ENDSWITH = 'endsWith'; const CONDITION_EXPRESSION = 'expression'; - const CONDITION_CONTAINSBLANKS = 'containsBlanks'; const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks'; + const CONDITION_NOTCONTAINSERRORS = 'notContainsErrors'; + const CONDITION_NOTCONTAINSTEXT = 'notContainsText'; + const CONDITION_TIMEPERIOD = 'timePeriod'; + const CONDITION_DUPLICATES = 'duplicateValues'; + const CONDITION_UNIQUE = 'uniqueValues'; + + private const CONDITION_TYPES = [ + self::CONDITION_BEGINSWITH, + self::CONDITION_CELLIS, + self::CONDITION_CONTAINSBLANKS, + self::CONDITION_CONTAINSERRORS, + self::CONDITION_CONTAINSTEXT, + self::CONDITION_DATABAR, + self::CONDITION_DUPLICATES, + self::CONDITION_ENDSWITH, + self::CONDITION_EXPRESSION, + self::CONDITION_NONE, + self::CONDITION_NOTCONTAINSBLANKS, + self::CONDITION_NOTCONTAINSERRORS, + self::CONDITION_NOTCONTAINSTEXT, + self::CONDITION_TIMEPERIOD, + self::CONDITION_UNIQUE, + ]; // Operator types const OPERATOR_NONE = ''; @@ -27,6 +55,18 @@ class Conditional implements IComparable const OPERATOR_CONTAINSTEXT = 'containsText'; const OPERATOR_NOTCONTAINS = 'notContains'; const OPERATOR_BETWEEN = 'between'; + const OPERATOR_NOTBETWEEN = 'notBetween'; + + const TIMEPERIOD_TODAY = 'today'; + const TIMEPERIOD_YESTERDAY = 'yesterday'; + const TIMEPERIOD_TOMORROW = 'tomorrow'; + const TIMEPERIOD_LAST_7_DAYS = 'last7Days'; + const TIMEPERIOD_LAST_WEEK = 'lastWeek'; + const TIMEPERIOD_THIS_WEEK = 'thisWeek'; + const TIMEPERIOD_NEXT_WEEK = 'nextWeek'; + const TIMEPERIOD_LAST_MONTH = 'lastMonth'; + const TIMEPERIOD_THIS_MONTH = 'thisMonth'; + const TIMEPERIOD_NEXT_MONTH = 'nextMonth'; /** * Condition type. @@ -59,10 +99,15 @@ class Conditional implements IComparable /** * Condition. * - * @var string[] + * @var (bool|float|int|string)[] */ private $condition = []; + /** + * @var ConditionalDataBar + */ + private $dataBar; + /** * Style. * @@ -92,13 +137,13 @@ public function getConditionType() /** * Set Condition type. * - * @param string $pValue Condition type, see self::CONDITION_* + * @param string $type Condition type, see self::CONDITION_* * * @return $this */ - public function setConditionType($pValue) + public function setConditionType($type) { - $this->conditionType = $pValue; + $this->conditionType = $type; return $this; } @@ -116,13 +161,13 @@ public function getOperatorType() /** * Set Operator type. * - * @param string $pValue Conditional operator type, see self::OPERATOR_* + * @param string $type Conditional operator type, see self::OPERATOR_* * * @return $this */ - public function setOperatorType($pValue) + public function setOperatorType($type) { - $this->operatorType = $pValue; + $this->operatorType = $type; return $this; } @@ -140,13 +185,13 @@ public function getText() /** * Set text. * - * @param string $value + * @param string $text * * @return $this */ - public function setText($value) + public function setText($text) { - $this->text = $value; + $this->text = $text; return $this; } @@ -164,13 +209,13 @@ public function getStopIfTrue() /** * Set StopIfTrue. * - * @param bool $value + * @param bool $stopIfTrue * * @return $this */ - public function setStopIfTrue($value) + public function setStopIfTrue($stopIfTrue) { - $this->stopIfTrue = $value; + $this->stopIfTrue = $stopIfTrue; return $this; } @@ -178,7 +223,7 @@ public function setStopIfTrue($value) /** * Get Conditions. * - * @return string[] + * @return (bool|float|int|string)[] */ public function getConditions() { @@ -188,16 +233,16 @@ public function getConditions() /** * Set Conditions. * - * @param string[] $pValue Condition + * @param bool|float|int|string|(bool|float|int|string)[] $conditions Condition * * @return $this */ - public function setConditions($pValue) + public function setConditions($conditions) { - if (!is_array($pValue)) { - $pValue = [$pValue]; + if (!is_array($conditions)) { + $conditions = [$conditions]; } - $this->condition = $pValue; + $this->condition = $conditions; return $this; } @@ -205,13 +250,13 @@ public function setConditions($pValue) /** * Add Condition. * - * @param string $pValue Condition + * @param bool|float|int|string $condition Condition * * @return $this */ - public function addCondition($pValue) + public function addCondition($condition) { - $this->condition[] = $pValue; + $this->condition[] = $condition; return $this; } @@ -229,13 +274,33 @@ public function getStyle() /** * Set Style. * - * @param Style $pValue + * @return $this + */ + public function setStyle(Style $style) + { + $this->style = $style; + + return $this; + } + + /** + * get DataBar. + * + * @return null|ConditionalDataBar + */ + public function getDataBar() + { + return $this->dataBar; + } + + /** + * set DataBar. * * @return $this */ - public function setStyle(Style $pValue = null) + public function setDataBar(ConditionalDataBar $dataBar) { - $this->style = $pValue; + $this->dataBar = $dataBar; return $this; } @@ -270,4 +335,12 @@ public function __clone() } } } + + /** + * Verify if param is valid condition type. + */ + public static function isValidConditionType(string $type): bool + { + return in_array($type, self::CONDITION_TYPES); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php new file mode 100644 index 00000000..7d520120 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php @@ -0,0 +1,312 @@ + '=', + Conditional::OPERATOR_GREATERTHAN => '>', + Conditional::OPERATOR_GREATERTHANOREQUAL => '>=', + Conditional::OPERATOR_LESSTHAN => '<', + Conditional::OPERATOR_LESSTHANOREQUAL => '<=', + Conditional::OPERATOR_NOTEQUAL => '<>', + ]; + + public const COMPARISON_RANGE_OPERATORS = [ + Conditional::OPERATOR_BETWEEN => 'IF(AND(A1>=%s,A1<=%s),TRUE,FALSE)', + Conditional::OPERATOR_NOTBETWEEN => 'IF(AND(A1>=%s,A1<=%s),FALSE,TRUE)', + ]; + + public const COMPARISON_DUPLICATES_OPERATORS = [ + Conditional::CONDITION_DUPLICATES => "COUNTIF('%s'!%s,%s)>1", + Conditional::CONDITION_UNIQUE => "COUNTIF('%s'!%s,%s)=1", + ]; + + /** + * @var Cell + */ + protected $cell; + + /** + * @var int + */ + protected $cellRow; + + /** + * @var Worksheet + */ + protected $worksheet; + + /** + * @var int + */ + protected $cellColumn; + + /** + * @var string + */ + protected $conditionalRange; + + /** + * @var string + */ + protected $referenceCell; + + /** + * @var int + */ + protected $referenceRow; + + /** + * @var int + */ + protected $referenceColumn; + + /** + * @var Calculation + */ + protected $engine; + + public function __construct(Cell $cell, string $conditionalRange) + { + $this->cell = $cell; + $this->worksheet = $cell->getWorksheet(); + [$this->cellColumn, $this->cellRow] = Coordinate::indexesFromString($this->cell->getCoordinate()); + $this->setReferenceCellForExpressions($conditionalRange); + + $this->engine = Calculation::getInstance($this->worksheet->getParent()); + } + + protected function setReferenceCellForExpressions(string $conditionalRange): void + { + $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); + [$this->referenceCell] = $conditionalRange[0]; + + [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); + + // Convert our conditional range to an absolute conditional range, so it can be used "pinned" in formulae + $rangeSets = []; + foreach ($conditionalRange as $rangeSet) { + $absoluteRangeSet = array_map( + [Coordinate::class, 'absoluteCoordinate'], + $rangeSet + ); + $rangeSets[] = implode(':', $absoluteRangeSet); + } + $this->conditionalRange = implode(',', $rangeSets); + } + + public function evaluateConditional(Conditional $conditional): bool + { + // Some calculations may modify the stored cell; so reset it before every evaluation. + $cellColumn = Coordinate::stringFromColumnIndex($this->cellColumn); + $cellAddress = "{$cellColumn}{$this->cellRow}"; + $this->cell = $this->worksheet->getCell($cellAddress); + + switch ($conditional->getConditionType()) { + case Conditional::CONDITION_CELLIS: + return $this->processOperatorComparison($conditional); + case Conditional::CONDITION_DUPLICATES: + case Conditional::CONDITION_UNIQUE: + return $this->processDuplicatesComparison($conditional); + case Conditional::CONDITION_CONTAINSTEXT: + // Expression is NOT(ISERROR(SEARCH("",))) + case Conditional::CONDITION_NOTCONTAINSTEXT: + // Expression is ISERROR(SEARCH("",)) + case Conditional::CONDITION_BEGINSWITH: + // Expression is LEFT(,LEN(""))="" + case Conditional::CONDITION_ENDSWITH: + // Expression is RIGHT(,LEN(""))="" + case Conditional::CONDITION_CONTAINSBLANKS: + // Expression is LEN(TRIM())=0 + case Conditional::CONDITION_NOTCONTAINSBLANKS: + // Expression is LEN(TRIM())>0 + case Conditional::CONDITION_CONTAINSERRORS: + // Expression is ISERROR() + case Conditional::CONDITION_NOTCONTAINSERRORS: + // Expression is NOT(ISERROR()) + case Conditional::CONDITION_TIMEPERIOD: + // Expression varies, depending on specified timePeriod value, e.g. + // Yesterday FLOOR(,1)=TODAY()-1 + // Today FLOOR(,1)=TODAY() + // Tomorrow FLOOR(,1)=TODAY()+1 + // Last 7 Days AND(TODAY()-FLOOR(,1)<=6,FLOOR(,1)<=TODAY()) + case Conditional::CONDITION_EXPRESSION: + return $this->processExpression($conditional); + } + + return false; + } + + /** + * @param mixed $value + * + * @return float|int|string + */ + protected function wrapValue($value) + { + if (!is_numeric($value)) { + if (is_bool($value)) { + return $value ? 'TRUE' : 'FALSE'; + } elseif ($value === null) { + return 'NULL'; + } + + return '"' . $value . '"'; + } + + return $value; + } + + /** + * @return float|int|string + */ + protected function wrapCellValue() + { + return $this->wrapValue($this->cell->getCalculatedValue()); + } + + /** + * @return float|int|string + */ + protected function conditionCellAdjustment(array $matches) + { + $column = $matches[6]; + $row = $matches[7]; + + if (strpos($column, '$') === false) { + $column = Coordinate::columnIndexFromString($column); + $column += $this->cellColumn - $this->referenceColumn; + $column = Coordinate::stringFromColumnIndex($column); + } + + if (strpos($row, '$') === false) { + $row += $this->cellRow - $this->referenceRow; + } + + if (!empty($matches[4])) { + $worksheet = $this->worksheet->getParent()->getSheetByName(trim($matches[4], "'")); + if ($worksheet === null) { + return $this->wrapValue(null); + } + + return $this->wrapValue( + $worksheet + ->getCell(str_replace('$', '', "{$column}{$row}")) + ->getCalculatedValue() + ); + } + + return $this->wrapValue( + $this->worksheet + ->getCell(str_replace('$', '', "{$column}{$row}")) + ->getCalculatedValue() + ); + } + + protected function cellConditionCheck(string $condition): string + { + $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); + $i = false; + foreach ($splitCondition as &$value) { + // Only count/replace in alternating array entries (ie. not in quoted strings) + if ($i = !$i) { + $value = preg_replace_callback( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', + [$this, 'conditionCellAdjustment'], + $value + ); + } + } + unset($value); + // Then rebuild the condition string to return it + return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); + } + + protected function adjustConditionsForCellReferences(array $conditions): array + { + return array_map( + [$this, 'cellConditionCheck'], + $conditions + ); + } + + protected function processOperatorComparison(Conditional $conditional): bool + { + if (array_key_exists($conditional->getOperatorType(), self::COMPARISON_RANGE_OPERATORS)) { + return $this->processRangeOperator($conditional); + } + + $operator = self::COMPARISON_OPERATORS[$conditional->getOperatorType()]; + $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); + $expression = sprintf('%s%s%s', (string) $this->wrapCellValue(), $operator, (string) array_pop($conditions)); + + return $this->evaluateExpression($expression); + } + + protected function processRangeOperator(Conditional $conditional): bool + { + $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); + sort($conditions); + $expression = sprintf( + (string) preg_replace( + '/\bA1\b/i', + (string) $this->wrapCellValue(), + self::COMPARISON_RANGE_OPERATORS[$conditional->getOperatorType()] + ), + ...$conditions + ); + + return $this->evaluateExpression($expression); + } + + protected function processDuplicatesComparison(Conditional $conditional): bool + { + $worksheetName = $this->cell->getWorksheet()->getTitle(); + + $expression = sprintf( + self::COMPARISON_DUPLICATES_OPERATORS[$conditional->getConditionType()], + $worksheetName, + $this->conditionalRange, + $this->cellConditionCheck($this->cell->getCalculatedValue()) + ); + + return $this->evaluateExpression($expression); + } + + protected function processExpression(Conditional $conditional): bool + { + $conditions = $this->adjustConditionsForCellReferences($conditional->getConditions()); + $expression = array_pop($conditions); + + $expression = preg_replace( + '/\b' . $this->referenceCell . '\b/i', + (string) $this->wrapCellValue(), + $expression + ); + + return $this->evaluateExpression($expression); + } + + protected function evaluateExpression(string $expression): bool + { + $expression = "={$expression}"; + + try { + $this->engine->flushInstance(); + $result = (bool) $this->engine->calculateFormula($expression); + } catch (Exception $e) { + return false; + } + + return $result; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php new file mode 100644 index 00000000..4c000db3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php @@ -0,0 +1,45 @@ +cellMatcher = new CellMatcher($cell, $conditionalRange); + $this->styleMerger = new StyleMerger($cell->getStyle()); + } + + /** + * @param Conditional[] $conditionalStyles + */ + public function matchConditions(array $conditionalStyles = []): Style + { + foreach ($conditionalStyles as $conditional) { + /** @var Conditional $conditional */ + if ($this->cellMatcher->evaluateConditional($conditional) === true) { + // Merging the conditional style into the base style goes in here + $this->styleMerger->mergeStyle($conditional->getStyle()); + if ($conditional->getStopIfTrue() === true) { + break; + } + } + } + + return $this->styleMerger->getStyle(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php new file mode 100644 index 00000000..54513670 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php @@ -0,0 +1,102 @@ + attribute */ + + /** @var null|bool */ + private $showValue; + + /** children */ + + /** @var ConditionalFormatValueObject */ + private $minimumConditionalFormatValueObject; + + /** @var ConditionalFormatValueObject */ + private $maximumConditionalFormatValueObject; + + /** @var string */ + private $color; + + /** */ + + /** @var ConditionalFormattingRuleExtension */ + private $conditionalFormattingRuleExt; + + /** + * @return null|bool + */ + public function getShowValue() + { + return $this->showValue; + } + + /** + * @param bool $showValue + */ + public function setShowValue($showValue) + { + $this->showValue = $showValue; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMinimumConditionalFormatValueObject() + { + return $this->minimumConditionalFormatValueObject; + } + + public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject) + { + $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMaximumConditionalFormatValueObject() + { + return $this->maximumConditionalFormatValueObject; + } + + public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject) + { + $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; + + return $this; + } + + public function getColor(): string + { + return $this->color; + } + + public function setColor(string $color): self + { + $this->color = $color; + + return $this; + } + + /** + * @return ConditionalFormattingRuleExtension + */ + public function getConditionalFormattingRuleExt() + { + return $this->conditionalFormattingRuleExt; + } + + public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt) + { + $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php new file mode 100644 index 00000000..c709cf3e --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php @@ -0,0 +1,290 @@ + attributes */ + + /** @var int */ + private $minLength; + + /** @var int */ + private $maxLength; + + /** @var null|bool */ + private $border; + + /** @var null|bool */ + private $gradient; + + /** @var string */ + private $direction; + + /** @var null|bool */ + private $negativeBarBorderColorSameAsPositive; + + /** @var string */ + private $axisPosition; + + // children + + /** @var ConditionalFormatValueObject */ + private $maximumConditionalFormatValueObject; + + /** @var ConditionalFormatValueObject */ + private $minimumConditionalFormatValueObject; + + /** @var string */ + private $borderColor; + + /** @var string */ + private $negativeFillColor; + + /** @var string */ + private $negativeBorderColor; + + /** @var array */ + private $axisColor = [ + 'rgb' => null, + 'theme' => null, + 'tint' => null, + ]; + + public function getXmlAttributes() + { + $ret = []; + foreach (['minLength', 'maxLength', 'direction', 'axisPosition'] as $attrKey) { + if (null !== $this->{$attrKey}) { + $ret[$attrKey] = $this->{$attrKey}; + } + } + foreach (['border', 'gradient', 'negativeBarBorderColorSameAsPositive'] as $attrKey) { + if (null !== $this->{$attrKey}) { + $ret[$attrKey] = $this->{$attrKey} ? '1' : '0'; + } + } + + return $ret; + } + + public function getXmlElements() + { + $ret = []; + $elms = ['borderColor', 'negativeFillColor', 'negativeBorderColor']; + foreach ($elms as $elmKey) { + if (null !== $this->{$elmKey}) { + $ret[$elmKey] = ['rgb' => $this->{$elmKey}]; + } + } + foreach (array_filter($this->axisColor) as $attrKey => $axisColorAttr) { + if (!isset($ret['axisColor'])) { + $ret['axisColor'] = []; + } + $ret['axisColor'][$attrKey] = $axisColorAttr; + } + + return $ret; + } + + /** + * @return int + */ + public function getMinLength() + { + return $this->minLength; + } + + public function setMinLength(int $minLength): self + { + $this->minLength = $minLength; + + return $this; + } + + /** + * @return int + */ + public function getMaxLength() + { + return $this->maxLength; + } + + public function setMaxLength(int $maxLength): self + { + $this->maxLength = $maxLength; + + return $this; + } + + /** + * @return null|bool + */ + public function getBorder() + { + return $this->border; + } + + public function setBorder(bool $border): self + { + $this->border = $border; + + return $this; + } + + /** + * @return null|bool + */ + public function getGradient() + { + return $this->gradient; + } + + public function setGradient(bool $gradient): self + { + $this->gradient = $gradient; + + return $this; + } + + /** + * @return string + */ + public function getDirection() + { + return $this->direction; + } + + public function setDirection(string $direction): self + { + $this->direction = $direction; + + return $this; + } + + /** + * @return null|bool + */ + public function getNegativeBarBorderColorSameAsPositive() + { + return $this->negativeBarBorderColorSameAsPositive; + } + + public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self + { + $this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive; + + return $this; + } + + /** + * @return string + */ + public function getAxisPosition() + { + return $this->axisPosition; + } + + public function setAxisPosition(string $axisPosition): self + { + $this->axisPosition = $axisPosition; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMaximumConditionalFormatValueObject() + { + return $this->maximumConditionalFormatValueObject; + } + + public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject) + { + $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; + + return $this; + } + + /** + * @return ConditionalFormatValueObject + */ + public function getMinimumConditionalFormatValueObject() + { + return $this->minimumConditionalFormatValueObject; + } + + public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject) + { + $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; + + return $this; + } + + /** + * @return string + */ + public function getBorderColor() + { + return $this->borderColor; + } + + public function setBorderColor(string $borderColor): self + { + $this->borderColor = $borderColor; + + return $this; + } + + /** + * @return string + */ + public function getNegativeFillColor() + { + return $this->negativeFillColor; + } + + public function setNegativeFillColor(string $negativeFillColor): self + { + $this->negativeFillColor = $negativeFillColor; + + return $this; + } + + /** + * @return string + */ + public function getNegativeBorderColor() + { + return $this->negativeBorderColor; + } + + public function setNegativeBorderColor(string $negativeBorderColor): self + { + $this->negativeBorderColor = $negativeBorderColor; + + return $this; + } + + public function getAxisColor(): array + { + return $this->axisColor; + } + + /** + * @param mixed $rgb + * @param null|mixed $theme + * @param null|mixed $tint + */ + public function setAxisColor($rgb, $theme = null, $tint = null): self + { + $this->axisColor = [ + 'rgb' => $rgb, + 'theme' => $theme, + 'tint' => $tint, + ]; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php new file mode 100644 index 00000000..107969bf --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php @@ -0,0 +1,78 @@ +type = $type; + $this->value = $value; + $this->cellFormula = $cellFormula; + } + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param mixed $type + */ + public function setType($type) + { + $this->type = $type; + + return $this; + } + + /** + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * @param mixed $value + */ + public function setValue($value) + { + $this->value = $value; + + return $this; + } + + /** + * @return mixed + */ + public function getCellFormula() + { + return $this->cellFormula; + } + + /** + * @param mixed $cellFormula + */ + public function setCellFormula($cellFormula) + { + $this->cellFormula = $cellFormula; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php new file mode 100644 index 00000000..d8ef990c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php @@ -0,0 +1,208 @@ + attributes */ + private $id; + + /** @var string Conditional Formatting Rule */ + private $cfRule; + + /** children */ + + /** @var ConditionalDataBarExtension */ + private $dataBar; + + /** @var string Sequence of References */ + private $sqref; + + /** + * ConditionalFormattingRuleExtension constructor. + */ + public function __construct($id = null, string $cfRule = self::CONDITION_EXTENSION_DATABAR) + { + if (null === $id) { + $this->id = '{' . $this->generateUuid() . '}'; + } else { + $this->id = $id; + } + $this->cfRule = $cfRule; + } + + private function generateUuid() + { + $chars = str_split('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'); + + foreach ($chars as $i => $char) { + if ($char === 'x') { + $chars[$i] = dechex(random_int(0, 15)); + } elseif ($char === 'y') { + $chars[$i] = dechex(random_int(8, 11)); + } + } + + return implode('', $chars); + } + + public static function parseExtLstXml($extLstXml) + { + $conditionalFormattingRuleExtensions = []; + $conditionalFormattingRuleExtensionXml = null; + if ($extLstXml instanceof SimpleXMLElement) { + foreach ((count($extLstXml) > 0 ? $extLstXml : [$extLstXml]) as $extLst) { + //this uri is conditionalFormattings + //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 + if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { + $conditionalFormattingRuleExtensionXml = $extLst->ext; + } + } + + if ($conditionalFormattingRuleExtensionXml) { + $ns = $conditionalFormattingRuleExtensionXml->getNamespaces(true); + $extFormattingsXml = $conditionalFormattingRuleExtensionXml->children($ns['x14']); + + foreach ($extFormattingsXml->children($ns['x14']) as $extFormattingXml) { + $extCfRuleXml = $extFormattingXml->cfRule; + $attributes = $extCfRuleXml->attributes(); + if (!$attributes || ((string) $attributes->type) !== Conditional::CONDITION_DATABAR) { + continue; + } + + $extFormattingRuleObj = new self((string) $attributes->id); + $extFormattingRuleObj->setSqref((string) $extFormattingXml->children($ns['xm'])->sqref); + $conditionalFormattingRuleExtensions[$extFormattingRuleObj->getId()] = $extFormattingRuleObj; + + $extDataBarObj = new ConditionalDataBarExtension(); + $extFormattingRuleObj->setDataBarExt($extDataBarObj); + $dataBarXml = $extCfRuleXml->dataBar; + self::parseExtDataBarAttributesFromXml($extDataBarObj, $dataBarXml); + self::parseExtDataBarElementChildrenFromXml($extDataBarObj, $dataBarXml, $ns); + } + } + } + + return $conditionalFormattingRuleExtensions; + } + + private static function parseExtDataBarAttributesFromXml( + ConditionalDataBarExtension $extDataBarObj, + SimpleXMLElement $dataBarXml + ): void { + $dataBarAttribute = $dataBarXml->attributes(); + if ($dataBarAttribute->minLength) { + $extDataBarObj->setMinLength((int) $dataBarAttribute->minLength); + } + if ($dataBarAttribute->maxLength) { + $extDataBarObj->setMaxLength((int) $dataBarAttribute->maxLength); + } + if ($dataBarAttribute->border) { + $extDataBarObj->setBorder((bool) (string) $dataBarAttribute->border); + } + if ($dataBarAttribute->gradient) { + $extDataBarObj->setGradient((bool) (string) $dataBarAttribute->gradient); + } + if ($dataBarAttribute->direction) { + $extDataBarObj->setDirection((string) $dataBarAttribute->direction); + } + if ($dataBarAttribute->negativeBarBorderColorSameAsPositive) { + $extDataBarObj->setNegativeBarBorderColorSameAsPositive((bool) (string) $dataBarAttribute->negativeBarBorderColorSameAsPositive); + } + if ($dataBarAttribute->axisPosition) { + $extDataBarObj->setAxisPosition((string) $dataBarAttribute->axisPosition); + } + } + + private static function parseExtDataBarElementChildrenFromXml(ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml, $ns): void + { + if ($dataBarXml->borderColor) { + $extDataBarObj->setBorderColor((string) $dataBarXml->borderColor->attributes()['rgb']); + } + if ($dataBarXml->negativeFillColor) { + $extDataBarObj->setNegativeFillColor((string) $dataBarXml->negativeFillColor->attributes()['rgb']); + } + if ($dataBarXml->negativeBorderColor) { + $extDataBarObj->setNegativeBorderColor((string) $dataBarXml->negativeBorderColor->attributes()['rgb']); + } + if ($dataBarXml->axisColor) { + $axisColorAttr = $dataBarXml->axisColor->attributes(); + $extDataBarObj->setAxisColor((string) $axisColorAttr['rgb'], (string) $axisColorAttr['theme'], (string) $axisColorAttr['tint']); + } + $cfvoIndex = 0; + foreach ($dataBarXml->cfvo as $cfvo) { + $f = (string) $cfvo->children($ns['xm'])->f; + $attributes = $cfvo->attributes(); + if (!($attributes)) { + continue; + } + + if ($cfvoIndex === 0) { + $extDataBarObj->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); + } + if ($cfvoIndex === 1) { + $extDataBarObj->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); + } + ++$cfvoIndex; + } + } + + /** + * @return mixed + */ + public function getId() + { + return $this->id; + } + + /** + * @param mixed $id + */ + public function setId($id): self + { + $this->id = $id; + + return $this; + } + + public function getCfRule(): string + { + return $this->cfRule; + } + + public function setCfRule(string $cfRule): self + { + $this->cfRule = $cfRule; + + return $this; + } + + public function getDataBarExt(): ConditionalDataBarExtension + { + return $this->dataBar; + } + + public function setDataBarExt(ConditionalDataBarExtension $dataBar): self + { + $this->dataBar = $dataBar; + + return $this; + } + + public function getSqref(): string + { + return $this->sqref; + } + + public function setSqref(string $sqref): self + { + $this->sqref = $sqref; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php new file mode 100644 index 00000000..95e6dfd8 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php @@ -0,0 +1,118 @@ +baseStyle = $baseStyle; + } + + public function getStyle(): Style + { + return $this->baseStyle; + } + + public function mergeStyle(Style $style): void + { + if ($style->getNumberFormat() !== null && $style->getNumberFormat()->getFormatCode() !== null) { + $this->baseStyle->getNumberFormat()->setFormatCode($style->getNumberFormat()->getFormatCode()); + } + + if ($style->getFont() !== null) { + $this->mergeFontStyle($this->baseStyle->getFont(), $style->getFont()); + } + + if ($style->getFill() !== null) { + $this->mergeFillStyle($this->baseStyle->getFill(), $style->getFill()); + } + + if ($style->getBorders() !== null) { + $this->mergeBordersStyle($this->baseStyle->getBorders(), $style->getBorders()); + } + } + + protected function mergeFontStyle(Font $baseFontStyle, Font $fontStyle): void + { + if ($fontStyle->getBold() !== null) { + $baseFontStyle->setBold($fontStyle->getBold()); + } + + if ($fontStyle->getItalic() !== null) { + $baseFontStyle->setItalic($fontStyle->getItalic()); + } + + if ($fontStyle->getStrikethrough() !== null) { + $baseFontStyle->setStrikethrough($fontStyle->getStrikethrough()); + } + + if ($fontStyle->getUnderline() !== null) { + $baseFontStyle->setUnderline($fontStyle->getUnderline()); + } + + if ($fontStyle->getColor() !== null && $fontStyle->getColor()->getARGB() !== null) { + $baseFontStyle->setColor($fontStyle->getColor()); + } + } + + protected function mergeFillStyle(Fill $baseFillStyle, Fill $fillStyle): void + { + if ($fillStyle->getFillType() !== null) { + $baseFillStyle->setFillType($fillStyle->getFillType()); + } + + if ($fillStyle->getRotation() !== null) { + $baseFillStyle->setRotation($fillStyle->getRotation()); + } + + if ($fillStyle->getStartColor() !== null && $fillStyle->getStartColor()->getARGB() !== null) { + $baseFillStyle->setStartColor($fillStyle->getStartColor()); + } + + if ($fillStyle->getEndColor() !== null && $fillStyle->getEndColor()->getARGB() !== null) { + $baseFillStyle->setEndColor($fillStyle->getEndColor()); + } + } + + protected function mergeBordersStyle(Borders $baseBordersStyle, Borders $bordersStyle): void + { + if ($bordersStyle->getTop() !== null) { + $this->mergeBorderStyle($baseBordersStyle->getTop(), $bordersStyle->getTop()); + } + + if ($bordersStyle->getBottom() !== null) { + $this->mergeBorderStyle($baseBordersStyle->getBottom(), $bordersStyle->getBottom()); + } + + if ($bordersStyle->getLeft() !== null) { + $this->mergeBorderStyle($baseBordersStyle->getLeft(), $bordersStyle->getLeft()); + } + + if ($bordersStyle->getRight() !== null) { + $this->mergeBorderStyle($baseBordersStyle->getRight(), $bordersStyle->getRight()); + } + } + + protected function mergeBorderStyle(Border $baseBorderStyle, Border $borderStyle): void + { + if ($borderStyle->getBorderStyle() !== null) { + $baseBorderStyle->setBorderStyle($borderStyle->getBorderStyle()); + } + + if ($borderStyle->getColor() !== null && $borderStyle->getColor()->getARGB() !== null) { + $baseBorderStyle->setColor($borderStyle->getColor()); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php new file mode 100644 index 00000000..d5d56a9a --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php @@ -0,0 +1,95 @@ +cellRange = $cellRange; + } + + public function newRule(string $ruleType): WizardInterface + { + switch ($ruleType) { + case self::CELL_VALUE: + return new Wizard\CellValue($this->cellRange); + case self::TEXT_VALUE: + return new Wizard\TextValue($this->cellRange); + case self::BLANKS: + return new Wizard\Blanks($this->cellRange, true); + case self::NOT_BLANKS: + return new Wizard\Blanks($this->cellRange, false); + case self::ERRORS: + return new Wizard\Errors($this->cellRange, true); + case self::NOT_ERRORS: + return new Wizard\Errors($this->cellRange, false); + case self::EXPRESSION: + case self::FORMULA: + return new Wizard\Expression($this->cellRange); + case self::DATES_OCCURRING: + return new Wizard\DateValue($this->cellRange); + case self::DUPLICATES: + return new Wizard\Duplicates($this->cellRange, false); + case self::UNIQUE: + return new Wizard\Duplicates($this->cellRange, true); + default: + throw new Exception('No wizard exists for this CF rule type'); + } + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + $conditionalType = $conditional->getConditionType(); + + switch ($conditionalType) { + case Conditional::CONDITION_CELLIS: + return Wizard\CellValue::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_CONTAINSTEXT: + case Conditional::CONDITION_NOTCONTAINSTEXT: + case Conditional::CONDITION_BEGINSWITH: + case Conditional::CONDITION_ENDSWITH: + return Wizard\TextValue::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_CONTAINSBLANKS: + case Conditional::CONDITION_NOTCONTAINSBLANKS: + return Wizard\Blanks::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_CONTAINSERRORS: + case Conditional::CONDITION_NOTCONTAINSERRORS: + return Wizard\Errors::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_TIMEPERIOD: + return Wizard\DateValue::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_EXPRESSION: + return Wizard\Expression::fromConditional($conditional, $cellRange); + case Conditional::CONDITION_DUPLICATES: + case Conditional::CONDITION_UNIQUE: + return Wizard\Duplicates::fromConditional($conditional, $cellRange); + default: + throw new Exception('No wizard exists for this CF rule type'); + } + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php new file mode 100644 index 00000000..14f30d39 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php @@ -0,0 +1,99 @@ + false, + 'isBlank' => true, + 'notEmpty' => false, + 'empty' => true, + ]; + + protected const EXPRESSIONS = [ + Wizard::NOT_BLANKS => 'LEN(TRIM(%s))>0', + Wizard::BLANKS => 'LEN(TRIM(%s))=0', + ]; + + /** + * @var bool + */ + protected $inverse; + + public function __construct(string $cellRange, bool $inverse = false) + { + parent::__construct($cellRange); + $this->inverse = $inverse; + } + + protected function inverse(bool $inverse): void + { + $this->inverse = $inverse; + } + + protected function getExpression(): void + { + $this->expression = sprintf( + self::EXPRESSIONS[$this->inverse ? Wizard::BLANKS : Wizard::NOT_BLANKS], + $this->referenceCell + ); + } + + public function getConditional(): Conditional + { + $this->getExpression(); + + $conditional = new Conditional(); + $conditional->setConditionType( + $this->inverse ? Conditional::CONDITION_CONTAINSBLANKS : Conditional::CONDITION_NOTCONTAINSBLANKS + ); + $conditional->setConditions([$this->expression]); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ( + $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSBLANKS && + $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSBLANKS + ) { + throw new Exception('Conditional is not a Blanks CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSBLANKS; + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!array_key_exists($methodName, self::OPERATORS)) { + throw new Exception('Invalid Operation for Blanks CF Rule Wizard'); + } + + $this->inverse(self::OPERATORS[$methodName]); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php new file mode 100644 index 00000000..f36033dd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php @@ -0,0 +1,189 @@ + Conditional::OPERATOR_EQUAL, + 'notEquals' => Conditional::OPERATOR_NOTEQUAL, + 'greaterThan' => Conditional::OPERATOR_GREATERTHAN, + 'greaterThanOrEqual' => Conditional::OPERATOR_GREATERTHANOREQUAL, + 'lessThan' => Conditional::OPERATOR_LESSTHAN, + 'lessThanOrEqual' => Conditional::OPERATOR_LESSTHANOREQUAL, + 'between' => Conditional::OPERATOR_BETWEEN, + 'notBetween' => Conditional::OPERATOR_NOTBETWEEN, + ]; + + protected const SINGLE_OPERATORS = CellMatcher::COMPARISON_OPERATORS; + + protected const RANGE_OPERATORS = CellMatcher::COMPARISON_RANGE_OPERATORS; + + /** @var string */ + protected $operator = Conditional::OPERATOR_EQUAL; + + /** @var array */ + protected $operand = [0]; + + /** + * @var string[] + */ + protected $operandValueType = []; + + public function __construct(string $cellRange) + { + parent::__construct($cellRange); + } + + protected function operator(string $operator): void + { + if ((!isset(self::SINGLE_OPERATORS[$operator])) && (!isset(self::RANGE_OPERATORS[$operator]))) { + throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); + } + + $this->operator = $operator; + } + + /** + * @param mixed $operand + */ + protected function operand(int $index, $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void + { + if (is_string($operand)) { + $operand = $this->validateOperand($operand, $operandValueType); + } + + $this->operand[$index] = $operand; + $this->operandValueType[$index] = $operandValueType; + } + + /** + * @param mixed $value + * + * @return float|int|string + */ + protected function wrapValue($value, string $operandValueType) + { + if (!is_numeric($value) && !is_bool($value) && null !== $value) { + if ($operandValueType === Wizard::VALUE_TYPE_LITERAL) { + return '"' . str_replace('"', '""', $value) . '"'; + } + + return $this->cellConditionCheck($value); + } + + if (null === $value) { + $value = 'NULL'; + } elseif (is_bool($value)) { + $value = $value ? 'TRUE' : 'FALSE'; + } + + return $value; + } + + public function getConditional(): Conditional + { + if (!isset(self::RANGE_OPERATORS[$this->operator])) { + unset($this->operand[1], $this->operandValueType[1]); + } + $values = array_map([$this, 'wrapValue'], $this->operand, $this->operandValueType); + + $conditional = new Conditional(); + $conditional->setConditionType(Conditional::CONDITION_CELLIS); + $conditional->setOperatorType($this->operator); + $conditional->setConditions($values); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + protected static function unwrapString(string $condition): string + { + if ((strpos($condition, '"') === 0) && (strpos(strrev($condition), '"') === 0)) { + $condition = substr($condition, 1, -1); + } + + return str_replace('""', '"', $condition); + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ($conditional->getConditionType() !== Conditional::CONDITION_CELLIS) { + throw new Exception('Conditional is not a Cell Value CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + + $wizard->operator = $conditional->getOperatorType(); + $conditions = $conditional->getConditions(); + foreach ($conditions as $index => $condition) { + // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? + $operandValueType = Wizard::VALUE_TYPE_LITERAL; + if (is_string($condition)) { + if (array_key_exists($condition, Calculation::$excelConstants)) { + $condition = Calculation::$excelConstants[$condition]; + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { + $operandValueType = Wizard::VALUE_TYPE_CELL; + $condition = self::reverseAdjustCellRef($condition, $cellRange); + } elseif ( + preg_match('/\(\)/', $condition) || + preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) + ) { + $operandValueType = Wizard::VALUE_TYPE_FORMULA; + $condition = self::reverseAdjustCellRef($condition, $cellRange); + } else { + $condition = self::unwrapString($condition); + } + } + $wizard->operand($index, $condition, $operandValueType); + } + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!isset(self::MAGIC_OPERATIONS[$methodName]) && $methodName !== 'and') { + throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); + } + + if ($methodName === 'and') { + if (!isset(self::RANGE_OPERATORS[$this->operator])) { + throw new Exception('AND Value is only appropriate for range operators'); + } + + $this->operand(1, ...$arguments); + + return $this; + } + + $this->operator(self::MAGIC_OPERATIONS[$methodName]); + $this->operand(0, ...$arguments); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php new file mode 100644 index 00000000..453dcdf9 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php @@ -0,0 +1,111 @@ + Conditional::TIMEPERIOD_YESTERDAY, + 'today' => Conditional::TIMEPERIOD_TODAY, + 'tomorrow' => Conditional::TIMEPERIOD_TOMORROW, + 'lastSevenDays' => Conditional::TIMEPERIOD_LAST_7_DAYS, + 'last7Days' => Conditional::TIMEPERIOD_LAST_7_DAYS, + 'lastWeek' => Conditional::TIMEPERIOD_LAST_WEEK, + 'thisWeek' => Conditional::TIMEPERIOD_THIS_WEEK, + 'nextWeek' => Conditional::TIMEPERIOD_NEXT_WEEK, + 'lastMonth' => Conditional::TIMEPERIOD_LAST_MONTH, + 'thisMonth' => Conditional::TIMEPERIOD_THIS_MONTH, + 'nextMonth' => Conditional::TIMEPERIOD_NEXT_MONTH, + ]; + + protected const EXPRESSIONS = [ + Conditional::TIMEPERIOD_YESTERDAY => 'FLOOR(%s,1)=TODAY()-1', + Conditional::TIMEPERIOD_TODAY => 'FLOOR(%s,1)=TODAY()', + Conditional::TIMEPERIOD_TOMORROW => 'FLOOR(%s,1)=TODAY()+1', + Conditional::TIMEPERIOD_LAST_7_DAYS => 'AND(TODAY()-FLOOR(%s,1)<=6,FLOOR(%s,1)<=TODAY())', + Conditional::TIMEPERIOD_LAST_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(%s,0)<(WEEKDAY(TODAY())+7))', + Conditional::TIMEPERIOD_THIS_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(%s,0)-TODAY()<=7-WEEKDAY(TODAY()))', + Conditional::TIMEPERIOD_NEXT_WEEK => 'AND(ROUNDDOWN(%s,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(%s,0)-TODAY()<(15-WEEKDAY(TODAY())))', + Conditional::TIMEPERIOD_LAST_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0-1)),YEAR(%s)=YEAR(EDATE(TODAY(),0-1)))', + Conditional::TIMEPERIOD_THIS_MONTH => 'AND(MONTH(%s)=MONTH(TODAY()),YEAR(%s)=YEAR(TODAY()))', + Conditional::TIMEPERIOD_NEXT_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0+1)),YEAR(%s)=YEAR(EDATE(TODAY(),0+1)))', + ]; + + /** @var string */ + protected $operator; + + public function __construct(string $cellRange) + { + parent::__construct($cellRange); + } + + protected function operator(string $operator): void + { + $this->operator = $operator; + } + + protected function setExpression(): void + { + $referenceCount = substr_count(self::EXPRESSIONS[$this->operator], '%s'); + $references = array_fill(0, $referenceCount, $this->referenceCell); + $this->expression = sprintf(self::EXPRESSIONS[$this->operator], ...$references); + } + + public function getConditional(): Conditional + { + $this->setExpression(); + + $conditional = new Conditional(); + $conditional->setConditionType(Conditional::CONDITION_TIMEPERIOD); + $conditional->setText($this->operator); + $conditional->setConditions([$this->expression]); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ($conditional->getConditionType() !== Conditional::CONDITION_TIMEPERIOD) { + throw new Exception('Conditional is not a Date Value CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + $wizard->operator = $conditional->getText(); + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!isset(self::MAGIC_OPERATIONS[$methodName])) { + throw new Exception('Invalid Operation for Date Value CF Rule Wizard'); + } + + $this->operator(self::MAGIC_OPERATIONS[$methodName]); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php new file mode 100644 index 00000000..3f063fef --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php @@ -0,0 +1,78 @@ + false, + 'unique' => true, + ]; + + /** + * @var bool + */ + protected $inverse; + + public function __construct(string $cellRange, bool $inverse = false) + { + parent::__construct($cellRange); + $this->inverse = $inverse; + } + + protected function inverse(bool $inverse): void + { + $this->inverse = $inverse; + } + + public function getConditional(): Conditional + { + $conditional = new Conditional(); + $conditional->setConditionType( + $this->inverse ? Conditional::CONDITION_UNIQUE : Conditional::CONDITION_DUPLICATES + ); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ( + $conditional->getConditionType() !== Conditional::CONDITION_DUPLICATES && + $conditional->getConditionType() !== Conditional::CONDITION_UNIQUE + ) { + throw new Exception('Conditional is not a Duplicates CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_UNIQUE; + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!array_key_exists($methodName, self::OPERATORS)) { + throw new Exception('Invalid Operation for Errors CF Rule Wizard'); + } + + $this->inverse(self::OPERATORS[$methodName]); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php new file mode 100644 index 00000000..56b9086c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php @@ -0,0 +1,95 @@ + false, + 'isError' => true, + ]; + + protected const EXPRESSIONS = [ + Wizard::NOT_ERRORS => 'NOT(ISERROR(%s))', + Wizard::ERRORS => 'ISERROR(%s)', + ]; + + /** + * @var bool + */ + protected $inverse; + + public function __construct(string $cellRange, bool $inverse = false) + { + parent::__construct($cellRange); + $this->inverse = $inverse; + } + + protected function inverse(bool $inverse): void + { + $this->inverse = $inverse; + } + + protected function getExpression(): void + { + $this->expression = sprintf( + self::EXPRESSIONS[$this->inverse ? Wizard::ERRORS : Wizard::NOT_ERRORS], + $this->referenceCell + ); + } + + public function getConditional(): Conditional + { + $this->getExpression(); + + $conditional = new Conditional(); + $conditional->setConditionType( + $this->inverse ? Conditional::CONDITION_CONTAINSERRORS : Conditional::CONDITION_NOTCONTAINSERRORS + ); + $conditional->setConditions([$this->expression]); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ( + $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSERRORS && + $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSERRORS + ) { + throw new Exception('Conditional is not an Errors CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSERRORS; + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!array_key_exists($methodName, self::OPERATORS)) { + throw new Exception('Invalid Operation for Errors CF Rule Wizard'); + } + + $this->inverse(self::OPERATORS[$methodName]); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php new file mode 100644 index 00000000..ee71e34b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php @@ -0,0 +1,73 @@ +validateOperand($expression, Wizard::VALUE_TYPE_FORMULA); + $this->expression = $expression; + + return $this; + } + + public function getConditional(): Conditional + { + $expression = $this->adjustConditionsForCellReferences([$this->expression]); + + $conditional = new Conditional(); + $conditional->setConditionType(Conditional::CONDITION_EXPRESSION); + $conditional->setConditions($expression); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if ($conditional->getConditionType() !== Conditional::CONDITION_EXPRESSION) { + throw new Exception('Conditional is not an Expression CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + $wizard->expression = self::reverseAdjustCellRef((string) ($conditional->getConditions()[0]), $cellRange); + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if ($methodName !== 'formula') { + throw new Exception('Invalid Operation for Expression CF Rule Wizard'); + } + + $this->expression(...$arguments); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php new file mode 100644 index 00000000..4fa635be --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php @@ -0,0 +1,163 @@ + Conditional::OPERATOR_CONTAINSTEXT, + 'doesntContain' => Conditional::OPERATOR_NOTCONTAINS, + 'doesNotContain' => Conditional::OPERATOR_NOTCONTAINS, + 'beginsWith' => Conditional::OPERATOR_BEGINSWITH, + 'startsWith' => Conditional::OPERATOR_BEGINSWITH, + 'endsWith' => Conditional::OPERATOR_ENDSWITH, + ]; + + protected const OPERATORS = [ + Conditional::OPERATOR_CONTAINSTEXT => Conditional::CONDITION_CONTAINSTEXT, + Conditional::OPERATOR_NOTCONTAINS => Conditional::CONDITION_NOTCONTAINSTEXT, + Conditional::OPERATOR_BEGINSWITH => Conditional::CONDITION_BEGINSWITH, + Conditional::OPERATOR_ENDSWITH => Conditional::CONDITION_ENDSWITH, + ]; + + protected const EXPRESSIONS = [ + Conditional::OPERATOR_CONTAINSTEXT => 'NOT(ISERROR(SEARCH(%s,%s)))', + Conditional::OPERATOR_NOTCONTAINS => 'ISERROR(SEARCH(%s,%s))', + Conditional::OPERATOR_BEGINSWITH => 'LEFT(%s,LEN(%s))=%s', + Conditional::OPERATOR_ENDSWITH => 'RIGHT(%s,LEN(%s))=%s', + ]; + + /** @var string */ + protected $operator; + + /** @var string */ + protected $operand; + + /** + * @var string + */ + protected $operandValueType; + + public function __construct(string $cellRange) + { + parent::__construct($cellRange); + } + + protected function operator(string $operator): void + { + if (!isset(self::OPERATORS[$operator])) { + throw new Exception('Invalid Operator for Text Value CF Rule Wizard'); + } + + $this->operator = $operator; + } + + protected function operand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void + { + if (is_string($operand)) { + $operand = $this->validateOperand($operand, $operandValueType); + } + + $this->operand = $operand; + $this->operandValueType = $operandValueType; + } + + protected function wrapValue(string $value): string + { + return '"' . $value . '"'; + } + + protected function setExpression(): void + { + $operand = $this->operandValueType === Wizard::VALUE_TYPE_LITERAL + ? $this->wrapValue(str_replace('"', '""', $this->operand)) + : $this->cellConditionCheck($this->operand); + + if ( + $this->operator === Conditional::OPERATOR_CONTAINSTEXT || + $this->operator === Conditional::OPERATOR_NOTCONTAINS + ) { + $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $operand, $this->referenceCell); + } else { + $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $this->referenceCell, $operand, $operand); + } + } + + public function getConditional(): Conditional + { + $this->setExpression(); + + $conditional = new Conditional(); + $conditional->setConditionType(self::OPERATORS[$this->operator]); + $conditional->setOperatorType($this->operator); + $conditional->setText( + $this->operandValueType !== Wizard::VALUE_TYPE_LITERAL + ? $this->cellConditionCheck($this->operand) + : $this->operand + ); + $conditional->setConditions([$this->expression]); + $conditional->setStyle($this->getStyle()); + $conditional->setStopIfTrue($this->getStopIfTrue()); + + return $conditional; + } + + public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface + { + if (!in_array($conditional->getConditionType(), self::OPERATORS, true)) { + throw new Exception('Conditional is not a Text Value CF Rule conditional'); + } + + $wizard = new self($cellRange); + $wizard->operator = (string) array_search($conditional->getConditionType(), self::OPERATORS, true); + $wizard->style = $conditional->getStyle(); + $wizard->stopIfTrue = $conditional->getStopIfTrue(); + + // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? + $wizard->operandValueType = Wizard::VALUE_TYPE_LITERAL; + $condition = $conditional->getText(); + if (is_string($condition) && array_key_exists($condition, Calculation::$excelConstants)) { + $condition = Calculation::$excelConstants[$condition]; + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { + $wizard->operandValueType = Wizard::VALUE_TYPE_CELL; + $condition = self::reverseAdjustCellRef($condition, $cellRange); + } elseif ( + preg_match('/\(\)/', $condition) || + preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) + ) { + $wizard->operandValueType = Wizard::VALUE_TYPE_FORMULA; + } + $wizard->operand = $condition; + + return $wizard; + } + + /** + * @param string $methodName + * @param mixed[] $arguments + */ + public function __call($methodName, $arguments): self + { + if (!isset(self::MAGIC_OPERATIONS[$methodName])) { + throw new Exception('Invalid Operation for Text Value CF Rule Wizard'); + } + + $this->operator(self::MAGIC_OPERATIONS[$methodName]); + $this->operand(...$arguments); + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php new file mode 100644 index 00000000..df9daab3 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php @@ -0,0 +1,197 @@ +setCellRange($cellRange); + } + + public function getCellRange(): string + { + return $this->cellRange; + } + + public function setCellRange(string $cellRange): void + { + $this->cellRange = $cellRange; + $this->setReferenceCellForExpressions($cellRange); + } + + protected function setReferenceCellForExpressions(string $conditionalRange): void + { + $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); + [$this->referenceCell] = $conditionalRange[0]; + + [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); + } + + public function getStopIfTrue(): bool + { + return $this->stopIfTrue; + } + + public function setStopIfTrue(bool $stopIfTrue): void + { + $this->stopIfTrue = $stopIfTrue; + } + + public function getStyle(): Style + { + return $this->style ?? new Style(false, true); + } + + public function setStyle(Style $style): void + { + $this->style = $style; + } + + protected function validateOperand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): string + { + if ( + $operandValueType === Wizard::VALUE_TYPE_LITERAL && + substr($operand, 0, 1) === '"' && + substr($operand, -1) === '"' + ) { + $operand = str_replace('""', '"', substr($operand, 1, -1)); + } elseif ($operandValueType === Wizard::VALUE_TYPE_FORMULA && substr($operand, 0, 1) === '=') { + $operand = substr($operand, 1); + } + + return $operand; + } + + protected static function reverseCellAdjustment(array $matches, int $referenceColumn, int $referenceRow): string + { + $worksheet = $matches[1]; + $column = $matches[6]; + $row = $matches[7]; + + if (strpos($column, '$') === false) { + $column = Coordinate::columnIndexFromString($column); + $column -= $referenceColumn - 1; + $column = Coordinate::stringFromColumnIndex($column); + } + + if (strpos($row, '$') === false) { + $row -= $referenceRow - 1; + } + + return "{$worksheet}{$column}{$row}"; + } + + public static function reverseAdjustCellRef(string $condition, string $cellRange): string + { + $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellRange))); + [$referenceCell] = $conditionalRange[0]; + [$referenceColumnIndex, $referenceRow] = Coordinate::indexesFromString($referenceCell); + + $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); + $i = false; + foreach ($splitCondition as &$value) { + // Only count/replace in alternating array entries (ie. not in quoted strings) + if ($i = !$i) { + $value = preg_replace_callback( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', + function ($matches) use ($referenceColumnIndex, $referenceRow) { + return self::reverseCellAdjustment($matches, $referenceColumnIndex, $referenceRow); + }, + $value + ); + } + } + unset($value); + + // Then rebuild the condition string to return it + return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); + } + + protected function conditionCellAdjustment(array $matches): string + { + $worksheet = $matches[1]; + $column = $matches[6]; + $row = $matches[7]; + + if (strpos($column, '$') === false) { + $column = Coordinate::columnIndexFromString($column); + $column += $this->referenceColumn - 1; + $column = Coordinate::stringFromColumnIndex($column); + } + + if (strpos($row, '$') === false) { + $row += $this->referenceRow - 1; + } + + return "{$worksheet}{$column}{$row}"; + } + + protected function cellConditionCheck(string $condition): string + { + $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); + $i = false; + foreach ($splitCondition as &$value) { + // Only count/replace in alternating array entries (ie. not in quoted strings) + if ($i = !$i) { + $value = preg_replace_callback( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', + [$this, 'conditionCellAdjustment'], + $value + ); + } + } + unset($value); + + // Then rebuild the condition string to return it + return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); + } + + protected function adjustConditionsForCellReferences(array $conditions): array + { + return array_map( + [$this, 'cellConditionCheck'], + $conditions + ); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php new file mode 100644 index 00000000..10ad57b2 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php @@ -0,0 +1,25 @@ +parent->getSharedComponent()->getFill(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getFill(); } /** @@ -126,7 +130,7 @@ public function getStyleArray($array) * $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( * [ * 'fillType' => Fill::FILL_GRADIENT_LINEAR, - * 'rotation' => 0, + * 'rotation' => 0.0, * 'startColor' => [ * 'rgb' => '000000' * ], @@ -137,32 +141,30 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['fillType'])) { - $this->setFillType($pStyles['fillType']); + if (isset($styleArray['fillType'])) { + $this->setFillType($styleArray['fillType']); } - if (isset($pStyles['rotation'])) { - $this->setRotation($pStyles['rotation']); + if (isset($styleArray['rotation'])) { + $this->setRotation($styleArray['rotation']); } - if (isset($pStyles['startColor'])) { - $this->getStartColor()->applyFromArray($pStyles['startColor']); + if (isset($styleArray['startColor'])) { + $this->getStartColor()->applyFromArray($styleArray['startColor']); } - if (isset($pStyles['endColor'])) { - $this->getEndColor()->applyFromArray($pStyles['endColor']); + if (isset($styleArray['endColor'])) { + $this->getEndColor()->applyFromArray($styleArray['endColor']); } - if (isset($pStyles['color'])) { - $this->getStartColor()->applyFromArray($pStyles['color']); - $this->getEndColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getStartColor()->applyFromArray($styleArray['color']); + $this->getEndColor()->applyFromArray($styleArray['color']); } } @@ -172,7 +174,7 @@ public function applyFromArray(array $pStyles) /** * Get Fill Type. * - * @return string + * @return null|string */ public function getFillType() { @@ -186,17 +188,17 @@ public function getFillType() /** * Set Fill Type. * - * @param string $pValue Fill type, see self::FILL_* + * @param string $fillType Fill type, see self::FILL_* * * @return $this */ - public function setFillType($pValue) + public function setFillType($fillType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['fillType' => $pValue]); + $styleArray = $this->getStyleArray(['fillType' => $fillType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->fillType = $pValue; + $this->fillType = $fillType; } return $this; @@ -219,17 +221,17 @@ public function getRotation() /** * Set Rotation. * - * @param float $pValue + * @param float $angleInDegrees * * @return $this */ - public function setRotation($pValue) + public function setRotation($angleInDegrees) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['rotation' => $pValue]); + $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->rotation = $pValue; + $this->rotation = $angleInDegrees; } return $this; @@ -248,16 +250,13 @@ public function getStartColor() /** * Set Start Color. * - * @param Color $pValue - * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setStartColor(Color $pValue) + public function setStartColor(Color $color) { + $this->colorChanged = true; // make sure parameter is a real color and not a supervisor - $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); @@ -282,16 +281,13 @@ public function getEndColor() /** * Set End Color. * - * @param Color $pValue - * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setEndColor(Color $pValue) + public function setEndColor(Color $color) { + $this->colorChanged = true; // make sure parameter is a real color and not a supervisor - $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); @@ -303,6 +299,17 @@ public function setEndColor(Color $pValue) return $this; } + public function getColorsChanged(): bool + { + if ($this->isSupervisor) { + $changed = $this->getSharedComponent()->colorChanged; + } else { + $changed = $this->colorChanged; + } + + return $changed || $this->startColor->getHasChanged() || $this->endColor->getHasChanged(); + } + /** * Get hash code. * @@ -320,7 +327,21 @@ public function getHashCode() $this->getRotation() . ($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '') . ($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '') . + ((string) $this->getColorsChanged()) . __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'fillType', $this->getFillType()); + $this->exportArray2($exportedArray, 'rotation', $this->getRotation()); + if ($this->getColorsChanged()) { + $this->exportArray2($exportedArray, 'endColor', $this->getEndColor()); + $this->exportArray2($exportedArray, 'startColor', $this->getStartColor()); + } + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php index 0341cad0..13fe2b67 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php @@ -2,8 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Style; -use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; - class Font extends Supervisor { // Underline types @@ -16,56 +14,56 @@ class Font extends Supervisor /** * Font Name. * - * @var string + * @var null|string */ protected $name = 'Calibri'; /** * Font Size. * - * @var float + * @var null|float */ protected $size = 11; /** * Bold. * - * @var bool + * @var null|bool */ protected $bold = false; /** * Italic. * - * @var bool + * @var null|bool */ protected $italic = false; /** * Superscript. * - * @var bool + * @var null|bool */ protected $superscript = false; /** * Subscript. * - * @var bool + * @var null|bool */ protected $subscript = false; /** * Underline. * - * @var string + * @var null|string */ protected $underline = self::UNDERLINE_NONE; /** * Strikethrough. * - * @var bool + * @var null|bool */ protected $strikethrough = false; @@ -77,7 +75,7 @@ class Font extends Supervisor protected $color; /** - * @var int + * @var null|int */ public $colorIndex; @@ -124,7 +122,10 @@ public function __construct($isSupervisor = false, $isConditional = false) */ public function getSharedComponent() { - return $this->parent->getSharedComponent()->getFont(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getFont(); } /** @@ -157,43 +158,41 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['name'])) { - $this->setName($pStyles['name']); + if (isset($styleArray['name'])) { + $this->setName($styleArray['name']); } - if (isset($pStyles['bold'])) { - $this->setBold($pStyles['bold']); + if (isset($styleArray['bold'])) { + $this->setBold($styleArray['bold']); } - if (isset($pStyles['italic'])) { - $this->setItalic($pStyles['italic']); + if (isset($styleArray['italic'])) { + $this->setItalic($styleArray['italic']); } - if (isset($pStyles['superscript'])) { - $this->setSuperscript($pStyles['superscript']); + if (isset($styleArray['superscript'])) { + $this->setSuperscript($styleArray['superscript']); } - if (isset($pStyles['subscript'])) { - $this->setSubscript($pStyles['subscript']); + if (isset($styleArray['subscript'])) { + $this->setSubscript($styleArray['subscript']); } - if (isset($pStyles['underline'])) { - $this->setUnderline($pStyles['underline']); + if (isset($styleArray['underline'])) { + $this->setUnderline($styleArray['underline']); } - if (isset($pStyles['strikethrough'])) { - $this->setStrikethrough($pStyles['strikethrough']); + if (isset($styleArray['strikethrough'])) { + $this->setStrikethrough($styleArray['strikethrough']); } - if (isset($pStyles['color'])) { - $this->getColor()->applyFromArray($pStyles['color']); + if (isset($styleArray['color'])) { + $this->getColor()->applyFromArray($styleArray['color']); } - if (isset($pStyles['size'])) { - $this->setSize($pStyles['size']); + if (isset($styleArray['size'])) { + $this->setSize($styleArray['size']); } } @@ -203,7 +202,7 @@ public function applyFromArray(array $pStyles) /** * Get Name. * - * @return string + * @return null|string */ public function getName() { @@ -217,20 +216,20 @@ public function getName() /** * Set Name. * - * @param string $pValue + * @param string $fontname * * @return $this */ - public function setName($pValue) + public function setName($fontname) { - if ($pValue == '') { - $pValue = 'Calibri'; + if ($fontname == '') { + $fontname = 'Calibri'; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['name' => $pValue]); + $styleArray = $this->getStyleArray(['name' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->name = $pValue; + $this->name = $fontname; } return $this; @@ -239,7 +238,7 @@ public function setName($pValue) /** * Get Size. * - * @return float + * @return null|float */ public function getSize() { @@ -253,20 +252,27 @@ public function getSize() /** * Set Size. * - * @param float $pValue + * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch) * * @return $this */ - public function setSize($pValue) + public function setSize($sizeInPoints) { - if ($pValue == '') { - $pValue = 10; + if (is_string($sizeInPoints) || is_int($sizeInPoints)) { + $sizeInPoints = (float) $sizeInPoints; // $pValue = 0 if given string is not numeric + } + + // Size must be a positive floating point number + // ECMA-376-1:2016, part 1, chapter 18.4.11 sz (Font Size), p. 1536 + if (!is_float($sizeInPoints) || !($sizeInPoints > 0)) { + $sizeInPoints = 10.0; } + if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['size' => $pValue]); + $styleArray = $this->getStyleArray(['size' => $sizeInPoints]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->size = $pValue; + $this->size = $sizeInPoints; } return $this; @@ -275,7 +281,7 @@ public function setSize($pValue) /** * Get Bold. * - * @return bool + * @return null|bool */ public function getBold() { @@ -289,20 +295,20 @@ public function getBold() /** * Set Bold. * - * @param bool $pValue + * @param bool $bold * * @return $this */ - public function setBold($pValue) + public function setBold($bold) { - if ($pValue == '') { - $pValue = false; + if ($bold == '') { + $bold = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['bold' => $pValue]); + $styleArray = $this->getStyleArray(['bold' => $bold]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->bold = $pValue; + $this->bold = $bold; } return $this; @@ -311,7 +317,7 @@ public function setBold($pValue) /** * Get Italic. * - * @return bool + * @return null|bool */ public function getItalic() { @@ -325,20 +331,20 @@ public function getItalic() /** * Set Italic. * - * @param bool $pValue + * @param bool $italic * * @return $this */ - public function setItalic($pValue) + public function setItalic($italic) { - if ($pValue == '') { - $pValue = false; + if ($italic == '') { + $italic = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['italic' => $pValue]); + $styleArray = $this->getStyleArray(['italic' => $italic]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->italic = $pValue; + $this->italic = $italic; } return $this; @@ -347,7 +353,7 @@ public function setItalic($pValue) /** * Get Superscript. * - * @return bool + * @return null|bool */ public function getSuperscript() { @@ -361,21 +367,18 @@ public function getSuperscript() /** * Set Superscript. * - * @param bool $pValue - * * @return $this */ - public function setSuperscript($pValue) + public function setSuperscript(bool $superscript) { - if ($pValue == '') { - $pValue = false; - } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['superscript' => $pValue]); + $styleArray = $this->getStyleArray(['superscript' => $superscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->superscript = $pValue; - $this->subscript = !$pValue; + $this->superscript = $superscript; + if ($this->superscript) { + $this->subscript = false; + } } return $this; @@ -384,7 +387,7 @@ public function setSuperscript($pValue) /** * Get Subscript. * - * @return bool + * @return null|bool */ public function getSubscript() { @@ -398,21 +401,18 @@ public function getSubscript() /** * Set Subscript. * - * @param bool $pValue - * * @return $this */ - public function setSubscript($pValue) + public function setSubscript(bool $subscript) { - if ($pValue == '') { - $pValue = false; - } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['subscript' => $pValue]); + $styleArray = $this->getStyleArray(['subscript' => $subscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->subscript = $pValue; - $this->superscript = !$pValue; + $this->subscript = $subscript; + if ($this->subscript) { + $this->superscript = false; + } } return $this; @@ -421,7 +421,7 @@ public function setSubscript($pValue) /** * Get Underline. * - * @return string + * @return null|string */ public function getUnderline() { @@ -435,24 +435,24 @@ public function getUnderline() /** * Set Underline. * - * @param bool|string $pValue \PhpOffice\PhpSpreadsheet\Style\Font underline type + * @param bool|string $underlineStyle \PhpOffice\PhpSpreadsheet\Style\Font underline type * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, * false equates to UNDERLINE_NONE * * @return $this */ - public function setUnderline($pValue) + public function setUnderline($underlineStyle) { - if (is_bool($pValue)) { - $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; - } elseif ($pValue == '') { - $pValue = self::UNDERLINE_NONE; + if (is_bool($underlineStyle)) { + $underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; + } elseif ($underlineStyle == '') { + $underlineStyle = self::UNDERLINE_NONE; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['underline' => $pValue]); + $styleArray = $this->getStyleArray(['underline' => $underlineStyle]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->underline = $pValue; + $this->underline = $underlineStyle; } return $this; @@ -461,7 +461,7 @@ public function setUnderline($pValue) /** * Get Strikethrough. * - * @return bool + * @return null|bool */ public function getStrikethrough() { @@ -475,21 +475,21 @@ public function getStrikethrough() /** * Set Strikethrough. * - * @param bool $pValue + * @param bool $strikethru * * @return $this */ - public function setStrikethrough($pValue) + public function setStrikethrough($strikethru) { - if ($pValue == '') { - $pValue = false; + if ($strikethru == '') { + $strikethru = false; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['strikethrough' => $pValue]); + $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->strikethrough = $pValue; + $this->strikethrough = $strikethru; } return $this; @@ -508,16 +508,12 @@ public function getColor() /** * Set Color. * - * @param Color $pValue - * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setColor(Color $pValue) + public function setColor(Color $color) { // make sure parameter is a real color and not a supervisor - $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); @@ -553,4 +549,20 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'bold', $this->getBold()); + $this->exportArray2($exportedArray, 'color', $this->getColor()); + $this->exportArray2($exportedArray, 'italic', $this->getItalic()); + $this->exportArray2($exportedArray, 'name', $this->getName()); + $this->exportArray2($exportedArray, 'size', $this->getSize()); + $this->exportArray2($exportedArray, 'strikethrough', $this->getStrikethrough()); + $this->exportArray2($exportedArray, 'subscript', $this->getSubscript()); + $this->exportArray2($exportedArray, 'superscript', $this->getSuperscript()); + $this->exportArray2($exportedArray, 'underline', $this->getUnderline()); + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php index df4ca76f..6f552cb3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php @@ -2,11 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Style; -use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; -use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; -use PhpOffice\PhpSpreadsheet\Shared\Date; -use PhpOffice\PhpSpreadsheet\Shared\StringHelper; - class NumberFormat extends Supervisor { // Pre-defined formats @@ -15,11 +10,13 @@ class NumberFormat extends Supervisor const FORMAT_TEXT = '@'; const FORMAT_NUMBER = '0'; + const FORMAT_NUMBER_0 = '0.0'; const FORMAT_NUMBER_00 = '0.00'; const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'; const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'; const FORMAT_PERCENTAGE = '0%'; + const FORMAT_PERCENTAGE_0 = '0.0%'; const FORMAT_PERCENTAGE_00 = '0.00%'; const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; @@ -69,14 +66,14 @@ class NumberFormat extends Supervisor /** * Format Code. * - * @var string + * @var null|string */ protected $formatCode = self::FORMAT_GENERAL; /** * Built-in format Code. * - * @var string + * @var false|int */ protected $builtInFormatCode = 0; @@ -109,7 +106,10 @@ public function __construct($isSupervisor = false, $isConditional = false) */ public function getSharedComponent() { - return $this->parent->getSharedComponent()->getNumberFormat(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getNumberFormat(); } /** @@ -135,19 +135,17 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['formatCode'])) { - $this->setFormatCode($pStyles['formatCode']); + if (isset($styleArray['formatCode'])) { + $this->setFormatCode($styleArray['formatCode']); } } @@ -157,14 +155,14 @@ public function applyFromArray(array $pStyles) /** * Get Format Code. * - * @return string + * @return null|string */ public function getFormatCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getFormatCode(); } - if ($this->builtInFormatCode !== false) { + if (is_int($this->builtInFormatCode)) { return self::builtInFormatCode($this->builtInFormatCode); } @@ -174,21 +172,21 @@ public function getFormatCode() /** * Set Format Code. * - * @param string $pValue see self::FORMAT_* + * @param string $formatCode see self::FORMAT_* * * @return $this */ - public function setFormatCode($pValue) + public function setFormatCode($formatCode) { - if ($pValue == '') { - $pValue = self::FORMAT_GENERAL; + if ($formatCode == '') { + $formatCode = self::FORMAT_GENERAL; } if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['formatCode' => $pValue]); + $styleArray = $this->getStyleArray(['formatCode' => $formatCode]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->formatCode = $pValue; - $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue); + $this->formatCode = $formatCode; + $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode); } return $this; @@ -197,7 +195,7 @@ public function setFormatCode($pValue) /** * Get Built-In Format Code. * - * @return int + * @return false|int */ public function getBuiltInFormatCode() { @@ -211,18 +209,18 @@ public function getBuiltInFormatCode() /** * Set Built-In Format Code. * - * @param int $pValue + * @param int $formatCodeIndex * * @return $this */ - public function setBuiltInFormatCode($pValue) + public function setBuiltInFormatCode($formatCodeIndex) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($pValue)]); + $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->builtInFormatCode = $pValue; - $this->formatCode = self::builtInFormatCode($pValue); + $this->builtInFormatCode = $formatCodeIndex; + $this->formatCode = self::builtInFormatCode($formatCodeIndex); } return $this; @@ -231,7 +229,7 @@ public function setBuiltInFormatCode($pValue) /** * Fill built-in format codes. */ - private static function fillBuiltInFormatCodes() + private static function fillBuiltInFormatCodes(): void { // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance] // 18.8.30. numFmt (Number Format) @@ -334,21 +332,21 @@ private static function fillBuiltInFormatCodes() /** * Get built-in format code. * - * @param int $pIndex + * @param int $index * * @return string */ - public static function builtInFormatCode($pIndex) + public static function builtInFormatCode($index) { // Clean parameter - $pIndex = (int) $pIndex; + $index = (int) $index; // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code - if (isset(self::$builtInFormats[$pIndex])) { - return self::$builtInFormats[$pIndex]; + if (isset(self::$builtInFormats[$index])) { + return self::$builtInFormats[$index]; } return ''; @@ -357,18 +355,18 @@ public static function builtInFormatCode($pIndex) /** * Get built-in format code index. * - * @param string $formatCode + * @param string $formatCodeIndex * - * @return bool|int + * @return false|int */ - public static function builtInFormatCodeIndex($formatCode) + public static function builtInFormatCodeIndex($formatCodeIndex) { // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code - if (array_key_exists($formatCode, self::$flippedBuiltInFormats)) { - return self::$flippedBuiltInFormats[$formatCode]; + if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) { + return self::$flippedBuiltInFormats[$formatCodeIndex]; } return false; @@ -392,334 +390,6 @@ public function getHashCode() ); } - /** - * Search/replace values to convert Excel date/time format masks to PHP format masks. - * - * @var array - */ - private static $dateFormatReplacements = [ - // first remove escapes related to non-format characters - '\\' => '', - // 12-hour suffix - 'am/pm' => 'A', - // 4-digit year - 'e' => 'Y', - 'yyyy' => 'Y', - // 2-digit year - 'yy' => 'y', - // first letter of month - no php equivalent - 'mmmmm' => 'M', - // full month name - 'mmmm' => 'F', - // short month name - 'mmm' => 'M', - // mm is minutes if time, but can also be month w/leading zero - // so we try to identify times be the inclusion of a : separator in the mask - // It isn't perfect, but the best way I know how - ':mm' => ':i', - 'mm:' => 'i:', - // month leading zero - 'mm' => 'm', - // month no leading zero - 'm' => 'n', - // full day of week name - 'dddd' => 'l', - // short day of week name - 'ddd' => 'D', - // days leading zero - 'dd' => 'd', - // days no leading zero - 'd' => 'j', - // seconds - 'ss' => 's', - // fractional seconds - no php equivalent - '.s' => '', - ]; - - /** - * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). - * - * @var array - */ - private static $dateFormatReplacements24 = [ - 'hh' => 'H', - 'h' => 'G', - ]; - - /** - * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). - * - * @var array - */ - private static $dateFormatReplacements12 = [ - 'hh' => 'h', - 'h' => 'g', - ]; - - private static function setLowercaseCallback($matches) - { - return mb_strtolower($matches[0]); - } - - private static function escapeQuotesCallback($matches) - { - return '\\' . implode('\\', str_split($matches[1])); - } - - private static function formatAsDate(&$value, &$format) - { - // strip off first part containing e.g. [$-F800] or [$USD-409] - // general syntax: [$-] - // language info is in hexadecimal - // strip off chinese part like [DBNum1][$-804] - $format = preg_replace('/^(\[[0-9A-Za-z]*\])*(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format); - - // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; - // but we don't want to change any quoted strings - $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', ['self', 'setLowercaseCallback'], $format); - - // Only process the non-quoted blocks for date format characters - $blocks = explode('"', $format); - foreach ($blocks as $key => &$block) { - if ($key % 2 == 0) { - $block = strtr($block, self::$dateFormatReplacements); - if (!strpos($block, 'A')) { - // 24-hour time format - // when [h]:mm format, the [h] should replace to the hours of the value * 24 - if (false !== strpos($block, '[h]')) { - $hours = (int) ($value * 24); - $block = str_replace('[h]', $hours, $block); - - continue; - } - $block = strtr($block, self::$dateFormatReplacements24); - } else { - // 12-hour time format - $block = strtr($block, self::$dateFormatReplacements12); - } - } - } - $format = implode('"', $blocks); - - // escape any quoted characters so that DateTime format() will render them correctly - $format = preg_replace_callback('/"(.*)"/U', ['self', 'escapeQuotesCallback'], $format); - - $dateObj = Date::excelToDateTimeObject($value); - $value = $dateObj->format($format); - } - - private static function formatAsPercentage(&$value, &$format) - { - if ($format === self::FORMAT_PERCENTAGE) { - $value = round((100 * $value), 0) . '%'; - } else { - if (preg_match('/\.[#0]+/', $format, $m)) { - $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1); - $format = str_replace($m[0], $s, $format); - } - if (preg_match('/^[#0]+/', $format, $m)) { - $format = str_replace($m[0], strlen($m[0]), $format); - } - $format = '%' . str_replace('%', 'f%%', $format); - - $value = sprintf($format, 100 * $value); - } - } - - private static function formatAsFraction(&$value, &$format) - { - $sign = ($value < 0) ? '-' : ''; - - $integerPart = floor(abs($value)); - $decimalPart = trim(fmod(abs($value), 1), '0.'); - $decimalLength = strlen($decimalPart); - $decimalDivisor = pow(10, $decimalLength); - - $GCD = MathTrig::GCD($decimalPart, $decimalDivisor); - - $adjustedDecimalPart = $decimalPart / $GCD; - $adjustedDecimalDivisor = $decimalDivisor / $GCD; - - if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) { - if ($integerPart == 0) { - $integerPart = ''; - } - $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; - } else { - $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; - $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor"; - } - } - - private static function mergeComplexNumberFormatMasks($numbers, $masks) - { - $decimalCount = strlen($numbers[1]); - $postDecimalMasks = []; - - do { - $tempMask = array_pop($masks); - $postDecimalMasks[] = $tempMask; - $decimalCount -= strlen($tempMask); - } while ($decimalCount > 0); - - return [ - implode('.', $masks), - implode('.', array_reverse($postDecimalMasks)), - ]; - } - - private static function processComplexNumberFormatMask($number, $mask) - { - $result = $number; - $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); - - if ($maskingBlockCount > 1) { - $maskingBlocks = array_reverse($maskingBlocks[0]); - - foreach ($maskingBlocks as $block) { - $divisor = 1 . $block[0]; - $size = strlen($block[0]); - $offset = $block[1]; - - $blockValue = sprintf( - '%0' . $size . 'd', - fmod($number, $divisor) - ); - $number = floor($number / $divisor); - $mask = substr_replace($mask, $blockValue, $offset, $size); - } - if ($number > 0) { - $mask = substr_replace($mask, $number, $offset, 0); - } - $result = $mask; - } - - return $result; - } - - private static function complexNumberFormatMask($number, $mask, $splitOnPoint = true) - { - $sign = ($number < 0.0); - $number = abs($number); - - if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) { - $numbers = explode('.', $number); - $masks = explode('.', $mask); - if (count($masks) > 2) { - $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); - } - $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], false); - $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); - - return (($sign) ? '-' : '') . $result1 . '.' . $result2; - } - - $result = self::processComplexNumberFormatMask($number, $mask); - - return (($sign) ? '-' : '') . $result; - } - - private static function formatStraightNumericValue($value, $format, array $matches, $useThousands, $number_regex) - { - $left = $matches[1]; - $dec = $matches[2]; - $right = $matches[3]; - - // minimun width of formatted number (including dot) - $minWidth = strlen($left) + strlen($dec) + strlen($right); - if ($useThousands) { - $value = number_format( - $value, - strlen($right), - StringHelper::getDecimalSeparator(), - StringHelper::getThousandsSeparator() - ); - $value = preg_replace($number_regex, $value, $format); - } else { - if (preg_match('/[0#]E[+-]0/i', $format)) { - // Scientific format - $value = sprintf('%5.2E', $value); - } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { - if ($value == (int) $value && substr_count($format, '.') === 1) { - $value *= 10 ** strlen(explode('.', $format)[1]); - } - $value = self::complexNumberFormatMask($value, $format); - } else { - $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f'; - $value = sprintf($sprintf_pattern, $value); - $value = preg_replace($number_regex, $value, $format); - } - } - - return $value; - } - - private static function formatAsNumber($value, $format) - { - if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) { - return 'EUR ' . sprintf('%1.2f', $value); - } - - // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols - $format = str_replace(['"', '*'], '', $format); - - // Find out if we need thousands separator - // This is indicated by a comma enclosed by a digit placeholder: - // #,# or 0,0 - $useThousands = preg_match('/(#,#|0,0)/', $format); - if ($useThousands) { - $format = preg_replace('/0,0/', '00', $format); - $format = preg_replace('/#,#/', '##', $format); - } - - // Scale thousands, millions,... - // This is indicated by a number of commas after a digit placeholder: - // #, or 0.0,, - $scale = 1; // same as no scale - $matches = []; - if (preg_match('/(#|0)(,+)/', $format, $matches)) { - $scale = pow(1000, strlen($matches[2])); - - // strip the commas - $format = preg_replace('/0,+/', '0', $format); - $format = preg_replace('/#,+/', '#', $format); - } - - if (preg_match('/#?.*\?\/\?/', $format, $m)) { - if ($value != (int) $value) { - self::formatAsFraction($value, $format); - } - } else { - // Handle the number itself - - // scale number - $value = $value / $scale; - // Strip # - $format = preg_replace('/\\#/', '0', $format); - // Remove locale code [$-###] - $format = preg_replace('/\[\$\-.*\]/', '', $format); - - $n = '/\\[[^\\]]+\\]/'; - $m = preg_replace($n, '', $format); - $number_regex = '/(0+)(\\.?)(0*)/'; - if (preg_match($number_regex, $m, $matches)) { - $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands, $number_regex); - } - } - - if (preg_match('/\[\$(.*)\]/u', $format, $m)) { - // Currency or Accounting - $currencyCode = $m[1]; - [$currencyCode] = explode('-', $currencyCode); - if ($currencyCode == '') { - $currencyCode = StringHelper::getCurrencyCode(); - } - $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value); - } - - return $value; - } - /** * Convert a value in a pre-defined format to a PHP string. * @@ -731,90 +401,14 @@ private static function formatAsNumber($value, $format) */ public static function toFormattedString($value, $format, $callBack = null) { - // For now we do not treat strings although section 4 of a format code affects strings - if (!is_numeric($value)) { - return $value; - } - - // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, - // it seems to round numbers to a total of 10 digits. - if (($format === self::FORMAT_GENERAL) || ($format === self::FORMAT_TEXT)) { - return $value; - } - - // Convert any other escaped characters to quoted strings, e.g. (\T to "T") - $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format); - - // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal) - $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format); - - // Extract the relevant section depending on whether number is positive, negative, or zero? - // Text not supported yet. - // Here is how the sections apply to various values in Excel: - // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] - // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] - // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] - // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] - switch (count($sections)) { - case 1: - $format = $sections[0]; - - break; - case 2: - $format = ($value >= 0) ? $sections[0] : $sections[1]; - $value = abs($value); // Use the absolute value - break; - case 3: - $format = ($value > 0) ? - $sections[0] : (($value < 0) ? - $sections[1] : $sections[2]); - $value = abs($value); // Use the absolute value - break; - case 4: - $format = ($value > 0) ? - $sections[0] : (($value < 0) ? - $sections[1] : $sections[2]); - $value = abs($value); // Use the absolute value - break; - default: - // something is wrong, just use first section - $format = $sections[0]; - - break; - } - - // In Excel formats, "_" is used to add spacing, - // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space - $format = preg_replace('/_./', ' ', $format); - - // Save format with color information for later use below - $formatColor = $format; - // Strip colour information - $color_regex = '/\[(' . implode('|', Color::NAMED_COLORS) . ')\]/'; - $format = preg_replace($color_regex, '', $format); - // Let's begin inspecting the format and converting the value to a formatted string - - // Check for date/time characters (not inside quotes) - if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) { - // datetime format - self::formatAsDate($value, $format); - } else { - if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"') { - $value = substr($format, 1, -1); - } elseif (preg_match('/%$/', $format)) { - // % number format - self::formatAsPercentage($value, $format); - } else { - $value = self::formatAsNumber($value, $format); - } - } + return NumberFormat\Formatter::toFormattedString($value, $format, $callBack); + } - // Additional formatting provided by callback function - if ($callBack !== null) { - [$writerInstance, $function] = $callBack; - $value = $writerInstance->$function($value, $formatColor); - } + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'formatCode', $this->getFormatCode()); - return $value; + return $exportedArray; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php new file mode 100644 index 00000000..7988143c --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php @@ -0,0 +1,12 @@ + '', + // 12-hour suffix + 'am/pm' => 'A', + // 4-digit year + 'e' => 'Y', + 'yyyy' => 'Y', + // 2-digit year + 'yy' => 'y', + // first letter of month - no php equivalent + 'mmmmm' => 'M', + // full month name + 'mmmm' => 'F', + // short month name + 'mmm' => 'M', + // mm is minutes if time, but can also be month w/leading zero + // so we try to identify times be the inclusion of a : separator in the mask + // It isn't perfect, but the best way I know how + ':mm' => ':i', + 'mm:' => 'i:', + // full day of week name + 'dddd' => 'l', + // short day of week name + 'ddd' => 'D', + // days leading zero + 'dd' => 'd', + // days no leading zero + 'd' => 'j', + // fractional seconds - no php equivalent + '.s' => '', + ]; + + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). + */ + private const DATE_FORMAT_REPLACEMENTS24 = [ + 'hh' => 'H', + 'h' => 'G', + // month leading zero + 'mm' => 'm', + // month no leading zero + 'm' => 'n', + // seconds + 'ss' => 's', + ]; + + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). + */ + private const DATE_FORMAT_REPLACEMENTS12 = [ + 'hh' => 'h', + 'h' => 'g', + // month leading zero + 'mm' => 'm', + // month no leading zero + 'm' => 'n', + // seconds + 'ss' => 's', + ]; + + private const HOURS_IN_DAY = 24; + private const MINUTES_IN_DAY = 60 * self::HOURS_IN_DAY; + private const SECONDS_IN_DAY = 60 * self::MINUTES_IN_DAY; + private const INTERVAL_PRECISION = 10; + private const INTERVAL_LEADING_ZERO = [ + '[hh]', + '[mm]', + '[ss]', + ]; + private const INTERVAL_ROUND_PRECISION = [ + // hours and minutes truncate + '[h]' => self::INTERVAL_PRECISION, + '[hh]' => self::INTERVAL_PRECISION, + '[m]' => self::INTERVAL_PRECISION, + '[mm]' => self::INTERVAL_PRECISION, + // seconds round + '[s]' => 0, + '[ss]' => 0, + ]; + private const INTERVAL_MULTIPLIER = [ + '[h]' => self::HOURS_IN_DAY, + '[hh]' => self::HOURS_IN_DAY, + '[m]' => self::MINUTES_IN_DAY, + '[mm]' => self::MINUTES_IN_DAY, + '[s]' => self::SECONDS_IN_DAY, + '[ss]' => self::SECONDS_IN_DAY, + ]; + + /** @param mixed $value */ + private static function tryInterval(bool &$seekingBracket, string &$block, $value, string $format): void + { + if ($seekingBracket) { + if (false !== strpos($block, $format)) { + $hours = (string) (int) round( + self::INTERVAL_MULTIPLIER[$format] * $value, + self::INTERVAL_ROUND_PRECISION[$format] + ); + if (strlen($hours) === 1 && in_array($format, self::INTERVAL_LEADING_ZERO, true)) { + $hours = "0$hours"; + } + $block = str_replace($format, $hours, $block); + $seekingBracket = false; + } + } + } + + /** @param mixed $value */ + public static function format($value, string $format): string + { + // strip off first part containing e.g. [$-F800] or [$USD-409] + // general syntax: [$-] + // language info is in hexadecimal + // strip off chinese part like [DBNum1][$-804] + $format = (string) preg_replace('/^(\[DBNum\d\])*(\[\$[^\]]*\])/i', '', $format); + + // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; + // but we don't want to change any quoted strings + /** @var callable */ + $callable = [self::class, 'setLowercaseCallback']; + $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', $callable, $format); + + // Only process the non-quoted blocks for date format characters + + /** @phpstan-ignore-next-line */ + $blocks = explode('"', $format); + foreach ($blocks as $key => &$block) { + if ($key % 2 == 0) { + $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS); + if (!strpos($block, 'A')) { + // 24-hour time format + // when [h]:mm format, the [h] should replace to the hours of the value * 24 + $seekingBracket = true; + self::tryInterval($seekingBracket, $block, $value, '[h]'); + self::tryInterval($seekingBracket, $block, $value, '[hh]'); + self::tryInterval($seekingBracket, $block, $value, '[mm]'); + self::tryInterval($seekingBracket, $block, $value, '[m]'); + self::tryInterval($seekingBracket, $block, $value, '[s]'); + self::tryInterval($seekingBracket, $block, $value, '[ss]'); + $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS24); + } else { + // 12-hour time format + $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS12); + } + } + } + $format = implode('"', $blocks); + + // escape any quoted characters so that DateTime format() will render them correctly + /** @var callable */ + $callback = [self::class, 'escapeQuotesCallback']; + $format = (string) preg_replace_callback('/"(.*)"/U', $callback, $format); + + $dateObj = Date::excelToDateTimeObject($value); + // If the colon preceding minute had been quoted, as happens in + // Excel 2003 XML formats, m will not have been changed to i above. + // Change it now. + $format = (string) \preg_replace('/\\\\:m/', ':i', $format); + + return $dateObj->format($format); + } + + private static function setLowercaseCallback(array $matches): string + { + return mb_strtolower($matches[0]); + } + + private static function escapeQuotesCallback(array $matches): string + { + return '\\' . implode('\\', str_split($matches[1])); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php new file mode 100644 index 00000000..01407e64 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php @@ -0,0 +1,162 @@ +': + return $value > $val; + + case '<': + return $value < $val; + + case '<=': + return $value <= $val; + + case '<>': + return $value != $val; + + case '=': + return $value == $val; + } + + return $value >= $val; + } + + private static function splitFormat($sections, $value) + { + // Extract the relevant section depending on whether number is positive, negative, or zero? + // Text not supported yet. + // Here is how the sections apply to various values in Excel: + // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] + // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] + // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] + // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] + $cnt = count($sections); + $color_regex = '/\\[(' . implode('|', Color::NAMED_COLORS) . ')\\]/mui'; + $cond_regex = '/\\[(>|>=|<|<=|=|<>)([+-]?\\d+([.]\\d+)?)\\]/'; + $colors = ['', '', '', '', '']; + $condops = ['', '', '', '', '']; + $condvals = [0, 0, 0, 0, 0]; + for ($idx = 0; $idx < $cnt; ++$idx) { + if (preg_match($color_regex, $sections[$idx], $matches)) { + $colors[$idx] = $matches[0]; + $sections[$idx] = preg_replace($color_regex, '', $sections[$idx]); + } + if (preg_match($cond_regex, $sections[$idx], $matches)) { + $condops[$idx] = $matches[1]; + $condvals[$idx] = $matches[2]; + $sections[$idx] = preg_replace($cond_regex, '', $sections[$idx]); + } + } + $color = $colors[0]; + $format = $sections[0]; + $absval = $value; + switch ($cnt) { + case 2: + $absval = abs($value); + if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>=', 0)) { + $color = $colors[1]; + $format = $sections[1]; + } + + break; + case 3: + case 4: + $absval = abs($value); + if (!self::splitFormatCompare($value, $condops[0], $condvals[0], '>', 0)) { + if (self::splitFormatCompare($value, $condops[1], $condvals[1], '<', 0)) { + $color = $colors[1]; + $format = $sections[1]; + } else { + $color = $colors[2]; + $format = $sections[2]; + } + } + + break; + } + + return [$color, $format, $absval]; + } + + /** + * Convert a value in a pre-defined format to a PHP string. + * + * @param mixed $value Value to format + * @param string $format Format code, see = NumberFormat::FORMAT_* + * @param array $callBack Callback function for additional formatting of string + * + * @return string Formatted string + */ + public static function toFormattedString($value, $format, $callBack = null) + { + // For now we do not treat strings although section 4 of a format code affects strings + if (!is_numeric($value)) { + return $value; + } + + // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, + // it seems to round numbers to a total of 10 digits. + if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) { + return $value; + } + + $format = preg_replace_callback( + '/(["])(?:(?=(\\\\?))\\2.)*?\\1/u', + function ($matches) { + return str_replace('.', chr(0x00), $matches[0]); + }, + $format + ); + + // Convert any other escaped characters to quoted strings, e.g. (\T to "T") + $format = preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format); + + // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal) + $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format); + + [$colors, $format, $value] = self::splitFormat($sections, $value); + + // In Excel formats, "_" is used to add spacing, + // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space + $format = preg_replace('/_.?/ui', ' ', $format); + + // Let's begin inspecting the format and converting the value to a formatted string + + // Check for date/time characters (not inside quotes) + if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) { + // datetime format + $value = DateFormatter::format($value, $format); + } else { + if (substr($format, 0, 1) === '"' && substr($format, -1, 1) === '"' && substr_count($format, '"') === 2) { + $value = substr($format, 1, -1); + } elseif (preg_match('/[0#, ]%/', $format)) { + // % number format + $value = PercentageFormatter::format($value, $format); + } else { + $value = NumberFormatter::format($value, $format); + } + } + + // Additional formatting provided by callback function + if ($callBack !== null) { + [$writerInstance, $function] = $callBack; + $value = $writerInstance->$function($value, $colors); + } + + $value = str_replace(chr(0x00), '.', $value); + + return $value; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php new file mode 100644 index 00000000..d1fc89fd --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php @@ -0,0 +1,67 @@ + 0); + + return [ + implode('.', $masks), + implode('.', array_reverse($postDecimalMasks)), + ]; + } + + /** + * @param mixed $number + */ + private static function processComplexNumberFormatMask($number, string $mask): string + { + /** @var string */ + $result = $number; + $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); + + if ($maskingBlockCount > 1) { + $maskingBlocks = array_reverse($maskingBlocks[0]); + + $offset = 0; + foreach ($maskingBlocks as $block) { + $size = strlen($block[0]); + $divisor = 10 ** $size; + $offset = $block[1]; + + /** @var float */ + $numberFloat = $number; + $blockValue = sprintf("%0{$size}d", fmod($numberFloat, $divisor)); + $number = floor($numberFloat / $divisor); + $mask = substr_replace($mask, $blockValue, $offset, $size); + } + /** @var string */ + $numberString = $number; + if ($number > 0) { + $mask = substr_replace($mask, $numberString, $offset, 0); + } + $result = $mask; + } + + return self::makeString($result); + } + + /** + * @param mixed $number + */ + private static function complexNumberFormatMask($number, string $mask, bool $splitOnPoint = true): string + { + $sign = ($number < 0.0) ? '-' : ''; + /** @var float */ + $numberFloat = $number; + $number = (string) abs($numberFloat); + + if ($splitOnPoint && strpos($mask, '.') !== false && strpos($number, '.') !== false) { + $numbers = explode('.', $number); + $masks = explode('.', $mask); + if (count($masks) > 2) { + $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); + } + $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false); + $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); + + return "{$sign}{$integerPart}.{$decimalPart}"; + } + + $result = self::processComplexNumberFormatMask($number, $mask); + + return "{$sign}{$result}"; + } + + /** + * @param mixed $value + */ + private static function formatStraightNumericValue($value, string $format, array $matches, bool $useThousands): string + { + /** @var float */ + $valueFloat = $value; + $left = $matches[1]; + $dec = $matches[2]; + $right = $matches[3]; + + // minimun width of formatted number (including dot) + $minWidth = strlen($left) + strlen($dec) + strlen($right); + if ($useThousands) { + $value = number_format( + $valueFloat, + strlen($right), + StringHelper::getDecimalSeparator(), + StringHelper::getThousandsSeparator() + ); + + return self::pregReplace(self::NUMBER_REGEX, $value, $format); + } + + if (preg_match('/[0#]E[+-]0/i', $format)) { + // Scientific format + return sprintf('%5.2E', $valueFloat); + } elseif (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { + if ($value == (int) $valueFloat && substr_count($format, '.') === 1) { + $value *= 10 ** strlen(explode('.', $format)[1]); + } + + return self::complexNumberFormatMask($value, $format); + } + + $sprintf_pattern = "%0$minWidth." . strlen($right) . 'f'; + /** @var float */ + $valueFloat = $value; + $value = sprintf($sprintf_pattern, round($valueFloat, strlen($right))); + + return self::pregReplace(self::NUMBER_REGEX, $value, $format); + } + + /** + * @param mixed $value + */ + public static function format($value, string $format): string + { + // The "_" in this string has already been stripped out, + // so this test is never true. Furthermore, testing + // on Excel shows this format uses Euro symbol, not "EUR". + //if ($format === NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE) { + // return 'EUR ' . sprintf('%1.2f', $value); + //} + + // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols + $format = self::makeString(str_replace(['"', '*'], '', $format)); + + // Find out if we need thousands separator + // This is indicated by a comma enclosed by a digit placeholder: + // #,# or 0,0 + $useThousands = (bool) preg_match('/(#,#|0,0)/', $format); + if ($useThousands) { + $format = self::pregReplace('/0,0/', '00', $format); + $format = self::pregReplace('/#,#/', '##', $format); + } + + // Scale thousands, millions,... + // This is indicated by a number of commas after a digit placeholder: + // #, or 0.0,, + $scale = 1; // same as no scale + $matches = []; + if (preg_match('/(#|0)(,+)/', $format, $matches)) { + $scale = 1000 ** strlen($matches[2]); + + // strip the commas + $format = self::pregReplace('/0,+/', '0', $format); + $format = self::pregReplace('/#,+/', '#', $format); + } + if (preg_match('/#?.*\?\/\?/', $format, $m)) { + $value = FractionFormatter::format($value, $format); + } else { + // Handle the number itself + + // scale number + $value = $value / $scale; + // Strip # + $format = self::pregReplace('/\\#/', '0', $format); + // Remove locale code [$-###] + $format = self::pregReplace('/\[\$\-.*\]/', '', $format); + + $n = '/\\[[^\\]]+\\]/'; + $m = self::pregReplace($n, '', $format); + if (preg_match(self::NUMBER_REGEX, $m, $matches)) { + // There are placeholders for digits, so inject digits from the value into the mask + $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands); + } elseif ($format !== NumberFormat::FORMAT_GENERAL) { + // Yes, I know that this is basically just a hack; + // if there's no placeholders for digits, just return the format mask "as is" + $value = self::makeString(str_replace('?', '', $format)); + } + } + + if (preg_match('/\[\$(.*)\]/u', $format, $m)) { + // Currency or Accounting + $currencyCode = $m[1]; + [$currencyCode] = explode('-', $currencyCode); + if ($currencyCode == '') { + $currencyCode = StringHelper::getCurrencyCode(); + } + $value = self::pregReplace('/\[\$([^\]]*)\]/u', $currencyCode, (string) $value); + } + + return (string) $value; + } + + /** + * @param array|string $value + */ + private static function makeString($value): string + { + return is_array($value) ? '' : "$value"; + } + + private static function pregReplace(string $pattern, string $replacement, string $subject): string + { + return self::makeString(preg_replace($pattern, $replacement, $subject) ?? ''); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php new file mode 100644 index 00000000..334c40df --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php @@ -0,0 +1,45 @@ +parent->getSharedComponent()->getProtection(); + /** @var Style */ + $parent = $this->parent; + + return $parent->getSharedComponent()->getProtection(); } /** @@ -82,22 +83,20 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * - * @throws PhpSpreadsheetException + * @param array $styleArray Array containing style information * * @return $this */ - public function applyFromArray(array $pStyles) + public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { - $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { - if (isset($pStyles['locked'])) { - $this->setLocked($pStyles['locked']); + if (isset($styleArray['locked'])) { + $this->setLocked($styleArray['locked']); } - if (isset($pStyles['hidden'])) { - $this->setHidden($pStyles['hidden']); + if (isset($styleArray['hidden'])) { + $this->setHidden($styleArray['hidden']); } } @@ -121,17 +120,17 @@ public function getLocked() /** * Set locked. * - * @param string $pValue see self::PROTECTION_* + * @param string $lockType see self::PROTECTION_* * * @return $this */ - public function setLocked($pValue) + public function setLocked($lockType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['locked' => $pValue]); + $styleArray = $this->getStyleArray(['locked' => $lockType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->locked = $pValue; + $this->locked = $lockType; } return $this; @@ -154,17 +153,17 @@ public function getHidden() /** * Set hidden. * - * @param string $pValue see self::PROTECTION_* + * @param string $hiddenType see self::PROTECTION_* * * @return $this */ - public function setHidden($pValue) + public function setHidden($hiddenType) { if ($this->isSupervisor) { - $styleArray = $this->getStyleArray(['hidden' => $pValue]); + $styleArray = $this->getStyleArray(['hidden' => $hiddenType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->hidden = $pValue; + $this->hidden = $hiddenType; } return $this; @@ -187,4 +186,13 @@ public function getHashCode() __CLASS__ ); } + + protected function exportArray1(): array + { + $exportedArray = []; + $this->exportArray2($exportedArray, 'locked', $this->getLocked()); + $this->exportArray2($exportedArray, 'hidden', $this->getHidden()); + + return $exportedArray; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php index a37d99b5..78e5ebbf 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php @@ -42,13 +42,6 @@ class Style extends Supervisor */ protected $numberFormat; - /** - * Conditional styles. - * - * @var Conditional[] - */ - protected $conditionalStyles; - /** * Protection. * @@ -70,6 +63,25 @@ class Style extends Supervisor */ protected $quotePrefix = false; + /** + * Internal cache for styles + * Used when applying style on range of cells (column or row) and cleared when + * all cells in range is styled. + * + * PhpSpreadsheet will always minimize the amount of styles used. So cells with + * same styles will reference the same Style instance. To check if two styles + * are similar Style::getHashCode() is used. This call is expensive. To minimize + * the need to call this method we can cache the internal PHP object id of the + * Style in the range. Style::getHashCode() will then only be called when we + * encounter a unique style. + * + * @see Style::applyFromArray() + * @see Style::getHashCode() + * + * @var ?array + */ + private static $cachedStyles; + /** * Create a new Style. * @@ -85,10 +97,9 @@ public function __construct($isSupervisor = false, $isConditional = false) parent::__construct($isSupervisor); // Initialise values - $this->conditionalStyles = []; $this->font = new Font($isSupervisor, $isConditional); $this->fill = new Fill($isSupervisor, $isConditional); - $this->borders = new Borders($isSupervisor, $isConditional); + $this->borders = new Borders($isSupervisor); $this->alignment = new Alignment($isSupervisor, $isConditional); $this->numberFormat = new NumberFormat($isSupervisor, $isConditional); $this->protection = new Protection($isSupervisor, $isConditional); @@ -107,10 +118,8 @@ public function __construct($isSupervisor = false, $isConditional = false) /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. - * - * @return Style */ - public function getSharedComponent() + public function getSharedComponent(): self { $activeSheet = $this->getActiveSheet(); $selectedCell = $this->getActiveCell(); // e.g. 'A1' @@ -121,17 +130,15 @@ public function getSharedComponent() $xfIndex = 0; } - return $this->parent->getCellXfByIndex($xfIndex); + return $activeSheet->getParent()->getCellXfByIndex($xfIndex); } /** * Get parent. Only used for style supervisor. - * - * @return Spreadsheet */ - public function getParent() + public function getParent(): Spreadsheet { - return $this->parent; + return $this->getActiveSheet()->getParent(); } /** @@ -186,12 +193,12 @@ public function getStyleArray($array) * ); * * - * @param array $pStyles Array containing style information - * @param bool $pAdvanced advanced mode for setting borders + * @param array $styleArray Array containing style information + * @param bool $advancedBorders advanced mode for setting borders * * @return $this */ - public function applyFromArray(array $pStyles, $pAdvanced = true) + public function applyFromArray(array $styleArray, $advancedBorders = true) { if ($this->isSupervisor) { $pRange = $this->getSelectedCells(); @@ -210,64 +217,65 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) // Calculate range outer borders $rangeStart = Coordinate::coordinateFromString($rangeA); $rangeEnd = Coordinate::coordinateFromString($rangeB); + $rangeStartIndexes = Coordinate::indexesFromString($rangeA); + $rangeEndIndexes = Coordinate::indexesFromString($rangeB); - // Translate column into index - $rangeStart[0] = Coordinate::columnIndexFromString($rangeStart[0]); - $rangeEnd[0] = Coordinate::columnIndexFromString($rangeEnd[0]); + $columnStart = $rangeStart[0]; + $columnEnd = $rangeEnd[0]; // Make sure we can loop upwards on rows and columns - if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { - $tmp = $rangeStart; - $rangeStart = $rangeEnd; - $rangeEnd = $tmp; + if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) { + $tmp = $rangeStartIndexes; + $rangeStartIndexes = $rangeEndIndexes; + $rangeEndIndexes = $tmp; } // ADVANCED MODE: - if ($pAdvanced && isset($pStyles['borders'])) { + if ($advancedBorders && isset($styleArray['borders'])) { // 'allBorders' is a shorthand property for 'outline' and 'inside' and // it applies to components that have not been set explicitly - if (isset($pStyles['borders']['allBorders'])) { + if (isset($styleArray['borders']['allBorders'])) { foreach (['outline', 'inside'] as $component) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['allBorders']; + if (!isset($styleArray['borders'][$component])) { + $styleArray['borders'][$component] = $styleArray['borders']['allBorders']; } } - unset($pStyles['borders']['allBorders']); // not needed any more + unset($styleArray['borders']['allBorders']); // not needed any more } // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left' // it applies to components that have not been set explicitly - if (isset($pStyles['borders']['outline'])) { + if (isset($styleArray['borders']['outline'])) { foreach (['top', 'right', 'bottom', 'left'] as $component) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['outline']; + if (!isset($styleArray['borders'][$component])) { + $styleArray['borders'][$component] = $styleArray['borders']['outline']; } } - unset($pStyles['borders']['outline']); // not needed any more + unset($styleArray['borders']['outline']); // not needed any more } // 'inside' is a shorthand property for 'vertical' and 'horizontal' // it applies to components that have not been set explicitly - if (isset($pStyles['borders']['inside'])) { + if (isset($styleArray['borders']['inside'])) { foreach (['vertical', 'horizontal'] as $component) { - if (!isset($pStyles['borders'][$component])) { - $pStyles['borders'][$component] = $pStyles['borders']['inside']; + if (!isset($styleArray['borders'][$component])) { + $styleArray['borders'][$component] = $styleArray['borders']['inside']; } } - unset($pStyles['borders']['inside']); // not needed any more + unset($styleArray['borders']['inside']); // not needed any more } // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) - $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3); - $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3); + $xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3); + $yMax = min($rangeEndIndexes[1] - $rangeStartIndexes[1] + 1, 3); // loop through up to 3 x 3 = 9 regions for ($x = 1; $x <= $xMax; ++$x) { // start column index for region $colStart = ($x == 3) ? - Coordinate::stringFromColumnIndex($rangeEnd[0]) - : Coordinate::stringFromColumnIndex($rangeStart[0] + $x - 1); + Coordinate::stringFromColumnIndex($rangeEndIndexes[0]) + : Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1); // end column index for region $colEnd = ($x == 1) ? - Coordinate::stringFromColumnIndex($rangeStart[0]) - : Coordinate::stringFromColumnIndex($rangeEnd[0] - $xMax + $x); + Coordinate::stringFromColumnIndex($rangeStartIndexes[0]) + : Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x); for ($y = 1; $y <= $yMax; ++$y) { // which edges are touching the region @@ -291,17 +299,17 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) // start row index for region $rowStart = ($y == 3) ? - $rangeEnd[1] : $rangeStart[1] + $y - 1; + $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1; // end row index for region $rowEnd = ($y == 1) ? - $rangeStart[1] : $rangeEnd[1] - $yMax + $y; + $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y; // build range for region $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; // retrieve relevant style array for region - $regionStyles = $pStyles; + $regionStyles = $styleArray; unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection @@ -313,8 +321,8 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) case 'top': case 'bottom': // should pick up 'horizontal' border property if set - if (isset($pStyles['borders']['horizontal'])) { - $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal']; + if (isset($styleArray['borders']['horizontal'])) { + $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal']; } else { unset($regionStyles['borders'][$innerEdge]); } @@ -323,8 +331,8 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) case 'left': case 'right': // should pick up 'vertical' border property if set - if (isset($pStyles['borders']['vertical'])) { - $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical']; + if (isset($styleArray['borders']['vertical'])) { + $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical']; } else { unset($regionStyles['borders'][$innerEdge]); } @@ -348,54 +356,75 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) // Selection type, inspect if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) { $selectionType = 'COLUMN'; + + // Enable caching of styles + self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []]; } elseif (preg_match('/^A\d+:XFD\d+$/', $pRange)) { $selectionType = 'ROW'; + + // Enable caching of styles + self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []]; } else { $selectionType = 'CELL'; } // First loop through columns, rows, or cells to find out which styles are affected by this operation - switch ($selectionType) { - case 'COLUMN': - $oldXfIndexes = []; - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; - } - - break; - case 'ROW': - $oldXfIndexes = []; - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { - if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) { - $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style - } else { - $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; - } - } - - break; - case 'CELL': - $oldXfIndexes = []; - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { - $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; - } - } - - break; - } + $oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $styleArray); // clone each of the affected styles, apply the style array, and add the new styles to the workbook $workbook = $this->getActiveSheet()->getParent(); + $newXfIndexes = []; foreach ($oldXfIndexes as $oldXfIndex => $dummy) { $style = $workbook->getCellXfByIndex($oldXfIndex); - $newStyle = clone $style; - $newStyle->applyFromArray($pStyles); - if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) { + // $cachedStyles is set when applying style for a range of cells, either column or row + if (self::$cachedStyles === null) { + // Clone the old style and apply style-array + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + + // Look for existing style we can use instead (reduce memory usage) + $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); + } else { + // Style cache is stored by Style::getHashCode(). But calling this method is + // expensive. So we cache the php obj id -> hash. + $objId = spl_object_id($style); + + // Look for the original HashCode + $styleHash = self::$cachedStyles['hashByObjId'][$objId] ?? null; + if ($styleHash === null) { + // This object_id is not cached, store the hashcode in case encounter again + $styleHash = self::$cachedStyles['hashByObjId'][$objId] = $style->getHashCode(); + } + + // Find existing style by hash. + $existingStyle = self::$cachedStyles['styleByHash'][$styleHash] ?? null; + + if (!$existingStyle) { + // The old style combined with the new style array is not cached, so we create it now + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + + // Look for similar style in workbook to reduce memory usage + $existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode()); + + // Cache the new style by original hashcode + self::$cachedStyles['styleByHash'][$styleHash] = $existingStyle instanceof self ? $existingStyle : $newStyle; + } + } + + if ($existingStyle) { // there is already such cell Xf in our collection $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex(); } else { + if (!isset($newStyle)) { + // Handle bug in PHPStan, see https://github.com/phpstan/phpstan/issues/5805 + // $newStyle should always be defined. + // This block might not be needed in the future + $newStyle = clone $style; + $newStyle->applyFromArray($styleArray); + } + // we don't have such a cell Xf, need to add $workbook->addCellXf($newStyle); $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); @@ -405,25 +434,31 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) // Loop through columns, rows, or cells again and update the XF index switch ($selectionType) { case 'COLUMN': - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) { $columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col); $oldXfIndex = $columnDimension->getXfIndex(); $columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]); } + // Disable caching of styles + self::$cachedStyles = null; + break; case 'ROW': - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $rowDimension = $this->getActiveSheet()->getRowDimension($row); - $oldXfIndex = $rowDimension->getXfIndex() === null ? - 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style + // row without explicit style should be formatted based on default style + $oldXfIndex = $rowDimension->getXfIndex() ?? 0; $rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]); } + // Disable caching of styles + self::$cachedStyles = null; + break; case 'CELL': - for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { - for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) { + for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row); $oldXfIndex = $cell->getXfIndex(); $cell->setXfIndex($newXfIndexes[$oldXfIndex]); @@ -434,32 +469,83 @@ public function applyFromArray(array $pStyles, $pAdvanced = true) } } else { // not a supervisor, just apply the style array directly on style object - if (isset($pStyles['fill'])) { - $this->getFill()->applyFromArray($pStyles['fill']); + if (isset($styleArray['fill'])) { + $this->getFill()->applyFromArray($styleArray['fill']); } - if (isset($pStyles['font'])) { - $this->getFont()->applyFromArray($pStyles['font']); + if (isset($styleArray['font'])) { + $this->getFont()->applyFromArray($styleArray['font']); } - if (isset($pStyles['borders'])) { - $this->getBorders()->applyFromArray($pStyles['borders']); + if (isset($styleArray['borders'])) { + $this->getBorders()->applyFromArray($styleArray['borders']); } - if (isset($pStyles['alignment'])) { - $this->getAlignment()->applyFromArray($pStyles['alignment']); + if (isset($styleArray['alignment'])) { + $this->getAlignment()->applyFromArray($styleArray['alignment']); } - if (isset($pStyles['numberFormat'])) { - $this->getNumberFormat()->applyFromArray($pStyles['numberFormat']); + if (isset($styleArray['numberFormat'])) { + $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']); } - if (isset($pStyles['protection'])) { - $this->getProtection()->applyFromArray($pStyles['protection']); + if (isset($styleArray['protection'])) { + $this->getProtection()->applyFromArray($styleArray['protection']); } - if (isset($pStyles['quotePrefix'])) { - $this->quotePrefix = $pStyles['quotePrefix']; + if (isset($styleArray['quotePrefix'])) { + $this->quotePrefix = $styleArray['quotePrefix']; } } return $this; } + private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $styleArray): array + { + $oldXfIndexes = []; + switch ($selectionType) { + case 'COLUMN': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; + } + foreach ($this->getActiveSheet()->getColumnIterator($columnStart, $columnEnd) as $columnIterator) { + $cellIterator = $columnIterator->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(true); + foreach ($cellIterator as $columnCell) { + if ($columnCell !== null) { + $columnCell->getStyle()->applyFromArray($styleArray); + } + } + } + + break; + case 'ROW': + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() === null) { + $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style + } else { + $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; + } + } + foreach ($this->getActiveSheet()->getRowIterator((int) $rangeStart[1], (int) $rangeEnd[1]) as $rowIterator) { + $cellIterator = $rowIterator->getCellIterator(); + $cellIterator->setIterateOnlyExistingCells(true); + foreach ($cellIterator as $rowCell) { + if ($rowCell !== null) { + $rowCell->getStyle()->applyFromArray($styleArray); + } + } + } + + break; + case 'CELL': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; + } + } + + break; + } + + return $oldXfIndexes; + } + /** * Get Fill. * @@ -483,8 +569,6 @@ public function getFont() /** * Set font. * - * @param Font $font - * * @return $this */ public function setFont(Font $font) @@ -537,13 +621,13 @@ public function getConditionalStyles() /** * Set Conditional Styles. Only used on supervisor. * - * @param Conditional[] $pValue Array of conditional styles + * @param Conditional[] $conditionalStyleArray Array of conditional styles * * @return $this */ - public function setConditionalStyles(array $pValue) + public function setConditionalStyles(array $conditionalStyleArray) { - $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue); + $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray); return $this; } @@ -575,20 +659,20 @@ public function getQuotePrefix() /** * Set quote prefix. * - * @param bool $pValue + * @param bool $quotePrefix * * @return $this */ - public function setQuotePrefix($pValue) + public function setQuotePrefix($quotePrefix) { - if ($pValue == '') { - $pValue = false; + if ($quotePrefix == '') { + $quotePrefix = false; } if ($this->isSupervisor) { - $styleArray = ['quotePrefix' => $pValue]; + $styleArray = ['quotePrefix' => $quotePrefix]; $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { - $this->quotePrefix = (bool) $pValue; + $this->quotePrefix = (bool) $quotePrefix; } return $this; @@ -601,18 +685,12 @@ public function setQuotePrefix($pValue) */ public function getHashCode() { - $hashConditionals = ''; - foreach ($this->conditionalStyles as $conditional) { - $hashConditionals .= $conditional->getHashCode(); - } - return md5( $this->fill->getHashCode() . $this->font->getHashCode() . $this->borders->getHashCode() . $this->alignment->getHashCode() . $this->numberFormat->getHashCode() . - $hashConditionals . $this->protection->getHashCode() . ($this->quotePrefix ? 't' : 'f') . __CLASS__ @@ -632,10 +710,24 @@ public function getIndex() /** * Set own index in style collection. * - * @param int $pValue + * @param int $index */ - public function setIndex($pValue) + public function setIndex($index): void + { + $this->index = $index; + } + + protected function exportArray1(): array { - $this->index = $pValue; + $exportedArray = []; + $this->exportArray2($exportedArray, 'alignment', $this->getAlignment()); + $this->exportArray2($exportedArray, 'borders', $this->getBorders()); + $this->exportArray2($exportedArray, 'fill', $this->getFill()); + $this->exportArray2($exportedArray, 'font', $this->getFont()); + $this->exportArray2($exportedArray, 'numberFormat', $this->getNumberFormat()); + $this->exportArray2($exportedArray, 'protection', $this->getProtection()); + $this->exportArray2($exportedArray, 'quotePrefx', $this->getQuotePrefix()); + + return $exportedArray; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php index 1a700974..8a5c350d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php @@ -18,7 +18,7 @@ abstract class Supervisor implements IComparable /** * Parent. Only used for supervisor. * - * @var Spreadsheet|Style + * @var Spreadsheet|Supervisor */ protected $parent; @@ -45,7 +45,7 @@ public function __construct($isSupervisor = false) /** * Bind parent. Only used for supervisor. * - * @param Spreadsheet|Style $parent + * @param Spreadsheet|Supervisor $parent * @param null|string $parentPropertyName * * @return $this @@ -114,4 +114,62 @@ public function __clone() } } } + + /** + * Export style as array. + * + * Available to anything which extends this class: + * Alignment, Border, Borders, Color, Fill, Font, + * NumberFormat, Protection, and Style. + */ + final public function exportArray(): array + { + return $this->exportArray1(); + } + + /** + * Abstract method to be implemented in anything which + * extends this class. + * + * This method invokes exportArray2 with the names and values + * of all properties to be included in output array, + * returning that array to exportArray, then to caller. + */ + abstract protected function exportArray1(): array; + + /** + * Populate array from exportArray1. + * This method is available to anything which extends this class. + * The parameter index is the key to be added to the array. + * The parameter objOrValue is either a primitive type, + * which is the value added to the array, + * or a Style object to be recursively added via exportArray. + * + * @param mixed $objOrValue + */ + final protected function exportArray2(array &$exportedArray, string $index, $objOrValue): void + { + if ($objOrValue instanceof self) { + $exportedArray[$index] = $objOrValue->exportArray(); + } else { + $exportedArray[$index] = $objOrValue; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor. + * + * @return mixed + */ + abstract public function getSharedComponent(); + + /** + * Build style array from subcomponents. + * + * @param array $array + * + * @return array + */ + abstract public function getStyleArray($array); } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php index dcbc4da5..dd33d5d5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter.php @@ -2,19 +2,23 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use DateTime; +use DateTimeZone; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; -use PhpOffice\PhpSpreadsheet\Calculation\DateTime; use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; +use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; +use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; class AutoFilter { /** * Autofilter Worksheet. * - * @var Worksheet + * @var null|Worksheet */ private $workSheet; @@ -32,22 +36,41 @@ class AutoFilter */ private $columns = []; + /** @var bool */ + private $evaluated = false; + + public function getEvaluated(): bool + { + return $this->evaluated; + } + + public function setEvaluated(bool $value): void + { + $this->evaluated = $value; + } + /** * Create a new AutoFilter. * - * @param string $pRange Cell range (i.e. A1:E10) - * @param Worksheet $pSheet + * @param AddressRange|array|string $range + * A simple string containing a Cell range like 'A1:E10' is permitted + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. */ - public function __construct($pRange = '', Worksheet $pSheet = null) + public function __construct($range = '', ?Worksheet $worksheet = null) { - $this->range = $pRange; - $this->workSheet = $pSheet; + if ($range !== '') { + [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); + } + + $this->range = $range; + $this->workSheet = $worksheet; } /** * Get AutoFilter Parent Worksheet. * - * @return Worksheet + * @return null|Worksheet */ public function getParent() { @@ -57,13 +80,12 @@ public function getParent() /** * Set AutoFilter Parent Worksheet. * - * @param Worksheet $pSheet - * * @return $this */ - public function setParent(Worksheet $pSheet = null) + public function setParent(?Worksheet $worksheet = null) { - $this->workSheet = $pSheet; + $this->evaluated = false; + $this->workSheet = $worksheet; return $this; } @@ -79,38 +101,53 @@ public function getRange() } /** - * Set AutoFilter Range. + * Set AutoFilter Cell Range. * - * @param string $pRange Cell range (i.e. A1:E10) - * - * @throws PhpSpreadsheetException - * - * @return $this + * @param AddressRange|array|string $range + * A simple string containing a Cell range like 'A1:E10' is permitted + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. */ - public function setRange($pRange) + public function setRange($range = ''): self { + $this->evaluated = false; // extract coordinate - [$worksheet, $pRange] = Worksheet::extractSheetTitle($pRange, true); - - if (strpos($pRange, ':') !== false) { - $this->range = $pRange; - } elseif (empty($pRange)) { + if ($range !== '') { + [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); + } + if (empty($range)) { + // Discard all column rules + $this->columns = []; $this->range = ''; - } else { + + return $this; + } + + if (strpos($range, ':') === false) { throw new PhpSpreadsheetException('Autofilter must be set on a range of cells.'); } - if (empty($pRange)) { - // Discard all column rules - $this->columns = []; - } else { - // Discard any column rules that are no longer valid within this range - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); - foreach ($this->columns as $key => $value) { - $colIndex = Coordinate::columnIndexFromString($key); - if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { - unset($this->columns[$key]); - } + $this->range = $range; + // Discard any column rules that are no longer valid within this range + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + foreach ($this->columns as $key => $value) { + $colIndex = Coordinate::columnIndexFromString($key); + if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { + unset($this->columns[$key]); + } + } + + return $this; + } + + public function setRangeToMaxRow(): self + { + $this->evaluated = false; + if ($this->workSheet !== null) { + $thisrange = $this->range; + $range = preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange) ?? ''; + if ($range !== $thisrange) { + $this->setRange($range); } } @@ -132,8 +169,6 @@ public function getColumns() * * @param string $column Column name (e.g. A) * - * @throws PhpSpreadsheetException - * * @return int The column offset within the autofilter range */ public function testColumnInRange($column) @@ -154,50 +189,44 @@ public function testColumnInRange($column) /** * Get a specified AutoFilter Column Offset within the defined AutoFilter range. * - * @param string $pColumn Column name (e.g. A) - * - * @throws PhpSpreadsheetException + * @param string $column Column name (e.g. A) * * @return int The offset of the specified column within the autofilter range */ - public function getColumnOffset($pColumn) + public function getColumnOffset($column) { - return $this->testColumnInRange($pColumn); + return $this->testColumnInRange($column); } /** * Get a specified AutoFilter Column. * - * @param string $pColumn Column name (e.g. A) - * - * @throws PhpSpreadsheetException + * @param string $column Column name (e.g. A) * * @return AutoFilter\Column */ - public function getColumn($pColumn) + public function getColumn($column) { - $this->testColumnInRange($pColumn); + $this->testColumnInRange($column); - if (!isset($this->columns[$pColumn])) { - $this->columns[$pColumn] = new AutoFilter\Column($pColumn, $this); + if (!isset($this->columns[$column])) { + $this->columns[$column] = new AutoFilter\Column($column, $this); } - return $this->columns[$pColumn]; + return $this->columns[$column]; } /** * Get a specified AutoFilter Column by it's offset. * - * @param int $pColumnOffset Column offset within range (starting from 0) - * - * @throws PhpSpreadsheetException + * @param int $columnOffset Column offset within range (starting from 0) * * @return AutoFilter\Column */ - public function getColumnByOffset($pColumnOffset) + public function getColumnByOffset($columnOffset) { [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); - $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $pColumnOffset); + $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); return $this->getColumn($pColumn); } @@ -205,29 +234,28 @@ public function getColumnByOffset($pColumnOffset) /** * Set AutoFilter. * - * @param AutoFilter\Column|string $pColumn + * @param AutoFilter\Column|string $columnObjectOrString * A simple string containing a Column ID like 'A' is permitted * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setColumn($pColumn) + public function setColumn($columnObjectOrString) { - if ((is_string($pColumn)) && (!empty($pColumn))) { - $column = $pColumn; - } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) { - $column = $pColumn->getColumnIndex(); + $this->evaluated = false; + if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { + $column = $columnObjectOrString; + } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof AutoFilter\Column)) { + $column = $columnObjectOrString->getColumnIndex(); } else { throw new PhpSpreadsheetException('Column is not within the autofilter range.'); } $this->testColumnInRange($column); - if (is_string($pColumn)) { - $this->columns[$pColumn] = new AutoFilter\Column($pColumn, $this); - } elseif (is_object($pColumn) && ($pColumn instanceof AutoFilter\Column)) { - $pColumn->setParent($this); - $this->columns[$column] = $pColumn; + if (is_string($columnObjectOrString)) { + $this->columns[$columnObjectOrString] = new AutoFilter\Column($columnObjectOrString, $this); + } else { + $columnObjectOrString->setParent($this); + $this->columns[$column] = $columnObjectOrString; } ksort($this->columns); @@ -237,18 +265,17 @@ public function setColumn($pColumn) /** * Clear a specified AutoFilter Column. * - * @param string $pColumn Column name (e.g. A) - * - * @throws PhpSpreadsheetException + * @param string $column Column name (e.g. A) * * @return $this */ - public function clearColumn($pColumn) + public function clearColumn($column) { - $this->testColumnInRange($pColumn); + $this->evaluated = false; + $this->testColumnInRange($column); - if (isset($this->columns[$pColumn])) { - unset($this->columns[$pColumn]); + if (isset($this->columns[$column])) { + unset($this->columns[$column]); } return $this; @@ -268,6 +295,7 @@ public function clearColumn($pColumn) */ public function shiftColumn($fromColumn, $toColumn) { + $this->evaluated = false; $fromColumn = strtoupper($fromColumn); $toColumn = strtoupper($toColumn); @@ -318,20 +346,22 @@ private static function filterTestInDateGroupSet($cellValue, $dataSet) if (($cellValue == '') || ($cellValue === null)) { return $blanks; } + $timeZone = new DateTimeZone('UTC'); if (is_numeric($cellValue)) { - $dateValue = Date::excelToTimestamp($cellValue); + $dateTime = Date::excelToDateTimeObject((float) $cellValue, $timeZone); + $cellValue = (float) $cellValue; if ($cellValue < 1) { // Just the time part - $dtVal = date('His', $dateValue); + $dtVal = $dateTime->format('His'); $dateSet = $dateSet['time']; } elseif ($cellValue == floor($cellValue)) { // Just the date part - $dtVal = date('Ymd', $dateValue); + $dtVal = $dateTime->format('Ymd'); $dateSet = $dateSet['date']; } else { // date and time parts - $dtVal = date('YmdHis', $dateValue); + $dtVal = $dateTime->format('YmdHis'); $dateSet = $dateSet['dateTime']; } foreach ($dateSet as $dateValue) { @@ -355,6 +385,7 @@ private static function filterTestInDateGroupSet($cellValue, $dataSet) */ private static function filterTestInCustomDataSet($cellValue, $ruleSet) { + /** @var array[] */ $dataSet = $ruleSet['filterRules']; $join = $ruleSet['join']; $customRuleForBlanks = $ruleSet['customRuleForBlanks'] ?? false; @@ -367,43 +398,50 @@ private static function filterTestInCustomDataSet($cellValue, $ruleSet) } $returnVal = ($join == AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND); foreach ($dataSet as $rule) { + /** @var string */ + $ruleValue = $rule['value']; + /** @var string */ + $ruleOperator = $rule['operator']; + /** @var string */ + $cellValueString = $cellValue ?? ''; $retVal = false; - if (is_numeric($rule['value'])) { + if (is_numeric($ruleValue)) { // Numeric values are tested using the appropriate operator - switch ($rule['operator']) { - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: - $retVal = ($cellValue == $rule['value']); + $numericTest = is_numeric($cellValue); + switch ($ruleOperator) { + case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + $retVal = $numericTest && ($cellValue == $ruleValue); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: - $retVal = ($cellValue != $rule['value']); + case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + $retVal = !$numericTest || ($cellValue != $ruleValue); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: - $retVal = ($cellValue > $rule['value']); + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: + $retVal = $numericTest && ($cellValue > $ruleValue); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: - $retVal = ($cellValue >= $rule['value']); + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: + $retVal = $numericTest && ($cellValue >= $ruleValue); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: - $retVal = ($cellValue < $rule['value']); + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: + $retVal = $numericTest && ($cellValue < $ruleValue); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: - $retVal = ($cellValue <= $rule['value']); + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: + $retVal = $numericTest && ($cellValue <= $ruleValue); break; } - } elseif ($rule['value'] == '') { - switch ($rule['operator']) { - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + } elseif ($ruleValue == '') { + switch ($ruleOperator) { + case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: $retVal = (($cellValue == '') || ($cellValue === null)); break; - case AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: $retVal = (($cellValue != '') && ($cellValue !== null)); break; @@ -414,7 +452,32 @@ private static function filterTestInCustomDataSet($cellValue, $ruleSet) } } else { // String values are always tested for equality, factoring in for wildcards (hence a regexp test) - $retVal = preg_match('/^' . $rule['value'] . '$/i', $cellValue); + switch ($ruleOperator) { + case Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + $retVal = (bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString); + + break; + case Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + $retVal = !((bool) preg_match('/^' . $ruleValue . '$/i', $cellValueString)); + + break; + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: + $retVal = strcasecmp($cellValueString, $ruleValue) > 0; + + break; + case Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: + $retVal = strcasecmp($cellValueString, $ruleValue) >= 0; + + break; + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: + $retVal = strcasecmp($cellValueString, $ruleValue) < 0; + + break; + case Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: + $retVal = strcasecmp($cellValueString, $ruleValue) <= 0; + + break; + } } // If there are multiple conditions, then we need to test both using the appropriate join operator switch ($join) { @@ -453,7 +516,8 @@ private static function filterTestInPeriodDateSet($cellValue, $monthSet) } if (is_numeric($cellValue)) { - $dateValue = date('m', Date::excelToTimestamp($cellValue)); + $dateObject = Date::excelToDateTimeObject((float) $cellValue, new DateTimeZone('UTC')); + $dateValue = (int) $dateObject->format('m'); if (in_array($dateValue, $monthSet)) { return true; } @@ -462,165 +526,298 @@ private static function filterTestInPeriodDateSet($cellValue, $monthSet) return false; } - /** - * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching. - * - * @var array - */ - private static $fromReplace = ['\*', '\?', '~~', '~.*', '~.?']; + private static function makeDateObject(int $year, int $month, int $day, int $hour = 0, int $minute = 0, int $second = 0): DateTime + { + $baseDate = new DateTime(); + $baseDate->setDate($year, $month, $day); + $baseDate->setTime($hour, $minute, $second); - private static $toReplace = ['.*', '.', '~', '\*', '\?']; + return $baseDate; + } - /** - * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. - * - * @param string $dynamicRuleType - * @param AutoFilter\Column $filterColumn - * - * @return mixed[] - */ - private function dynamicFilterDateRange($dynamicRuleType, &$filterColumn) + private const DATE_FUNCTIONS = [ + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH => 'dynamicLastMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER => 'dynamicLastQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK => 'dynamicLastWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR => 'dynamicLastYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH => 'dynamicNextMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER => 'dynamicNextQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK => 'dynamicNextWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR => 'dynamicNextYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH => 'dynamicThisMonth', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER => 'dynamicThisQuarter', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK => 'dynamicThisWeek', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR => 'dynamicThisYear', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY => 'dynamicToday', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW => 'dynamicTomorrow', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE => 'dynamicYearToDate', + Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY => 'dynamicYesterday', + ]; + + private static function dynamicLastMonth(): array { - $rDateType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_PHP_NUMERIC); - $val = $maxVal = null; + $maxval = new DateTime(); + $year = (int) $maxval->format('Y'); + $month = (int) $maxval->format('m'); + $maxval->setDate($year, $month, 1); + $maxval->setTime(0, 0, 0); + $val = clone $maxval; + $val->modify('-1 month'); + + return [$val, $maxval]; + } - $ruleValues = []; - $baseDate = DateTime::DATENOW(); - // Calculate start/end dates for the required date range based on current date - switch ($dynamicRuleType) { - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: - $baseDate = strtotime('-7 days', $baseDate); + private static function firstDayOfQuarter(): DateTime + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $month = (int) $val->format('m'); + $month = 3 * intdiv($month - 1, 3) + 1; + $val->setDate($year, $month, 1); + $val->setTime(0, 0, 0); + + return $val; + } - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: - $baseDate = strtotime('-7 days', $baseDate); + private static function dynamicLastQuarter(): array + { + $maxval = self::firstDayOfQuarter(); + $val = clone $maxval; + $val->modify('-3 months'); - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: - $baseDate = strtotime('-1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + return [$val, $maxval]; + } - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: - $baseDate = strtotime('+1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + private static function dynamicLastWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $subtract = $dayOfWeek + 7; // revert to prior Sunday + $val->modify("-$subtract days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } + + private static function dynamicLastYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year - 1, 1, 1); + $maxval = self::makeDateObject($year, 1, 1); - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: - $baseDate = strtotime('-3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + return [$val, $maxval]; + } - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: - $baseDate = strtotime('+3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + private static function dynamicNextMonth(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $month = (int) $val->format('m'); + $val->setDate($year, $month, 1); + $val->setTime(0, 0, 0); + $val->modify('+1 month'); + $maxval = clone $val; + $maxval->modify('+1 month'); + + return [$val, $maxval]; + } - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: - $baseDate = strtotime('-1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + private static function dynamicNextQuarter(): array + { + $val = self::firstDayOfQuarter(); + $val->modify('+3 months'); + $maxval = clone $val; + $maxval->modify('+3 months'); - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: - $baseDate = strtotime('+1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + return [$val, $maxval]; + } - break; - } + private static function dynamicNextWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $add = 7 - $dayOfWeek; // move to next Sunday + $val->modify("+$add days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } - switch ($dynamicRuleType) { - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: - $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate)); - $val = (int) Date::PHPToExcel($baseDate); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE: - $maxVal = (int) Date::PHPtoExcel(strtotime('+1 day', $baseDate)); - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: - $maxVal = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: - $thisMonth = date('m', $baseDate); - $thisQuarter = floor(--$thisMonth / 3); - $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1 + $thisQuarter) * 3, date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1 + $thisQuarter * 3, date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: - $maxVal = (int) Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate))); - ++$maxVal; - $val = (int) Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); - - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: - $dayOfWeek = date('w', $baseDate); - $val = (int) Date::PHPToExcel($baseDate) - $dayOfWeek; - $maxVal = $val + 7; - - break; - } + private static function dynamicNextYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year + 1, 1, 1); + $maxval = self::makeDateObject($year + 2, 1, 1); + + return [$val, $maxval]; + } + + private static function dynamicThisMonth(): array + { + $baseDate = new DateTime(); + $baseDate->setTime(0, 0, 0); + $year = (int) $baseDate->format('Y'); + $month = (int) $baseDate->format('m'); + $val = self::makeDateObject($year, $month, 1); + $maxval = clone $val; + $maxval->modify('+1 month'); + + return [$val, $maxval]; + } + + private static function dynamicThisQuarter(): array + { + $val = self::firstDayOfQuarter(); + $maxval = clone $val; + $maxval->modify('+3 months'); + + return [$val, $maxval]; + } + + private static function dynamicThisWeek(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $dayOfWeek = (int) $val->format('w'); // Sunday is 0 + $subtract = $dayOfWeek; // revert to Sunday + $val->modify("-$subtract days"); + $maxval = clone $val; + $maxval->modify('+7 days'); + + return [$val, $maxval]; + } + + private static function dynamicThisYear(): array + { + $val = new DateTime(); + $year = (int) $val->format('Y'); + $val = self::makeDateObject($year, 1, 1); + $maxval = self::makeDateObject($year + 1, 1, 1); + + return [$val, $maxval]; + } + + private static function dynamicToday(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $maxval = clone $val; + $maxval->modify('+1 day'); - switch ($dynamicRuleType) { - // Adjust Today dates for Yesterday and Tomorrow - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: - --$maxVal; - --$val; + return [$val, $maxval]; + } + + private static function dynamicTomorrow(): array + { + $val = new DateTime(); + $val->setTime(0, 0, 0); + $val->modify('+1 day'); + $maxval = clone $val; + $maxval->modify('+1 day'); + + return [$val, $maxval]; + } + + private static function dynamicYearToDate(): array + { + $maxval = new DateTime(); + $maxval->setTime(0, 0, 0); + $val = self::makeDateObject((int) $maxval->format('Y'), 1, 1); + $maxval->modify('+1 day'); + + return [$val, $maxval]; + } - break; - case AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: - ++$maxVal; - ++$val; + private static function dynamicYesterday(): array + { + $maxval = new DateTime(); + $maxval->setTime(0, 0, 0); + $val = clone $maxval; + $val->modify('-1 day'); + + return [$val, $maxval]; + } - break; + /** + * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation. + * + * @param string $dynamicRuleType + * + * @return mixed[] + */ + private function dynamicFilterDateRange($dynamicRuleType, AutoFilter\Column &$filterColumn) + { + $ruleValues = []; + $callBack = [__CLASS__, self::DATE_FUNCTIONS[$dynamicRuleType]]; // What if not found? + // Calculate start/end dates for the required date range based on current date + // Val is lowest permitted value. + // Maxval is greater than highest permitted value + $val = $maxval = 0; + if (is_callable($callBack)) { + [$val, $maxval] = $callBack(); } + $val = Date::dateTimeToExcel($val); + $maxval = Date::dateTimeToExcel($maxval); // Set the filter column rule attributes ready for writing - $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxVal]); + $filterColumn->setAttributes(['val' => $val, 'maxVal' => $maxval]); // Set the rules for identifying rows for hide/show - $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; - $ruleValues[] = ['operator' => AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal]; - Functions::setReturnDateType($rDateType); + $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val]; + $ruleValues[] = ['operator' => Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxval]; return ['method' => 'filterTestInCustomDataSet', 'arguments' => ['filterRules' => $ruleValues, 'join' => AutoFilter\Column::AUTOFILTER_COLUMN_JOIN_AND]]; } + /** + * Apply the AutoFilter rules to the AutoFilter Range. + * + * @param string $columnID + * @param int $startRow + * @param int $endRow + * @param ?string $ruleType + * @param mixed $ruleValue + * + * @return mixed + */ private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) { $range = $columnID . $startRow . ':' . $columnID . $endRow; - $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); + $retVal = null; + if ($this->workSheet !== null) { + $dataValues = Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); + $dataValues = array_filter($dataValues); - $dataValues = array_filter($dataValues); - if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { - rsort($dataValues); - } else { - sort($dataValues); + if ($ruleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { + rsort($dataValues); + } else { + sort($dataValues); + } + + $slice = array_slice($dataValues, 0, $ruleValue); + + $retVal = array_pop($slice); } - return array_pop(array_slice($dataValues, 0, $ruleValue)); + return $retVal; } /** * Apply the AutoFilter rules to the AutoFilter Range. * - * @throws PhpSpreadsheetException - * * @return $this */ public function showHideRows() { + if ($this->workSheet === null) { + return $this; + } [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); // The heading row should always be visible @@ -644,7 +841,7 @@ public function showHideRows() if (count($ruleValues) != count($ruleDataSet)) { $blanks = true; } - if ($ruleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_FILTER) { + if ($ruleType == Rule::AUTOFILTER_RULETYPE_FILTER) { // Filter on absolute values $columnFilterTests[$columnID] = [ 'method' => 'filterTestInSimpleDataSet', @@ -658,30 +855,45 @@ public function showHideRows() 'dateTime' => [], ]; foreach ($ruleDataSet as $ruleValue) { + if (!is_array($ruleValue)) { + continue; + } $date = $time = ''; - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')) { - $date .= sprintf('%04d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '') + ) { + $date .= sprintf('%04d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); } - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')) { - $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '') + ) { + $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); } - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')) { - $date .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '') + ) { + $date .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); } - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '') + ) { + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); } - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '') + ) { + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); } - if ((isset($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && - ($ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')) { - $time .= sprintf('%02d', $ruleValue[AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); + if ( + (isset($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && + ($ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '') + ) { + $time .= sprintf('%02d', $ruleValue[Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); } $dateTime = $date . $time; $arguments['date'][] = $date; @@ -700,15 +912,14 @@ public function showHideRows() break; case AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: - $customRuleForBlanks = false; + $customRuleForBlanks = true; $ruleValues = []; // Build a list of the filter value selections foreach ($rules as $rule) { $ruleValue = $rule->getValue(); - if (!is_numeric($ruleValue)) { + if (!is_array($ruleValue) && !is_numeric($ruleValue)) { // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards - $ruleValue = preg_quote($ruleValue); - $ruleValue = str_replace(self::$fromReplace, self::$toReplace, $ruleValue); + $ruleValue = WildcardMatch::wildcard($ruleValue); if (trim($ruleValue) == '') { $customRuleForBlanks = true; $ruleValue = trim($ruleValue); @@ -728,16 +939,22 @@ public function showHideRows() foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $dynamicRuleType = $rule->getGrouping(); - if (($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || - ($dynamicRuleType == AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) { + if ( + ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || + ($dynamicRuleType == Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE) + ) { // Number (Average) based // Calculate the average $averageFormula = '=AVERAGE(' . $columnID . ($rangeStart[1] + 1) . ':' . $columnID . $rangeEnd[1] . ')'; - $average = Calculation::getInstance()->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); + $spreadsheet = ($this->workSheet === null) ? null : $this->workSheet->getParent(); + $average = Calculation::getInstance($spreadsheet)->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); + while (is_array($average)) { + $average = array_pop($average); + } // Set above/below rule based on greaterThan or LessTan - $operator = ($dynamicRuleType === AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) - ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN - : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; + $operator = ($dynamicRuleType === Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) + ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN + : Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; $ruleValues[] = [ 'operator' => $operator, 'value' => $average, @@ -779,27 +996,30 @@ public function showHideRows() case AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: $ruleValues = []; $dataRowCount = $rangeEnd[1] - $rangeStart[1]; + $toptenRuleType = null; + $ruleValue = 0; + $ruleOperator = null; foreach ($rules as $rule) { // We should only ever have one Dynamic Filter Rule anyway $toptenRuleType = $rule->getGrouping(); $ruleValue = $rule->getValue(); $ruleOperator = $rule->getOperator(); } - if ($ruleOperator === AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { - $ruleValue = floor($ruleValue * ($dataRowCount / 100)); + if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { + $ruleValue = floor((float) $ruleValue * ($dataRowCount / 100)); } - if ($ruleValue < 1) { + if (!is_array($ruleValue) && $ruleValue < 1) { $ruleValue = 1; } - if ($ruleValue > 500) { + if (!is_array($ruleValue) && $ruleValue > 500) { $ruleValue = 500; } - $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, $rangeEnd[1], $toptenRuleType, $ruleValue); + $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue); - $operator = ($toptenRuleType == AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) - ? AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL - : AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; + $operator = ($toptenRuleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) + ? Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL + : Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; $ruleValues[] = ['operator' => $operator, 'value' => $maxVal]; $columnFilterTests[$columnID] = [ 'method' => 'filterTestInCustomDataSet', @@ -817,19 +1037,18 @@ public function showHideRows() foreach ($columnFilterTests as $columnID => $columnFilterTest) { $cellValue = $this->workSheet->getCell($columnID . $row)->getCalculatedValue(); // Execute the filter test - $result = $result && - call_user_func_array( - [self::class, $columnFilterTest['method']], - [$cellValue, $columnFilterTest['arguments']] - ); + $result = // $result && // phpstan says $result is always true here + // @phpstan-ignore-next-line + call_user_func_array([self::class, $columnFilterTest['method']], [$cellValue, $columnFilterTest['arguments']]); // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests if (!$result) { break; } } // Set show/hide for the row based on the result of the autoFilter result - $this->workSheet->getRowDimension($row)->setVisible($result); + $this->workSheet->getRowDimension((int) $row)->setVisible($result); } + $this->evaluated = true; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php index 3ed7270a..076292f3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php @@ -49,7 +49,7 @@ class Column /** * Autofilter. * - * @var AutoFilter + * @var null|AutoFilter */ private $parent; @@ -77,27 +77,34 @@ class Column /** * Autofilter Column Rules. * - * @var array of Column\Rule + * @var Column\Rule[] */ private $ruleset = []; /** * Autofilter Column Dynamic Attributes. * - * @var array of mixed + * @var mixed[] */ private $attributes = []; /** * Create a new Column. * - * @param string $pColumn Column (e.g. A) - * @param AutoFilter $pParent Autofilter for this column + * @param string $column Column (e.g. A) + * @param AutoFilter $parent Autofilter for this column */ - public function __construct($pColumn, AutoFilter $pParent = null) + public function __construct($column, ?AutoFilter $parent = null) { - $this->columnIndex = $pColumn; - $this->parent = $pParent; + $this->columnIndex = $column; + $this->parent = $parent; + } + + public function setEvaluatedFalse(): void + { + if ($this->parent !== null) { + $this->parent->setEvaluated(false); + } } /** @@ -113,21 +120,20 @@ public function getColumnIndex() /** * Set AutoFilter column index as string eg: 'A'. * - * @param string $pColumn Column (e.g. A) - * - * @throws PhpSpreadsheetException + * @param string $column Column (e.g. A) * * @return $this */ - public function setColumnIndex($pColumn) + public function setColumnIndex($column) { + $this->setEvaluatedFalse(); // Uppercase coordinate - $pColumn = strtoupper($pColumn); + $column = strtoupper($column); if ($this->parent !== null) { - $this->parent->testColumnInRange($pColumn); + $this->parent->testColumnInRange($column); } - $this->columnIndex = $pColumn; + $this->columnIndex = $column; return $this; } @@ -135,7 +141,7 @@ public function setColumnIndex($pColumn) /** * Get this Column's AutoFilter Parent. * - * @return AutoFilter + * @return null|AutoFilter */ public function getParent() { @@ -145,13 +151,12 @@ public function getParent() /** * Set this Column's AutoFilter Parent. * - * @param AutoFilter $pParent - * * @return $this */ - public function setParent(AutoFilter $pParent = null) + public function setParent(?AutoFilter $parent = null) { - $this->parent = $pParent; + $this->setEvaluatedFalse(); + $this->parent = $parent; return $this; } @@ -169,19 +174,21 @@ public function getFilterType() /** * Set AutoFilter Type. * - * @param string $pFilterType - * - * @throws PhpSpreadsheetException + * @param string $filterType * * @return $this */ - public function setFilterType($pFilterType) + public function setFilterType($filterType) { - if (!in_array($pFilterType, self::$filterTypes)) { + $this->setEvaluatedFalse(); + if (!in_array($filterType, self::$filterTypes)) { throw new PhpSpreadsheetException('Invalid filter type for column AutoFilter.'); } + if ($filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) > 2) { + throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); + } - $this->filterType = $pFilterType; + $this->filterType = $filterType; return $this; } @@ -199,21 +206,20 @@ public function getJoin() /** * Set AutoFilter Multiple Rules And/Or. * - * @param string $pJoin And/Or - * - * @throws PhpSpreadsheetException + * @param string $join And/Or * * @return $this */ - public function setJoin($pJoin) + public function setJoin($join) { + $this->setEvaluatedFalse(); // Lowercase And/Or - $pJoin = strtolower($pJoin); - if (!in_array($pJoin, self::$ruleJoins)) { + $join = strtolower($join); + if (!in_array($join, self::$ruleJoins)) { throw new PhpSpreadsheetException('Invalid rule connection for column AutoFilter.'); } - $this->join = $pJoin; + $this->join = $join; return $this; } @@ -221,12 +227,13 @@ public function setJoin($pJoin) /** * Set AutoFilter Attributes. * - * @param string[] $attributes + * @param mixed[] $attributes * * @return $this */ - public function setAttributes(array $attributes) + public function setAttributes($attributes) { + $this->setEvaluatedFalse(); $this->attributes = $attributes; return $this; @@ -235,14 +242,15 @@ public function setAttributes(array $attributes) /** * Set An AutoFilter Attribute. * - * @param string $pName Attribute Name - * @param string $pValue Attribute Value + * @param string $name Attribute Name + * @param int|string $value Attribute Value * * @return $this */ - public function setAttribute($pName, $pValue) + public function setAttribute($name, $value) { - $this->attributes[$pName] = $pValue; + $this->setEvaluatedFalse(); + $this->attributes[$name] = $value; return $this; } @@ -250,7 +258,7 @@ public function setAttribute($pName, $pValue) /** * Get AutoFilter Column Attributes. * - * @return string[] + * @return int[]|string[] */ public function getAttributes() { @@ -260,19 +268,24 @@ public function getAttributes() /** * Get specific AutoFilter Column Attribute. * - * @param string $pName Attribute Name + * @param string $name Attribute Name * - * @return string + * @return null|int|string */ - public function getAttribute($pName) + public function getAttribute($name) { - if (isset($this->attributes[$pName])) { - return $this->attributes[$pName]; + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; } return null; } + public function ruleCount(): int + { + return count($this->ruleset); + } + /** * Get all AutoFilter Column Rules. * @@ -286,17 +299,17 @@ public function getRules() /** * Get a specified AutoFilter Column Rule. * - * @param int $pIndex Rule index in the ruleset array + * @param int $index Rule index in the ruleset array * * @return Column\Rule */ - public function getRule($pIndex) + public function getRule($index) { - if (!isset($this->ruleset[$pIndex])) { - $this->ruleset[$pIndex] = new Column\Rule($this); + if (!isset($this->ruleset[$index])) { + $this->ruleset[$index] = new Column\Rule($this); } - return $this->ruleset[$pIndex]; + return $this->ruleset[$index]; } /** @@ -306,6 +319,10 @@ public function getRule($pIndex) */ public function createRule() { + $this->setEvaluatedFalse(); + if ($this->filterType === self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER && count($this->ruleset) >= 2) { + throw new PhpSpreadsheetException('No more than 2 rules are allowed in a Custom Filter'); + } $this->ruleset[] = new Column\Rule($this); return end($this->ruleset); @@ -314,14 +331,13 @@ public function createRule() /** * Add a new AutoFilter Column Rule to the ruleset. * - * @param Column\Rule $pRule - * * @return $this */ - public function addRule(Column\Rule $pRule) + public function addRule(Column\Rule $rule) { - $pRule->setParent($this); - $this->ruleset[] = $pRule; + $this->setEvaluatedFalse(); + $rule->setParent($this); + $this->ruleset[] = $rule; return $this; } @@ -330,14 +346,15 @@ public function addRule(Column\Rule $pRule) * Delete a specified AutoFilter Column Rule * If the number of rules is reduced to 1, then we reset And/Or logic to Or. * - * @param int $pIndex Rule index in the ruleset array + * @param int $index Rule index in the ruleset array * * @return $this */ - public function deleteRule($pIndex) + public function deleteRule($index) { - if (isset($this->ruleset[$pIndex])) { - unset($this->ruleset[$pIndex]); + $this->setEvaluatedFalse(); + if (isset($this->ruleset[$index])) { + unset($this->ruleset[$index]); // If we've just deleted down to a single rule, then reset And/Or joining to Or if (count($this->ruleset) <= 1) { $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); @@ -354,6 +371,7 @@ public function deleteRule($pIndex) */ public function clearRules() { + $this->setEvaluatedFalse(); $this->ruleset = []; $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); @@ -378,8 +396,6 @@ public function __clone() $cloned->setParent($this); // attach the new cloned Rule to this new cloned Autofilter Cloned object $this->ruleset[$k] = $cloned; } - } elseif (is_object($value)) { - $this->$key = clone $value; } else { $this->$key = $value; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php index 09a2bacd..408dfb3f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/AutoFilter/Column/Rule.php @@ -13,7 +13,7 @@ class Rule const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; - private static $ruleTypes = [ + private const RULE_TYPES = [ // Currently we're not handling // colorFilter // extLst @@ -32,7 +32,7 @@ class Rule const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; - private static $dateTimeGroups = [ + private const DATE_TIME_GROUPS = [ self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, @@ -88,7 +88,7 @@ class Rule const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; - private static $dynamicTypes = [ + private const DYNAMIC_TYPES = [ self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, @@ -125,15 +125,7 @@ class Rule self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, ]; - /* - * The only valid filter rule operators for filter and customFilter types are: - * - * - * - * - * - * - */ + // Filter rule operators for filter and customFilter types. const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; @@ -141,7 +133,7 @@ class Rule const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; - private static $operators = [ + private const OPERATORS = [ self::AUTOFILTER_COLUMN_RULE_EQUAL, self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, @@ -153,7 +145,7 @@ class Rule const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; - private static $topTenValue = [ + private const TOP_TEN_VALUE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, ]; @@ -161,49 +153,27 @@ class Rule const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; - private static $topTenType = [ + private const TOP_TEN_TYPE = [ self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, ]; - // Rule Operators (Numeric, Boolean etc) -// const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 + // Unimplented Rule Operators (Numeric, Boolean etc) + // const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 // Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values -// const AUTOFILTER_COLUMN_RULE_TOPTEN = 'topTen'; // greaterThan calculated value -// const AUTOFILTER_COLUMN_RULE_TOPTENPERCENT = 'topTenPercent'; // greaterThan calculated value -// const AUTOFILTER_COLUMN_RULE_ABOVEAVERAGE = 'aboveAverage'; // Value is calculated as the average -// const AUTOFILTER_COLUMN_RULE_BELOWAVERAGE = 'belowAverage'; // Value is calculated as the average // Rule Operators (String) which are set as wild-carded values -// const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* -// const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z -// const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* -// const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* + // const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* + // const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z + // const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* + // const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* // Rule Operators (Date Special) which are translated to standard numeric operators with calculated values -// const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; -// const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; -// const AUTOFILTER_COLUMN_RULE_YESTERDAY = 'yesterday'; -// const AUTOFILTER_COLUMN_RULE_TODAY = 'today'; -// const AUTOFILTER_COLUMN_RULE_TOMORROW = 'tomorrow'; -// const AUTOFILTER_COLUMN_RULE_LASTWEEK = 'lastWeek'; -// const AUTOFILTER_COLUMN_RULE_THISWEEK = 'thisWeek'; -// const AUTOFILTER_COLUMN_RULE_NEXTWEEK = 'nextWeek'; -// const AUTOFILTER_COLUMN_RULE_LASTMONTH = 'lastMonth'; -// const AUTOFILTER_COLUMN_RULE_THISMONTH = 'thisMonth'; -// const AUTOFILTER_COLUMN_RULE_NEXTMONTH = 'nextMonth'; -// const AUTOFILTER_COLUMN_RULE_LASTQUARTER = 'lastQuarter'; -// const AUTOFILTER_COLUMN_RULE_THISQUARTER = 'thisQuarter'; -// const AUTOFILTER_COLUMN_RULE_NEXTQUARTER = 'nextQuarter'; -// const AUTOFILTER_COLUMN_RULE_LASTYEAR = 'lastYear'; -// const AUTOFILTER_COLUMN_RULE_THISYEAR = 'thisYear'; -// const AUTOFILTER_COLUMN_RULE_NEXTYEAR = 'nextYear'; -// const AUTOFILTER_COLUMN_RULE_YEARTODATE = 'yearToDate'; // -// const AUTOFILTER_COLUMN_RULE_ALLDATESINMONTH = 'allDatesInMonth'; // for Month/February -// const AUTOFILTER_COLUMN_RULE_ALLDATESINQUARTER = 'allDatesInQuarter'; // for Quarter 2 + // const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; + // const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; /** * Autofilter Column. * - * @var Column + * @var ?Column */ private $parent; @@ -217,7 +187,7 @@ class Rule /** * Autofilter Rule Value. * - * @var string + * @var int|int[]|string|string[] */ private $value = ''; @@ -237,12 +207,17 @@ class Rule /** * Create a new Rule. - * - * @param Column $pParent */ - public function __construct(Column $pParent = null) + public function __construct(?Column $parent = null) + { + $this->parent = $parent; + } + + private function setEvaluatedFalse(): void { - $this->parent = $pParent; + if ($this->parent !== null) { + $this->parent->setEvaluatedFalse(); + } } /** @@ -258,19 +233,18 @@ public function getRuleType() /** * Set AutoFilter Rule Type. * - * @param string $pRuleType see self::AUTOFILTER_RULETYPE_* - * - * @throws PhpSpreadsheetException + * @param string $ruleType see self::AUTOFILTER_RULETYPE_* * * @return $this */ - public function setRuleType($pRuleType) + public function setRuleType($ruleType) { - if (!in_array($pRuleType, self::$ruleTypes)) { + $this->setEvaluatedFalse(); + if (!in_array($ruleType, self::RULE_TYPES)) { throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); } - $this->ruleType = $pRuleType; + $this->ruleType = $ruleType; return $this; } @@ -278,7 +252,7 @@ public function setRuleType($pRuleType) /** * Get AutoFilter Rule Value. * - * @return string + * @return int|int[]|string|string[] */ public function getValue() { @@ -288,33 +262,32 @@ public function getValue() /** * Set AutoFilter Rule Value. * - * @param string|string[] $pValue - * - * @throws PhpSpreadsheetException + * @param int|int[]|string|string[] $value * * @return $this */ - public function setValue($pValue) + public function setValue($value) { - if (is_array($pValue)) { + $this->setEvaluatedFalse(); + if (is_array($value)) { $grouping = -1; - foreach ($pValue as $key => $value) { + foreach ($value as $key => $v) { // Validate array entries - if (!in_array($key, self::$dateTimeGroups)) { + if (!in_array($key, self::DATE_TIME_GROUPS)) { // Remove any invalid entries from the value array - unset($pValue[$key]); + unset($value[$key]); } else { // Work out what the dateTime grouping will be - $grouping = max($grouping, array_search($key, self::$dateTimeGroups)); + $grouping = max($grouping, array_search($key, self::DATE_TIME_GROUPS)); } } - if (count($pValue) == 0) { + if (count($value) == 0) { throw new PhpSpreadsheetException('Invalid rule value for column AutoFilter Rule.'); } // Set the dateTime grouping that we've anticipated - $this->setGrouping(self::$dateTimeGroups[$grouping]); + $this->setGrouping(self::DATE_TIME_GROUPS[$grouping]); } - $this->value = $pValue; + $this->value = $value; return $this; } @@ -332,22 +305,23 @@ public function getOperator() /** * Set AutoFilter Rule Operator. * - * @param string $pOperator see self::AUTOFILTER_COLUMN_RULE_* - * - * @throws PhpSpreadsheetException + * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* * * @return $this */ - public function setOperator($pOperator) + public function setOperator($operator) { - if (empty($pOperator)) { - $pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL; + $this->setEvaluatedFalse(); + if (empty($operator)) { + $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; } - if ((!in_array($pOperator, self::$operators)) && - (!in_array($pOperator, self::$topTenValue))) { + if ( + (!in_array($operator, self::OPERATORS)) && + (!in_array($operator, self::TOP_TEN_VALUE)) + ) { throw new PhpSpreadsheetException('Invalid operator for column AutoFilter Rule.'); } - $this->operator = $pOperator; + $this->operator = $operator; return $this; } @@ -365,21 +339,22 @@ public function getGrouping() /** * Set AutoFilter Rule Grouping. * - * @param string $pGrouping - * - * @throws PhpSpreadsheetException + * @param string $grouping * * @return $this */ - public function setGrouping($pGrouping) + public function setGrouping($grouping) { - if (($pGrouping !== null) && - (!in_array($pGrouping, self::$dateTimeGroups)) && - (!in_array($pGrouping, self::$dynamicTypes)) && - (!in_array($pGrouping, self::$topTenType))) { - throw new PhpSpreadsheetException('Invalid rule type for column AutoFilter Rule.'); + $this->setEvaluatedFalse(); + if ( + ($grouping !== null) && + (!in_array($grouping, self::DATE_TIME_GROUPS)) && + (!in_array($grouping, self::DYNAMIC_TYPES)) && + (!in_array($grouping, self::TOP_TEN_TYPE)) + ) { + throw new PhpSpreadsheetException('Invalid grouping for column AutoFilter Rule.'); } - $this->grouping = $pGrouping; + $this->grouping = $grouping; return $this; } @@ -387,23 +362,22 @@ public function setGrouping($pGrouping) /** * Set AutoFilter Rule. * - * @param string $pOperator see self::AUTOFILTER_COLUMN_RULE_* - * @param string|string[] $pValue - * @param string $pGrouping - * - * @throws PhpSpreadsheetException + * @param string $operator see self::AUTOFILTER_COLUMN_RULE_* + * @param int|int[]|string|string[] $value + * @param string $grouping * * @return $this */ - public function setRule($pOperator, $pValue, $pGrouping = null) + public function setRule($operator, $value, $grouping = null) { - $this->setOperator($pOperator); - $this->setValue($pValue); + $this->setEvaluatedFalse(); + $this->setOperator($operator); + $this->setValue($value); // Only set grouping if it's been passed in as a user-supplied argument, // otherwise we're calculating it when we setValue() and don't want to overwrite that // If the user supplies an argumnet for grouping, then on their own head be it - if ($pGrouping !== null) { - $this->setGrouping($pGrouping); + if ($grouping !== null) { + $this->setGrouping($grouping); } return $this; @@ -412,7 +386,7 @@ public function setRule($pOperator, $pValue, $pGrouping = null) /** * Get this Rule's AutoFilter Column Parent. * - * @return Column + * @return ?Column */ public function getParent() { @@ -422,13 +396,12 @@ public function getParent() /** * Set this Rule's AutoFilter Column Parent. * - * @param Column $pParent - * * @return $this */ - public function setParent(Column $pParent = null) + public function setParent(?Column $parent = null) { - $this->parent = $pParent; + $this->setEvaluatedFalse(); + $this->parent = $parent; return $this; } @@ -441,11 +414,9 @@ public function __clone() $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { - if ($key == 'parent') { + if ($key == 'parent') { // this is only object // Detach from autofilter column parent $this->$key = null; - } else { - $this->$key = clone $value; } } else { $this->$key = $value; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php index 7d24e449..815536b5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/BaseDrawing.php @@ -8,6 +8,22 @@ class BaseDrawing implements IComparable { + const EDIT_AS_ABSOLUTE = 'absolute'; + const EDIT_AS_ONECELL = 'onecell'; + const EDIT_AS_TWOCELL = 'twocell'; + private const VALID_EDIT_AS = [ + self::EDIT_AS_ABSOLUTE, + self::EDIT_AS_ONECELL, + self::EDIT_AS_TWOCELL, + ]; + + /** + * The editAs attribute, used only with two cell anchor. + * + * @var string + */ + protected $editAs = ''; + /** * Image counter. * @@ -27,19 +43,19 @@ class BaseDrawing implements IComparable * * @var string */ - protected $name; + protected $name = ''; /** * Description. * * @var string */ - protected $description; + protected $description = ''; /** * Worksheet. * - * @var Worksheet + * @var null|Worksheet */ protected $worksheet; @@ -48,49 +64,84 @@ class BaseDrawing implements IComparable * * @var string */ - protected $coordinates; + protected $coordinates = 'A1'; /** * Offset X. * * @var int */ - protected $offsetX; + protected $offsetX = 0; /** * Offset Y. * * @var int */ - protected $offsetY; + protected $offsetY = 0; + + /** + * Coordinates2. + * + * @var string + */ + protected $coordinates2 = ''; + + /** + * Offset X2. + * + * @var int + */ + protected $offsetX2 = 0; + + /** + * Offset Y2. + * + * @var int + */ + protected $offsetY2 = 0; /** * Width. * * @var int */ - protected $width; + protected $width = 0; /** * Height. * * @var int */ - protected $height; + protected $height = 0; + + /** + * Pixel width of image. See $width for the size the Drawing will be in the sheet. + * + * @var int + */ + protected $imageWidth = 0; + + /** + * Pixel width of image. See $height for the size the Drawing will be in the sheet. + * + * @var int + */ + protected $imageHeight = 0; /** * Proportional resize. * * @var bool */ - protected $resizeProportional; + protected $resizeProportional = true; /** * Rotation. * * @var int */ - protected $rotation; + protected $rotation = 0; /** * Shadow. @@ -106,93 +157,56 @@ class BaseDrawing implements IComparable */ private $hyperlink; + /** + * Image type. + * + * @var int + */ + protected $type = IMAGETYPE_UNKNOWN; + /** * Create a new BaseDrawing. */ public function __construct() { // Initialise values - $this->name = ''; - $this->description = ''; - $this->worksheet = null; - $this->coordinates = 'A1'; - $this->offsetX = 0; - $this->offsetY = 0; - $this->width = 0; - $this->height = 0; - $this->resizeProportional = true; - $this->rotation = 0; - $this->shadow = new Drawing\Shadow(); + $this->setShadow(); // Set image index ++self::$imageCounter; $this->imageIndex = self::$imageCounter; } - /** - * Get image index. - * - * @return int - */ - public function getImageIndex() + public function getImageIndex(): int { return $this->imageIndex; } - /** - * Get Name. - * - * @return string - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * Set Name. - * - * @param string $pValue - * - * @return $this - */ - public function setName($pValue) + public function setName(string $name): self { - $this->name = $pValue; + $this->name = $name; return $this; } - /** - * Get Description. - * - * @return string - */ - public function getDescription() + public function getDescription(): string { return $this->description; } - /** - * Set Description. - * - * @param string $description - * - * @return $this - */ - public function setDescription($description) + public function setDescription(string $description): self { $this->description = $description; return $this; } - /** - * Get Worksheet. - * - * @return Worksheet - */ - public function getWorksheet() + public function getWorksheet(): ?Worksheet { return $this->worksheet; } @@ -200,27 +214,24 @@ public function getWorksheet() /** * Set Worksheet. * - * @param Worksheet $pValue - * @param bool $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? - * - * @throws PhpSpreadsheetException - * - * @return $this + * @param bool $overrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? */ - public function setWorksheet(Worksheet $pValue = null, $pOverrideOld = false) + public function setWorksheet(?Worksheet $worksheet = null, bool $overrideOld = false): self { if ($this->worksheet === null) { // Add drawing to \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet - $this->worksheet = $pValue; - $this->worksheet->getCell($this->coordinates); - $this->worksheet->getDrawingCollection()->append($this); + if ($worksheet !== null) { + $this->worksheet = $worksheet; + $this->worksheet->getCell($this->coordinates); + $this->worksheet->getDrawingCollection()->append($this); + } } else { - if ($pOverrideOld) { + if ($overrideOld) { // Remove drawing from old \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $iterator = $this->worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { - if ($iterator->current()->getHashCode() == $this->getHashCode()) { + if ($iterator->current()->getHashCode() === $this->getHashCode()) { $this->worksheet->getDrawingCollection()->offsetUnset($iterator->key()); $this->worksheet = null; @@ -229,7 +240,7 @@ public function setWorksheet(Worksheet $pValue = null, $pOverrideOld = false) } // Set new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet - $this->setWorksheet($pValue); + $this->setWorksheet($worksheet); } else { throw new PhpSpreadsheetException('A Worksheet has already been assigned. Drawings can only exist on one \\PhpOffice\\PhpSpreadsheet\\Worksheet.'); } @@ -238,136 +249,112 @@ public function setWorksheet(Worksheet $pValue = null, $pOverrideOld = false) return $this; } - /** - * Get Coordinates. - * - * @return string - */ - public function getCoordinates() + public function getCoordinates(): string { return $this->coordinates; } - /** - * Set Coordinates. - * - * @param string $pValue eg: 'A1' - * - * @return $this - */ - public function setCoordinates($pValue) + public function setCoordinates(string $coordinates): self { - $this->coordinates = $pValue; + $this->coordinates = $coordinates; return $this; } - /** - * Get OffsetX. - * - * @return int - */ - public function getOffsetX() + public function getOffsetX(): int { return $this->offsetX; } - /** - * Set OffsetX. - * - * @param int $pValue - * - * @return $this - */ - public function setOffsetX($pValue) + public function setOffsetX(int $offsetX): self { - $this->offsetX = $pValue; + $this->offsetX = $offsetX; return $this; } - /** - * Get OffsetY. - * - * @return int - */ - public function getOffsetY() + public function getOffsetY(): int { return $this->offsetY; } - /** - * Set OffsetY. - * - * @param int $pValue - * - * @return $this - */ - public function setOffsetY($pValue) + public function setOffsetY(int $offsetY): self { - $this->offsetY = $pValue; + $this->offsetY = $offsetY; return $this; } - /** - * Get Width. - * - * @return int - */ - public function getWidth() + public function getCoordinates2(): string + { + return $this->coordinates2; + } + + public function setCoordinates2(string $coordinates2): self + { + $this->coordinates2 = $coordinates2; + + return $this; + } + + public function getOffsetX2(): int + { + return $this->offsetX2; + } + + public function setOffsetX2(int $offsetX2): self + { + $this->offsetX2 = $offsetX2; + + return $this; + } + + public function getOffsetY2(): int + { + return $this->offsetY2; + } + + public function setOffsetY2(int $offsetY2): self + { + $this->offsetY2 = $offsetY2; + + return $this; + } + + public function getWidth(): int { return $this->width; } - /** - * Set Width. - * - * @param int $pValue - * - * @return $this - */ - public function setWidth($pValue) + public function setWidth(int $width): self { // Resize proportional? - if ($this->resizeProportional && $pValue != 0) { + if ($this->resizeProportional && $width != 0) { $ratio = $this->height / ($this->width != 0 ? $this->width : 1); - $this->height = round($ratio * $pValue); + $this->height = (int) round($ratio * $width); } // Set width - $this->width = $pValue; + $this->width = $width; return $this; } - /** - * Get Height. - * - * @return int - */ - public function getHeight() + public function getHeight(): int { return $this->height; } - /** - * Set Height. - * - * @param int $pValue - * - * @return $this - */ - public function setHeight($pValue) + public function setHeight(int $height): self { // Resize proportional? - if ($this->resizeProportional && $pValue != 0) { + if ($this->resizeProportional && $height != 0) { $ratio = $this->width / ($this->height != 0 ? $this->height : 1); - $this->width = round($ratio * $pValue); + $this->width = (int) round($ratio * $height); } // Set height - $this->height = $pValue; + $this->height = $height; return $this; } @@ -382,22 +369,17 @@ public function setHeight($pValue) * * * @author Vincent@luo MSN:kele_100@hotmail.com - * - * @param int $width - * @param int $height - * - * @return $this */ - public function setWidthAndHeight($width, $height) + public function setWidthAndHeight(int $width, int $height): self { $xratio = $width / ($this->width != 0 ? $this->width : 1); $yratio = $height / ($this->height != 0 ? $this->height : 1); if ($this->resizeProportional && !($width == 0 || $height == 0)) { if (($xratio * $this->height) < $height) { - $this->height = ceil($xratio * $this->height); + $this->height = (int) ceil($xratio * $this->height); $this->width = $width; } else { - $this->width = ceil($yratio * $this->width); + $this->width = (int) ceil($yratio * $this->width); $this->height = $height; } } else { @@ -408,74 +390,38 @@ public function setWidthAndHeight($width, $height) return $this; } - /** - * Get ResizeProportional. - * - * @return bool - */ - public function getResizeProportional() + public function getResizeProportional(): bool { return $this->resizeProportional; } - /** - * Set ResizeProportional. - * - * @param bool $pValue - * - * @return $this - */ - public function setResizeProportional($pValue) + public function setResizeProportional(bool $resizeProportional): self { - $this->resizeProportional = $pValue; + $this->resizeProportional = $resizeProportional; return $this; } - /** - * Get Rotation. - * - * @return int - */ - public function getRotation() + public function getRotation(): int { return $this->rotation; } - /** - * Set Rotation. - * - * @param int $pValue - * - * @return $this - */ - public function setRotation($pValue) + public function setRotation(int $rotation): self { - $this->rotation = $pValue; + $this->rotation = $rotation; return $this; } - /** - * Get Shadow. - * - * @return Drawing\Shadow - */ - public function getShadow() + public function getShadow(): Drawing\Shadow { return $this->shadow; } - /** - * Set Shadow. - * - * @param Drawing\Shadow $pValue - * - * @return $this - */ - public function setShadow(Drawing\Shadow $pValue = null) + public function setShadow(?Drawing\Shadow $shadow = null): self { - $this->shadow = $pValue; + $this->shadow = $shadow ?? new Drawing\Shadow(); return $this; } @@ -490,10 +436,13 @@ public function getHashCode() return md5( $this->name . $this->description . - $this->worksheet->getHashCode() . + (($this->worksheet === null) ? '' : $this->worksheet->getHashCode()) . $this->coordinates . $this->offsetX . $this->offsetY . + $this->coordinates2 . + $this->offsetX2 . + $this->offsetY2 . $this->width . $this->height . $this->rotation . @@ -519,19 +468,68 @@ public function __clone() } } + public function setHyperlink(?Hyperlink $hyperlink = null): void + { + $this->hyperlink = $hyperlink; + } + + public function getHyperlink(): ?Hyperlink + { + return $this->hyperlink; + } + /** - * @param null|Hyperlink $pHyperlink + * Set Fact Sizes and Type of Image. */ - public function setHyperlink(Hyperlink $pHyperlink = null) + protected function setSizesAndType(string $path): void { - $this->hyperlink = $pHyperlink; + if ($this->imageWidth === 0 && $this->imageHeight === 0 && $this->type === IMAGETYPE_UNKNOWN) { + $imageData = getimagesize($path); + + if (is_array($imageData)) { + $this->imageWidth = $imageData[0]; + $this->imageHeight = $imageData[1]; + $this->type = $imageData[2]; + } + } + if ($this->width === 0 && $this->height === 0) { + $this->width = $this->imageWidth; + $this->height = $this->imageHeight; + } } /** - * @return null|Hyperlink + * Get Image Type. */ - public function getHyperlink() + public function getType(): int { - return $this->hyperlink; + return $this->type; + } + + public function getImageWidth(): int + { + return $this->imageWidth; + } + + public function getImageHeight(): int + { + return $this->imageHeight; + } + + public function getEditAs(): string + { + return $this->editAs; + } + + public function setEditAs(string $editAs): self + { + $this->editAs = $editAs; + + return $this; + } + + public function validEditAs(): bool + { + return in_array($this->editAs, self::VALID_EDIT_AS); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php index d97e33f7..444e3b1f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/CellIterator.php @@ -2,9 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; -use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; - -abstract class CellIterator implements \Iterator +use Iterator; +use PhpOffice\PhpSpreadsheet\Cell\Cell; + +/** + * @template TKey + * @implements Iterator + */ +abstract class CellIterator implements Iterator { /** * Worksheet to iterate. @@ -25,34 +30,27 @@ abstract class CellIterator implements \Iterator */ public function __destruct() { - unset($this->worksheet); + // @phpstan-ignore-next-line + $this->worksheet = null; } /** * Get loop only existing cells. - * - * @return bool */ - public function getIterateOnlyExistingCells() + public function getIterateOnlyExistingCells(): bool { return $this->onlyExistingCells; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. - * - * @throws PhpSpreadsheetException */ abstract protected function adjustForExistingOnlyRange(); /** * Set the iterator to loop only existing cells. - * - * @param bool $value - * - * @throws PhpSpreadsheetException */ - public function setIterateOnlyExistingCells($value) + public function setIterateOnlyExistingCells(bool $value): void { $this->onlyExistingCells = (bool) $value; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php index 098967f7..b6f30f1f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Column.php @@ -21,10 +21,9 @@ class Column /** * Create a new column. * - * @param Worksheet $parent * @param string $columnIndex */ - public function __construct(Worksheet $parent = null, $columnIndex = 'A') + public function __construct(?Worksheet $parent = null, $columnIndex = 'A') { // Set parent and column index $this->parent = $parent; @@ -36,15 +35,14 @@ public function __construct(Worksheet $parent = null, $columnIndex = 'A') */ public function __destruct() { - unset($this->parent); + // @phpstan-ignore-next-line + $this->parent = null; } /** * Get column index as string eg: 'A'. - * - * @return string */ - public function getColumnIndex() + public function getColumnIndex(): string { return $this->columnIndex; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php index d75da898..9d0be5bd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnCellIterator.php @@ -2,9 +2,13 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +/** + * @extends CellIterator + */ class ColumnCellIterator extends CellIterator { /** @@ -17,7 +21,7 @@ class ColumnCellIterator extends CellIterator /** * Column index. * - * @var string + * @var int */ private $columnIndex; @@ -43,7 +47,7 @@ class ColumnCellIterator extends CellIterator * @param int $startRow The row number at which to start iterating * @param int $endRow Optionally, the row number at which to stop iterating */ - public function __construct(Worksheet $subject = null, $columnIndex = 'A', $startRow = 1, $endRow = null) + public function __construct(Worksheet $subject, $columnIndex = 'A', $startRow = 1, $endRow = null) { // Set subject $this->worksheet = $subject; @@ -57,11 +61,9 @@ public function __construct(Worksheet $subject = null, $columnIndex = 'A', $star * * @param int $startRow The row number at which to start iterating * - * @throws PhpSpreadsheetException - * * @return $this */ - public function resetStart($startRow = 1) + public function resetStart(int $startRow = 1) { $this->startRow = $startRow; $this->adjustForExistingOnlyRange(); @@ -75,13 +77,11 @@ public function resetStart($startRow = 1) * * @param int $endRow The row number at which to stop iterating * - * @throws PhpSpreadsheetException - * * @return $this */ public function resetEnd($endRow = null) { - $this->endRow = ($endRow) ? $endRow : $this->worksheet->getHighestRow(); + $this->endRow = $endRow ?: $this->worksheet->getHighestRow(); $this->adjustForExistingOnlyRange(); return $this; @@ -92,16 +92,15 @@ public function resetEnd($endRow = null) * * @param int $row The row number to set the current pointer at * - * @throws PhpSpreadsheetException - * * @return $this */ - public function seek($row = 1) + public function seek(int $row = 1) { + if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $row))) { + throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); + } if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); - } elseif ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $row))) { - throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } $this->currentRow = $row; @@ -111,27 +110,23 @@ public function seek($row = 1) /** * Rewind the iterator to the starting row. */ - public function rewind() + public function rewind(): void { $this->currentRow = $this->startRow; } /** * Return the current cell in this worksheet column. - * - * @return null|\PhpOffice\PhpSpreadsheet\Cell\Cell */ - public function current() + public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->columnIndex, $this->currentRow); } /** * Return the current iterator key. - * - * @return int */ - public function key() + public function key(): int { return $this->currentRow; } @@ -139,59 +134,57 @@ public function key() /** * Set the iterator to its next value. */ - public function next() + public function next(): void { do { ++$this->currentRow; - } while (($this->onlyExistingCells) && + } while ( + ($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->currentRow)) && - ($this->currentRow <= $this->endRow)); + ($this->currentRow <= $this->endRow) + ); } /** * Set the iterator to its previous value. */ - public function prev() + public function prev(): void { do { --$this->currentRow; - } while (($this->onlyExistingCells) && + } while ( + ($this->onlyExistingCells) && (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->currentRow)) && - ($this->currentRow >= $this->startRow)); + ($this->currentRow >= $this->startRow) + ); } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentRow <= $this->endRow && $this->currentRow >= $this->startRow; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. - * - * @throws PhpSpreadsheetException */ - protected function adjustForExistingOnlyRange() + protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { - while ((!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->startRow)) && - ($this->startRow <= $this->endRow)) { + while ( + (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->startRow)) && + ($this->startRow <= $this->endRow) + ) { ++$this->startRow; } - if ($this->startRow > $this->endRow) { - throw new PhpSpreadsheetException('No cells exist within the specified range'); - } - while ((!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->endRow)) && - ($this->endRow >= $this->startRow)) { + while ( + (!$this->worksheet->cellExistsByColumnAndRow($this->columnIndex, $this->endRow)) && + ($this->endRow >= $this->startRow) + ) { --$this->endRow; } - if ($this->endRow < $this->startRow) { - throw new PhpSpreadsheetException('No cells exist within the specified range'); - } } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php index 4e87a344..b64ecec9 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnDimension.php @@ -2,6 +2,9 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; + class ColumnDimension extends Dimension { /** @@ -30,12 +33,12 @@ class ColumnDimension extends Dimension /** * Create a new ColumnDimension. * - * @param string $pIndex Character column index + * @param string $index Character column index */ - public function __construct($pIndex = 'A') + public function __construct($index = 'A') { // Initialise values - $this->columnIndex = $pIndex; + $this->columnIndex = $index; // set dimension as unformatted by default parent::__construct(0); @@ -43,24 +46,36 @@ public function __construct($pIndex = 'A') /** * Get column index as string eg: 'A'. - * - * @return string */ - public function getColumnIndex() + public function getColumnIndex(): string { return $this->columnIndex; } /** * Set column index as string eg: 'A'. - * - * @param string $pValue - * - * @return $this */ - public function setColumnIndex($pValue) + public function setColumnIndex(string $index): self { - $this->columnIndex = $pValue; + $this->columnIndex = $index; + + return $this; + } + + /** + * Get column index as numeric. + */ + public function getColumnNumeric(): int + { + return Coordinate::columnIndexFromString($this->columnIndex); + } + + /** + * Set column index as numeric. + */ + public function setColumnNumeric(int $index): self + { + $this->columnIndex = Coordinate::stringFromColumnIndex($index); return $this; } @@ -68,33 +83,42 @@ public function setColumnIndex($pValue) /** * Get Width. * - * @return float + * Each unit of column width is equal to the width of one character in the default font size. A value of -1 + * tells Excel to display this column in its default width. + * By default, this will be the return value; but this method also accepts an optional unit of measure argument + * and will convert the returned value to the specified UoM.. */ - public function getWidth() + public function getWidth(?string $unitOfMeasure = null): float { - return $this->width; + return ($unitOfMeasure === null || $this->width < 0) + ? $this->width + : (new CssDimension((string) $this->width))->toUnit($unitOfMeasure); } /** * Set Width. * - * @param float $pValue + * Each unit of column width is equal to the width of one character in the default font size. A value of -1 + * tells Excel to display this column in its default width. + * By default, this will be the unit of measure for the passed value; but this method also accepts an + * optional unit of measure argument, and will convert the value from the specified UoM using an + * approximation method. * * @return $this */ - public function setWidth($pValue) + public function setWidth(float $width, ?string $unitOfMeasure = null) { - $this->width = $pValue; + $this->width = ($unitOfMeasure === null || $width < 0) + ? $width + : (new CssDimension("{$width}{$unitOfMeasure}"))->width(); return $this; } /** * Get Auto Size. - * - * @return bool */ - public function getAutoSize() + public function getAutoSize(): bool { return $this->autoSize; } @@ -102,13 +126,11 @@ public function getAutoSize() /** * Set Auto Size. * - * @param bool $pValue - * * @return $this */ - public function setAutoSize($pValue) + public function setAutoSize(bool $autosizeEnabled) { - $this->autoSize = $pValue; + $this->autoSize = $autosizeEnabled; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php index c8913cc1..b64ae5a4 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/ColumnIterator.php @@ -2,11 +2,15 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use Iterator; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; -class ColumnIterator implements \Iterator +/** + * @implements Iterator + */ +class ColumnIterator implements Iterator { /** * Worksheet to iterate. @@ -56,7 +60,8 @@ public function __construct(Worksheet $worksheet, $startColumn = 'A', $endColumn */ public function __destruct() { - unset($this->worksheet); + // @phpstan-ignore-next-line + $this->worksheet = null; } /** @@ -64,15 +69,15 @@ public function __destruct() * * @param string $startColumn The column address at which to start iterating * - * @throws Exception - * * @return $this */ - public function resetStart($startColumn = 'A') + public function resetStart(string $startColumn = 'A') { $startColumnIndex = Coordinate::columnIndexFromString($startColumn); if ($startColumnIndex > Coordinate::columnIndexFromString($this->worksheet->getHighestColumn())) { - throw new Exception("Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})"); + throw new Exception( + "Start column ({$startColumn}) is beyond highest column ({$this->worksheet->getHighestColumn()})" + ); } $this->startColumnIndex = $startColumnIndex; @@ -93,7 +98,7 @@ public function resetStart($startColumn = 'A') */ public function resetEnd($endColumn = null) { - $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn(); + $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); return $this; @@ -104,15 +109,15 @@ public function resetEnd($endColumn = null) * * @param string $column The column address to set the current pointer at * - * @throws PhpSpreadsheetException - * * @return $this */ - public function seek($column = 'A') + public function seek(string $column = 'A') { $column = Coordinate::columnIndexFromString($column); if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { - throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); + throw new PhpSpreadsheetException( + "Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})" + ); } $this->currentColumnIndex = $column; @@ -122,27 +127,23 @@ public function seek($column = 'A') /** * Rewind the iterator to the starting column. */ - public function rewind() + public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current column in this worksheet. - * - * @return Column */ - public function current() + public function current(): Column { return new Column($this->worksheet, Coordinate::stringFromColumnIndex($this->currentColumnIndex)); } /** * Return the current iterator key. - * - * @return string */ - public function key() + public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } @@ -150,7 +151,7 @@ public function key() /** * Set the iterator to its next value. */ - public function next() + public function next(): void { ++$this->currentColumnIndex; } @@ -158,17 +159,15 @@ public function next() /** * Set the iterator to its previous value. */ - public function prev() + public function prev(): void { --$this->currentColumnIndex; } /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php index ce40cf57..ba03b5b7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Dimension.php @@ -47,10 +47,8 @@ public function __construct($initialValue = null) /** * Get Visible. - * - * @return bool */ - public function getVisible() + public function getVisible(): bool { return $this->visible; } @@ -58,23 +56,19 @@ public function getVisible() /** * Set Visible. * - * @param bool $pValue - * * @return $this */ - public function setVisible($pValue) + public function setVisible(bool $visible) { - $this->visible = (bool) $pValue; + $this->visible = $visible; return $this; } /** * Get Outline Level. - * - * @return int */ - public function getOutlineLevel() + public function getOutlineLevel(): int { return $this->outlineLevel; } @@ -83,29 +77,23 @@ public function getOutlineLevel() * Set Outline Level. * Value must be between 0 and 7. * - * @param int $pValue - * - * @throws PhpSpreadsheetException - * * @return $this */ - public function setOutlineLevel($pValue) + public function setOutlineLevel(int $level) { - if ($pValue < 0 || $pValue > 7) { + if ($level < 0 || $level > 7) { throw new PhpSpreadsheetException('Outline level must range between 0 and 7.'); } - $this->outlineLevel = $pValue; + $this->outlineLevel = $level; return $this; } /** * Get Collapsed. - * - * @return bool */ - public function getCollapsed() + public function getCollapsed(): bool { return $this->collapsed; } @@ -113,13 +101,11 @@ public function getCollapsed() /** * Set Collapsed. * - * @param bool $pValue - * * @return $this */ - public function setCollapsed($pValue) + public function setCollapsed(bool $collapsed) { - $this->collapsed = (bool) $pValue; + $this->collapsed = $collapsed; return $this; } @@ -129,7 +115,7 @@ public function setCollapsed($pValue) * * @return int */ - public function getXfIndex() + public function getXfIndex(): ?int { return $this->xfIndex; } @@ -137,29 +123,12 @@ public function getXfIndex() /** * Set index to cellXf. * - * @param int $pValue - * * @return $this */ - public function setXfIndex($pValue) + public function setXfIndex(int $XfIndex) { - $this->xfIndex = $pValue; + $this->xfIndex = $XfIndex; return $this; } - - /** - * Implement PHP __clone to create a deep clone, not just a shallow copy. - */ - public function __clone() - { - $vars = get_object_vars($this); - foreach ($vars as $key => $value) { - if (is_object($value)) { - $this->$key = clone $value; - } else { - $this->$key = $value; - } - } - } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php index da492b4c..f62873bb 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing.php @@ -3,9 +3,17 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +use ZipArchive; class Drawing extends BaseDrawing { + const IMAGE_TYPES_CONVERTION_MAP = [ + IMAGETYPE_GIF => IMAGETYPE_PNG, + IMAGETYPE_JPEG => IMAGETYPE_JPEG, + IMAGETYPE_PNG => IMAGETYPE_PNG, + IMAGETYPE_BMP => IMAGETYPE_PNG, + ]; + /** * Path. * @@ -13,6 +21,13 @@ class Drawing extends BaseDrawing */ private $path; + /** + * Whether or not we are dealing with a URL. + * + * @var bool + */ + private $isUrl; + /** * Create a new Drawing. */ @@ -20,6 +35,7 @@ public function __construct() { // Initialise values $this->path = ''; + $this->isUrl = false; // Initialize parent parent::__construct(); @@ -37,15 +53,10 @@ public function getFilename() /** * Get indexed filename (using image index). - * - * @return string */ - public function getIndexedFilename() + public function getIndexedFilename(): string { - $fileName = $this->getFilename(); - $fileName = str_replace(' ', '_', $fileName); - - return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); + return md5($this->path) . '.' . $this->getExtension(); } /** @@ -60,6 +71,20 @@ public function getExtension() return $exploded[count($exploded) - 1]; } + /** + * Get full filepath to store drawing in zip archive. + * + * @return string + */ + public function getMediaFilename() + { + if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { + throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + } + + return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave()); + } + /** * Get Path. * @@ -73,33 +98,68 @@ public function getPath() /** * Set Path. * - * @param string $pValue File path - * @param bool $pVerifyFile Verify file - * - * @throws PhpSpreadsheetException + * @param string $path File path + * @param bool $verifyFile Verify file + * @param ZipArchive $zip Zip archive instance * * @return $this */ - public function setPath($pValue, $pVerifyFile = true) + public function setPath($path, $verifyFile = true, $zip = null) { - if ($pVerifyFile) { - if (file_exists($pValue)) { - $this->path = $pValue; - - if ($this->width == 0 && $this->height == 0) { - // Get width/height - [$this->width, $this->height] = getimagesize($pValue); + if ($verifyFile) { + // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979 + if (filter_var($path, FILTER_VALIDATE_URL)) { + $this->path = $path; + // Implicit that it is a URL, rather store info than running check above on value in other places. + $this->isUrl = true; + $imageContents = file_get_contents($path); + $filePath = tempnam(sys_get_temp_dir(), 'Drawing'); + if ($filePath) { + file_put_contents($filePath, $imageContents); + if (file_exists($filePath)) { + $this->setSizesAndType($filePath); + unlink($filePath); + } + } + } elseif (file_exists($path)) { + $this->path = $path; + $this->setSizesAndType($path); + } elseif ($zip instanceof ZipArchive) { + $zipPath = explode('#', $path)[1]; + if ($zip->locateName($zipPath) !== false) { + $this->path = $path; + $this->setSizesAndType($path); } } else { - throw new PhpSpreadsheetException("File $pValue not found!"); + throw new PhpSpreadsheetException("File $path not found!"); } } else { - $this->path = $pValue; + $this->path = $path; } return $this; } + /** + * Get isURL. + */ + public function getIsURL(): bool + { + return $this->isUrl; + } + + /** + * Set isURL. + * + * @return $this + */ + public function setIsURL(bool $isUrl): self + { + $this->isUrl = $isUrl; + + return $this; + } + /** * Get hash code. * @@ -113,4 +173,42 @@ public function getHashCode() __CLASS__ ); } + + /** + * Get Image Type for Save. + */ + public function getImageTypeForSave(): int + { + if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { + throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + } + + return self::IMAGE_TYPES_CONVERTION_MAP[$this->type]; + } + + /** + * Get Image file extention for Save. + */ + public function getImageFileExtensionForSave(bool $includeDot = true): string + { + if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { + throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + } + + $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot); + + return is_string($result) ? $result : ''; + } + + /** + * Get Image mime type. + */ + public function getImageMimeType(): string + { + if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) { + throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.'); + } + + return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php index c7594dae..a461a51b 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Drawing/Shadow.php @@ -52,7 +52,7 @@ class Shadow implements IComparable /** * Shadow alignment. * - * @var int + * @var string */ private $alignment; @@ -98,13 +98,13 @@ public function getVisible() /** * Set Visible. * - * @param bool $pValue + * @param bool $visible * * @return $this */ - public function setVisible($pValue) + public function setVisible($visible) { - $this->visible = $pValue; + $this->visible = $visible; return $this; } @@ -122,13 +122,13 @@ public function getBlurRadius() /** * Set Blur radius. * - * @param int $pValue + * @param int $blurRadius * * @return $this */ - public function setBlurRadius($pValue) + public function setBlurRadius($blurRadius) { - $this->blurRadius = $pValue; + $this->blurRadius = $blurRadius; return $this; } @@ -146,13 +146,13 @@ public function getDistance() /** * Set Shadow distance. * - * @param int $pValue + * @param int $distance * * @return $this */ - public function setDistance($pValue) + public function setDistance($distance) { - $this->distance = $pValue; + $this->distance = $distance; return $this; } @@ -170,13 +170,13 @@ public function getDirection() /** * Set Shadow direction (in degrees). * - * @param int $pValue + * @param int $direction * * @return $this */ - public function setDirection($pValue) + public function setDirection($direction) { - $this->direction = $pValue; + $this->direction = $direction; return $this; } @@ -184,7 +184,7 @@ public function setDirection($pValue) /** * Get Shadow alignment. * - * @return int + * @return string */ public function getAlignment() { @@ -194,13 +194,13 @@ public function getAlignment() /** * Set Shadow alignment. * - * @param int $pValue + * @param string $alignment * * @return $this */ - public function setAlignment($pValue) + public function setAlignment($alignment) { - $this->alignment = $pValue; + $this->alignment = $alignment; return $this; } @@ -218,13 +218,11 @@ public function getColor() /** * Set Color. * - * @param Color $pValue - * * @return $this */ - public function setColor(Color $pValue = null) + public function setColor(?Color $color = null) { - $this->color = $pValue; + $this->color = $color; return $this; } @@ -242,13 +240,13 @@ public function getAlpha() /** * Set Alpha. * - * @param int $pValue + * @param int $alpha * * @return $this */ - public function setAlpha($pValue) + public function setAlpha($alpha) { - $this->alpha = $pValue; + $this->alpha = $alpha; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php index be19abbd..c3504d83 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/HeaderFooter.php @@ -170,13 +170,13 @@ public function getOddHeader() /** * Set OddHeader. * - * @param string $pValue + * @param string $oddHeader * * @return $this */ - public function setOddHeader($pValue) + public function setOddHeader($oddHeader) { - $this->oddHeader = $pValue; + $this->oddHeader = $oddHeader; return $this; } @@ -194,13 +194,13 @@ public function getOddFooter() /** * Set OddFooter. * - * @param string $pValue + * @param string $oddFooter * * @return $this */ - public function setOddFooter($pValue) + public function setOddFooter($oddFooter) { - $this->oddFooter = $pValue; + $this->oddFooter = $oddFooter; return $this; } @@ -218,13 +218,13 @@ public function getEvenHeader() /** * Set EvenHeader. * - * @param string $pValue + * @param string $eventHeader * * @return $this */ - public function setEvenHeader($pValue) + public function setEvenHeader($eventHeader) { - $this->evenHeader = $pValue; + $this->evenHeader = $eventHeader; return $this; } @@ -242,13 +242,13 @@ public function getEvenFooter() /** * Set EvenFooter. * - * @param string $pValue + * @param string $evenFooter * * @return $this */ - public function setEvenFooter($pValue) + public function setEvenFooter($evenFooter) { - $this->evenFooter = $pValue; + $this->evenFooter = $evenFooter; return $this; } @@ -266,13 +266,13 @@ public function getFirstHeader() /** * Set FirstHeader. * - * @param string $pValue + * @param string $firstHeader * * @return $this */ - public function setFirstHeader($pValue) + public function setFirstHeader($firstHeader) { - $this->firstHeader = $pValue; + $this->firstHeader = $firstHeader; return $this; } @@ -290,13 +290,13 @@ public function getFirstFooter() /** * Set FirstFooter. * - * @param string $pValue + * @param string $firstFooter * * @return $this */ - public function setFirstFooter($pValue) + public function setFirstFooter($firstFooter) { - $this->firstFooter = $pValue; + $this->firstFooter = $firstFooter; return $this; } @@ -314,13 +314,13 @@ public function getDifferentOddEven() /** * Set DifferentOddEven. * - * @param bool $pValue + * @param bool $differentOddEvent * * @return $this */ - public function setDifferentOddEven($pValue) + public function setDifferentOddEven($differentOddEvent) { - $this->differentOddEven = $pValue; + $this->differentOddEven = $differentOddEvent; return $this; } @@ -338,13 +338,13 @@ public function getDifferentFirst() /** * Set DifferentFirst. * - * @param bool $pValue + * @param bool $differentFirst * * @return $this */ - public function setDifferentFirst($pValue) + public function setDifferentFirst($differentFirst) { - $this->differentFirst = $pValue; + $this->differentFirst = $differentFirst; return $this; } @@ -362,13 +362,13 @@ public function getScaleWithDocument() /** * Set ScaleWithDocument. * - * @param bool $pValue + * @param bool $scaleWithDocument * * @return $this */ - public function setScaleWithDocument($pValue) + public function setScaleWithDocument($scaleWithDocument) { - $this->scaleWithDocument = $pValue; + $this->scaleWithDocument = $scaleWithDocument; return $this; } @@ -386,13 +386,13 @@ public function getAlignWithMargins() /** * Set AlignWithMargins. * - * @param bool $pValue + * @param bool $alignWithMargins * * @return $this */ - public function setAlignWithMargins($pValue) + public function setAlignWithMargins($alignWithMargins) { - $this->alignWithMargins = $pValue; + $this->alignWithMargins = $alignWithMargins; return $this; } @@ -400,7 +400,6 @@ public function setAlignWithMargins($pValue) /** * Add header/footer image. * - * @param HeaderFooterDrawing $image * @param string $location * * @return $this diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php index d8797a34..dc082043 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Iterator.php @@ -4,6 +4,9 @@ use PhpOffice\PhpSpreadsheet\Spreadsheet; +/** + * @implements \Iterator + */ class Iterator implements \Iterator { /** @@ -22,8 +25,6 @@ class Iterator implements \Iterator /** * Create a new worksheet iterator. - * - * @param Spreadsheet $subject */ public function __construct(Spreadsheet $subject) { @@ -31,38 +32,26 @@ public function __construct(Spreadsheet $subject) $this->subject = $subject; } - /** - * Destructor. - */ - public function __destruct() - { - unset($this->subject); - } - /** * Rewind iterator. */ - public function rewind() + public function rewind(): void { $this->position = 0; } /** * Current Worksheet. - * - * @return Worksheet */ - public function current() + public function current(): Worksheet { return $this->subject->getSheet($this->position); } /** * Current key. - * - * @return int */ - public function key() + public function key(): int { return $this->position; } @@ -70,17 +59,15 @@ public function key() /** * Next value. */ - public function next() + public function next(): void { ++$this->position; } /** * Are there more Worksheet instances available? - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->position < $this->subject->getSheetCount() && $this->position >= 0; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php index f0935585..e65541dc 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/MemoryDrawing.php @@ -2,6 +2,9 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use GdImage; +use PhpOffice\PhpSpreadsheet\Exception; + class MemoryDrawing extends BaseDrawing { // Rendering functions @@ -19,7 +22,7 @@ class MemoryDrawing extends BaseDrawing /** * Image resource. * - * @var resource + * @var null|GdImage|resource */ private $imageResource; @@ -44,25 +47,90 @@ class MemoryDrawing extends BaseDrawing */ private $uniqueName; + /** @var null|resource */ + private $alwaysNull; + /** * Create a new MemoryDrawing. */ public function __construct() { // Initialise values - $this->imageResource = null; $this->renderingFunction = self::RENDERING_DEFAULT; $this->mimeType = self::MIMETYPE_DEFAULT; - $this->uniqueName = md5(rand(0, 9999) . time() . rand(0, 9999)); + $this->uniqueName = md5(mt_rand(0, 9999) . time() . mt_rand(0, 9999)); + $this->alwaysNull = null; // Initialize parent parent::__construct(); } + public function __destruct() + { + if ($this->imageResource) { + $rslt = @imagedestroy($this->imageResource); + // "Fix" for Scrutinizer + $this->imageResource = $rslt ? null : $this->alwaysNull; + } + } + + public function __clone() + { + parent::__clone(); + $this->cloneResource(); + } + + private function cloneResource(): void + { + if (!$this->imageResource) { + return; + } + + $width = imagesx($this->imageResource); + $height = imagesy($this->imageResource); + + if (imageistruecolor($this->imageResource)) { + $clone = imagecreatetruecolor($width, $height); + if (!$clone) { + throw new Exception('Could not clone image resource'); + } + + imagealphablending($clone, false); + imagesavealpha($clone, true); + } else { + $clone = imagecreate($width, $height); + if (!$clone) { + throw new Exception('Could not clone image resource'); + } + + // If the image has transparency... + $transparent = imagecolortransparent($this->imageResource); + if ($transparent >= 0) { + $rgb = imagecolorsforindex($this->imageResource, $transparent); + if (empty($rgb)) { + throw new Exception('Could not get image colors'); + } + + imagesavealpha($clone, true); + $color = imagecolorallocatealpha($clone, $rgb['red'], $rgb['green'], $rgb['blue'], $rgb['alpha']); + if ($color === false) { + throw new Exception('Could not get image alpha color'); + } + + imagefill($clone, 0, 0, $color); + } + } + + //Create the Clone!! + imagecopy($clone, $this->imageResource, 0, 0, 0, 0, $width, $height); + + $this->imageResource = $clone; + } + /** * Get image resource. * - * @return resource + * @return null|GdImage|resource */ public function getImageResource() { @@ -72,7 +140,7 @@ public function getImageResource() /** * Set image resource. * - * @param resource $value + * @param GdImage|resource $value * * @return $this */ @@ -139,10 +207,8 @@ public function setMimeType($value) /** * Get indexed filename (using image index). - * - * @return string */ - public function getIndexedFilename() + public function getIndexedFilename(): string { $extension = strtolower($this->getMimeType()); $extension = explode('/', $extension); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php index 9ebfb648..34e1145e 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageMargins.php @@ -66,13 +66,13 @@ public function getLeft() /** * Set Left. * - * @param float $pValue + * @param float $left * * @return $this */ - public function setLeft($pValue) + public function setLeft($left) { - $this->left = $pValue; + $this->left = $left; return $this; } @@ -90,13 +90,13 @@ public function getRight() /** * Set Right. * - * @param float $pValue + * @param float $right * * @return $this */ - public function setRight($pValue) + public function setRight($right) { - $this->right = $pValue; + $this->right = $right; return $this; } @@ -114,13 +114,13 @@ public function getTop() /** * Set Top. * - * @param float $pValue + * @param float $top * * @return $this */ - public function setTop($pValue) + public function setTop($top) { - $this->top = $pValue; + $this->top = $top; return $this; } @@ -138,13 +138,13 @@ public function getBottom() /** * Set Bottom. * - * @param float $pValue + * @param float $bottom * * @return $this */ - public function setBottom($pValue) + public function setBottom($bottom) { - $this->bottom = $pValue; + $this->bottom = $bottom; return $this; } @@ -162,13 +162,13 @@ public function getHeader() /** * Set Header. * - * @param float $pValue + * @param float $header * * @return $this */ - public function setHeader($pValue) + public function setHeader($header) { - $this->header = $pValue; + $this->header = $header; return $this; } @@ -186,13 +186,13 @@ public function getFooter() /** * Set Footer. * - * @param float $pValue + * @param float $footer * * @return $this */ - public function setFooter($pValue) + public function setFooter($footer) { - $this->footer = $pValue; + $this->footer = $footer; return $this; } @@ -211,4 +211,34 @@ public function __clone() } } } + + public static function fromCentimeters(float $value): float + { + return $value / 2.54; + } + + public static function toCentimeters(float $value): float + { + return $value * 2.54; + } + + public static function fromMillimeters(float $value): float + { + return $value / 25.4; + } + + public static function toMillimeters(float $value): float + { + return $value * 25.4; + } + + public static function fromPoints(float $value): float + { + return $value / 72; + } + + public static function toPoints(float $value): float + { + return $value * 72; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php index 38a09736..c23bfc59 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/PageSetup.php @@ -76,10 +76,6 @@ * 67 = A3 transverse paper (297 mm by 420 mm) * 68 = A3 extra transverse paper (322 mm by 445 mm) * - * - * @category PhpSpreadsheet - * - * @copyright Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) */ class PageSetup { @@ -160,19 +156,36 @@ class PageSetup const SETPRINTRANGE_OVERWRITE = 'O'; const SETPRINTRANGE_INSERT = 'I'; + const PAGEORDER_OVER_THEN_DOWN = 'overThenDown'; + const PAGEORDER_DOWN_THEN_OVER = 'downThenOver'; + /** - * Paper size. + * Paper size default. * * @var int */ - private $paperSize = self::PAPERSIZE_LETTER; + private static $paperSizeDefault = self::PAPERSIZE_LETTER; + + /** + * Paper size. + * + * @var ?int + */ + private $paperSize; + + /** + * Orientation default. + * + * @var string + */ + private static $orientationDefault = self::ORIENTATION_DEFAULT; /** * Orientation. * * @var string */ - private $orientation = self::ORIENTATION_DEFAULT; + private $orientation; /** * Scale (Print Scale). @@ -239,7 +252,7 @@ class PageSetup /** * Print area. * - * @var string + * @var null|string */ private $printArea; @@ -250,11 +263,14 @@ class PageSetup */ private $firstPageNumber; + private $pageOrder = self::PAGEORDER_DOWN_THEN_OVER; + /** * Create a new PageSetup. */ public function __construct() { + $this->orientation = self::$orientationDefault; } /** @@ -264,23 +280,39 @@ public function __construct() */ public function getPaperSize() { - return $this->paperSize; + return $this->paperSize ?? self::$paperSizeDefault; } /** * Set Paper Size. * - * @param int $pValue see self::PAPERSIZE_* + * @param int $paperSize see self::PAPERSIZE_* * * @return $this */ - public function setPaperSize($pValue) + public function setPaperSize($paperSize) { - $this->paperSize = $pValue; + $this->paperSize = $paperSize; return $this; } + /** + * Get Paper Size default. + */ + public static function getPaperSizeDefault(): int + { + return self::$paperSizeDefault; + } + + /** + * Set Paper Size Default. + */ + public static function setPaperSizeDefault(int $paperSize): void + { + self::$paperSizeDefault = $paperSize; + } + /** * Get Orientation. * @@ -294,17 +326,31 @@ public function getOrientation() /** * Set Orientation. * - * @param string $pValue see self::ORIENTATION_* + * @param string $orientation see self::ORIENTATION_* * * @return $this */ - public function setOrientation($pValue) + public function setOrientation($orientation) { - $this->orientation = $pValue; + if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) { + $this->orientation = $orientation; + } return $this; } + public static function getOrientationDefault(): string + { + return self::$orientationDefault; + } + + public static function setOrientationDefault(string $orientation): void + { + if ($orientation === self::ORIENTATION_LANDSCAPE || $orientation === self::ORIENTATION_PORTRAIT || $orientation === self::ORIENTATION_DEFAULT) { + self::$orientationDefault = $orientation; + } + } + /** * Get Scale. * @@ -320,20 +366,18 @@ public function getScale() * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use. * - * @param null|int $pValue - * @param bool $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth - * - * @throws PhpSpreadsheetException + * @param null|int $scale + * @param bool $update Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * * @return $this */ - public function setScale($pValue, $pUpdate = true) + public function setScale($scale, $update = true) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 - if (($pValue >= 0) || $pValue === null) { - $this->scale = $pValue; - if ($pUpdate) { + if (($scale >= 0) || $scale === null) { + $this->scale = $scale; + if ($update) { $this->fitToPage = false; } } else { @@ -356,13 +400,13 @@ public function getFitToPage() /** * Set Fit To Page. * - * @param bool $pValue + * @param bool $fitToPage * * @return $this */ - public function setFitToPage($pValue) + public function setFitToPage($fitToPage) { - $this->fitToPage = $pValue; + $this->fitToPage = $fitToPage; return $this; } @@ -380,15 +424,15 @@ public function getFitToHeight() /** * Set Fit To Height. * - * @param null|int $pValue - * @param bool $pUpdate Update fitToPage so it applies rather than scaling + * @param null|int $fitToHeight + * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ - public function setFitToHeight($pValue, $pUpdate = true) + public function setFitToHeight($fitToHeight, $update = true) { - $this->fitToHeight = $pValue; - if ($pUpdate) { + $this->fitToHeight = $fitToHeight; + if ($update) { $this->fitToPage = true; } @@ -408,15 +452,15 @@ public function getFitToWidth() /** * Set Fit To Width. * - * @param null|int $pValue - * @param bool $pUpdate Update fitToPage so it applies rather than scaling + * @param null|int $value + * @param bool $update Update fitToPage so it applies rather than scaling * * @return $this */ - public function setFitToWidth($pValue, $pUpdate = true) + public function setFitToWidth($value, $update = true) { - $this->fitToWidth = $pValue; - if ($pUpdate) { + $this->fitToWidth = $value; + if ($update) { $this->fitToPage = true; } @@ -452,13 +496,13 @@ public function getColumnsToRepeatAtLeft() /** * Set Columns to repeat at left. * - * @param array $pValue Containing start column and end column, empty array if option unset + * @param array $columnsToRepeatAtLeft Containing start column and end column, empty array if option unset * * @return $this */ - public function setColumnsToRepeatAtLeft(array $pValue) + public function setColumnsToRepeatAtLeft(array $columnsToRepeatAtLeft) { - $this->columnsToRepeatAtLeft = $pValue; + $this->columnsToRepeatAtLeft = $columnsToRepeatAtLeft; return $this; } @@ -466,14 +510,14 @@ public function setColumnsToRepeatAtLeft(array $pValue) /** * Set Columns to repeat at left by start and end. * - * @param string $pStart eg: 'A' - * @param string $pEnd eg: 'B' + * @param string $start eg: 'A' + * @param string $end eg: 'B' * * @return $this */ - public function setColumnsToRepeatAtLeftByStartAndEnd($pStart, $pEnd) + public function setColumnsToRepeatAtLeftByStartAndEnd($start, $end) { - $this->columnsToRepeatAtLeft = [$pStart, $pEnd]; + $this->columnsToRepeatAtLeft = [$start, $end]; return $this; } @@ -507,13 +551,13 @@ public function getRowsToRepeatAtTop() /** * Set Rows to repeat at top. * - * @param array $pValue Containing start column and end column, empty array if option unset + * @param array $rowsToRepeatAtTop Containing start column and end column, empty array if option unset * * @return $this */ - public function setRowsToRepeatAtTop(array $pValue) + public function setRowsToRepeatAtTop(array $rowsToRepeatAtTop) { - $this->rowsToRepeatAtTop = $pValue; + $this->rowsToRepeatAtTop = $rowsToRepeatAtTop; return $this; } @@ -521,14 +565,14 @@ public function setRowsToRepeatAtTop(array $pValue) /** * Set Rows to repeat at top by start and end. * - * @param int $pStart eg: 1 - * @param int $pEnd eg: 1 + * @param int $start eg: 1 + * @param int $end eg: 1 * * @return $this */ - public function setRowsToRepeatAtTopByStartAndEnd($pStart, $pEnd) + public function setRowsToRepeatAtTopByStartAndEnd($start, $end) { - $this->rowsToRepeatAtTop = [$pStart, $pEnd]; + $this->rowsToRepeatAtTop = [$start, $end]; return $this; } @@ -589,8 +633,6 @@ public function setVerticalCentered($value) * Otherwise, the specific range identified by the value of $index will be returned * Print areas are numbered from 1 * - * @throws PhpSpreadsheetException - * * @return string */ public function getPrintArea($index = 0) @@ -598,6 +640,7 @@ public function getPrintArea($index = 0) if ($index == 0) { return $this->printArea; } + /** @phpstan-ignore-next-line */ $printAreas = explode(',', $this->printArea); if (isset($printAreas[$index - 1])) { return $printAreas[$index - 1]; @@ -621,6 +664,7 @@ public function isPrintAreaSet($index = 0) if ($index == 0) { return $this->printArea !== null; } + /** @phpstan-ignore-next-line */ $printAreas = explode(',', $this->printArea); return isset($printAreas[$index - 1]); @@ -641,6 +685,7 @@ public function clearPrintArea($index = 0) if ($index == 0) { $this->printArea = null; } else { + /** @phpstan-ignore-next-line */ $printAreas = explode(',', $this->printArea); if (isset($printAreas[$index - 1])) { unset($printAreas[$index - 1]); @@ -669,8 +714,6 @@ public function clearPrintArea($index = 0) * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * - * @throws PhpSpreadsheetException - * * @return $this */ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) @@ -683,11 +726,15 @@ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_O throw new PhpSpreadsheetException('Cell coordinate must not be absolute.'); } $value = strtoupper($value); + if (!$this->printArea) { + $index = 0; + } if ($method == self::SETPRINTRANGE_OVERWRITE) { if ($index == 0) { $this->printArea = $value; } else { + /** @phpstan-ignore-next-line */ $printAreas = explode(',', $this->printArea); if ($index < 0) { $index = count($printAreas) - abs($index) + 1; @@ -700,8 +747,9 @@ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_O } } elseif ($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { - $this->printArea .= ($this->printArea == '') ? $value : ',' . $value; + $this->printArea = $this->printArea ? ($this->printArea . ',' . $value) : $value; } else { + /** @phpstan-ignore-next-line */ $printAreas = explode(',', $this->printArea); if ($index < 0) { $index = abs($index) - 1; @@ -730,8 +778,6 @@ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_O * list. * Print areas are numbered from 1 * - * @throws PhpSpreadsheetException - * * @return $this */ public function addPrintArea($value, $index = -1) @@ -760,8 +806,6 @@ public function addPrintArea($value, $index = -1) * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * - * @throws PhpSpreadsheetException - * * @return $this */ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) @@ -787,8 +831,6 @@ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $in * list. * Print areas are numbered from 1 * - * @throws PhpSpreadsheetException - * * @return $this */ public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) @@ -834,6 +876,20 @@ public function resetFirstPageNumber() return $this->setFirstPageNumber(null); } + public function getPageOrder(): string + { + return $this->pageOrder; + } + + public function setPageOrder(?string $pageOrder): self + { + if ($pageOrder === null || $pageOrder === self::PAGEORDER_DOWN_THEN_OVER || $pageOrder === self::PAGEORDER_OVER_THEN_DOWN) { + $this->pageOrder = $pageOrder ?? self::PAGEORDER_DOWN_THEN_OVER; + } + + return $this; + } + /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php index 2fd3e919..4d44d8e5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Protection.php @@ -6,6 +6,17 @@ class Protection { + const ALGORITHM_MD2 = 'MD2'; + const ALGORITHM_MD4 = 'MD4'; + const ALGORITHM_MD5 = 'MD5'; + const ALGORITHM_SHA_1 = 'SHA-1'; + const ALGORITHM_SHA_256 = 'SHA-256'; + const ALGORITHM_SHA_384 = 'SHA-384'; + const ALGORITHM_SHA_512 = 'SHA-512'; + const ALGORITHM_RIPEMD_128 = 'RIPEMD-128'; + const ALGORITHM_RIPEMD_160 = 'RIPEMD-160'; + const ALGORITHM_WHIRLPOOL = 'WHIRLPOOL'; + /** * Sheet. * @@ -119,12 +130,33 @@ class Protection private $selectUnlockedCells = false; /** - * Password. + * Hashed password. * * @var string */ private $password = ''; + /** + * Algorithm name. + * + * @var string + */ + private $algorithm = ''; + + /** + * Salt value. + * + * @var string + */ + private $salt = ''; + + /** + * Spin count. + * + * @var int + */ + private $spinCount = 10000; + /** * Create a new Protection. */ @@ -170,13 +202,13 @@ public function getSheet() /** * Set Sheet. * - * @param bool $pValue + * @param bool $sheet * * @return $this */ - public function setSheet($pValue) + public function setSheet($sheet) { - $this->sheet = $pValue; + $this->sheet = $sheet; return $this; } @@ -194,13 +226,13 @@ public function getObjects() /** * Set Objects. * - * @param bool $pValue + * @param bool $objects * * @return $this */ - public function setObjects($pValue) + public function setObjects($objects) { - $this->objects = $pValue; + $this->objects = $objects; return $this; } @@ -218,13 +250,13 @@ public function getScenarios() /** * Set Scenarios. * - * @param bool $pValue + * @param bool $scenarios * * @return $this */ - public function setScenarios($pValue) + public function setScenarios($scenarios) { - $this->scenarios = $pValue; + $this->scenarios = $scenarios; return $this; } @@ -242,13 +274,13 @@ public function getFormatCells() /** * Set FormatCells. * - * @param bool $pValue + * @param bool $formatCells * * @return $this */ - public function setFormatCells($pValue) + public function setFormatCells($formatCells) { - $this->formatCells = $pValue; + $this->formatCells = $formatCells; return $this; } @@ -266,13 +298,13 @@ public function getFormatColumns() /** * Set FormatColumns. * - * @param bool $pValue + * @param bool $formatColumns * * @return $this */ - public function setFormatColumns($pValue) + public function setFormatColumns($formatColumns) { - $this->formatColumns = $pValue; + $this->formatColumns = $formatColumns; return $this; } @@ -290,13 +322,13 @@ public function getFormatRows() /** * Set FormatRows. * - * @param bool $pValue + * @param bool $formatRows * * @return $this */ - public function setFormatRows($pValue) + public function setFormatRows($formatRows) { - $this->formatRows = $pValue; + $this->formatRows = $formatRows; return $this; } @@ -314,13 +346,13 @@ public function getInsertColumns() /** * Set InsertColumns. * - * @param bool $pValue + * @param bool $insertColumns * * @return $this */ - public function setInsertColumns($pValue) + public function setInsertColumns($insertColumns) { - $this->insertColumns = $pValue; + $this->insertColumns = $insertColumns; return $this; } @@ -338,13 +370,13 @@ public function getInsertRows() /** * Set InsertRows. * - * @param bool $pValue + * @param bool $insertRows * * @return $this */ - public function setInsertRows($pValue) + public function setInsertRows($insertRows) { - $this->insertRows = $pValue; + $this->insertRows = $insertRows; return $this; } @@ -362,13 +394,13 @@ public function getInsertHyperlinks() /** * Set InsertHyperlinks. * - * @param bool $pValue + * @param bool $insertHyperLinks * * @return $this */ - public function setInsertHyperlinks($pValue) + public function setInsertHyperlinks($insertHyperLinks) { - $this->insertHyperlinks = $pValue; + $this->insertHyperlinks = $insertHyperLinks; return $this; } @@ -386,13 +418,13 @@ public function getDeleteColumns() /** * Set DeleteColumns. * - * @param bool $pValue + * @param bool $deleteColumns * * @return $this */ - public function setDeleteColumns($pValue) + public function setDeleteColumns($deleteColumns) { - $this->deleteColumns = $pValue; + $this->deleteColumns = $deleteColumns; return $this; } @@ -410,13 +442,13 @@ public function getDeleteRows() /** * Set DeleteRows. * - * @param bool $pValue + * @param bool $deleteRows * * @return $this */ - public function setDeleteRows($pValue) + public function setDeleteRows($deleteRows) { - $this->deleteRows = $pValue; + $this->deleteRows = $deleteRows; return $this; } @@ -434,13 +466,13 @@ public function getSelectLockedCells() /** * Set SelectLockedCells. * - * @param bool $pValue + * @param bool $selectLockedCells * * @return $this */ - public function setSelectLockedCells($pValue) + public function setSelectLockedCells($selectLockedCells) { - $this->selectLockedCells = $pValue; + $this->selectLockedCells = $selectLockedCells; return $this; } @@ -458,13 +490,13 @@ public function getSort() /** * Set Sort. * - * @param bool $pValue + * @param bool $sort * * @return $this */ - public function setSort($pValue) + public function setSort($sort) { - $this->sort = $pValue; + $this->sort = $sort; return $this; } @@ -482,13 +514,13 @@ public function getAutoFilter() /** * Set AutoFilter. * - * @param bool $pValue + * @param bool $autoFilter * * @return $this */ - public function setAutoFilter($pValue) + public function setAutoFilter($autoFilter) { - $this->autoFilter = $pValue; + $this->autoFilter = $autoFilter; return $this; } @@ -506,13 +538,13 @@ public function getPivotTables() /** * Set PivotTables. * - * @param bool $pValue + * @param bool $pivotTables * * @return $this */ - public function setPivotTables($pValue) + public function setPivotTables($pivotTables) { - $this->pivotTables = $pValue; + $this->pivotTables = $pivotTables; return $this; } @@ -530,19 +562,19 @@ public function getSelectUnlockedCells() /** * Set SelectUnlockedCells. * - * @param bool $pValue + * @param bool $selectUnlockedCells * * @return $this */ - public function setSelectUnlockedCells($pValue) + public function setSelectUnlockedCells($selectUnlockedCells) { - $this->selectUnlockedCells = $pValue; + $this->selectUnlockedCells = $selectUnlockedCells; return $this; } /** - * Get Password (hashed). + * Get hashed password. * * @return string */ @@ -554,21 +586,94 @@ public function getPassword() /** * Set Password. * - * @param string $pValue - * @param bool $pAlreadyHashed If the password has already been hashed, set this to true + * @param string $password + * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ - public function setPassword($pValue, $pAlreadyHashed = false) + public function setPassword($password, $alreadyHashed = false) { - if (!$pAlreadyHashed) { - $pValue = PasswordHasher::hashPassword($pValue); + if (!$alreadyHashed) { + $salt = $this->generateSalt(); + $this->setSalt($salt); + $password = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); } - $this->password = $pValue; + + $this->password = $password; return $this; } + /** + * Create a pseudorandom string. + */ + private function generateSalt(): string + { + return base64_encode(random_bytes(16)); + } + + /** + * Get algorithm name. + */ + public function getAlgorithm(): string + { + return $this->algorithm; + } + + /** + * Set algorithm name. + */ + public function setAlgorithm(string $algorithm): void + { + $this->algorithm = $algorithm; + } + + /** + * Get salt value. + */ + public function getSalt(): string + { + return $this->salt; + } + + /** + * Set salt value. + */ + public function setSalt(string $salt): void + { + $this->salt = $salt; + } + + /** + * Get spin count. + */ + public function getSpinCount(): int + { + return $this->spinCount; + } + + /** + * Set spin count. + */ + public function setSpinCount(int $spinCount): void + { + $this->spinCount = $spinCount; + } + + /** + * Verify that the given non-hashed password can "unlock" the protection. + */ + public function verify(string $password): bool + { + if (!$this->isProtectionEnabled()) { + return true; + } + + $hash = PasswordHasher::hashPassword($password, $this->getAlgorithm(), $this->getSalt(), $this->getSpinCount()); + + return $this->getPassword() === $hash; + } + /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php index 2a379d2c..a5f8f326 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Row.php @@ -21,10 +21,9 @@ class Row /** * Create a new row. * - * @param Worksheet $worksheet * @param int $rowIndex */ - public function __construct(Worksheet $worksheet = null, $rowIndex = 1) + public function __construct(?Worksheet $worksheet = null, $rowIndex = 1) { // Set parent and row index $this->worksheet = $worksheet; @@ -36,15 +35,13 @@ public function __construct(Worksheet $worksheet = null, $rowIndex = 1) */ public function __destruct() { - unset($this->worksheet); + $this->worksheet = null; // @phpstan-ignore-line } /** * Get row index. - * - * @return int */ - public function getRowIndex() + public function getRowIndex(): int { return $this->rowIndex; } @@ -64,10 +61,8 @@ public function getCellIterator($startColumn = 'A', $endColumn = null) /** * Returns bound worksheet. - * - * @return Worksheet */ - public function getWorksheet() + public function getWorksheet(): Worksheet { return $this->worksheet; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php index 9746d640..a78765bd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowCellIterator.php @@ -2,9 +2,13 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; +/** + * @extends CellIterator + */ class RowCellIterator extends CellIterator { /** @@ -43,7 +47,7 @@ class RowCellIterator extends CellIterator * @param string $startColumn The column address at which to start iterating * @param string $endColumn Optionally, the column address at which to stop iterating */ - public function __construct(Worksheet $worksheet = null, $rowIndex = 1, $startColumn = 'A', $endColumn = null) + public function __construct(Worksheet $worksheet, $rowIndex = 1, $startColumn = 'A', $endColumn = null) { // Set subject and row index $this->worksheet = $worksheet; @@ -57,11 +61,9 @@ public function __construct(Worksheet $worksheet = null, $rowIndex = 1, $startCo * * @param string $startColumn The column address at which to start iterating * - * @throws PhpSpreadsheetException - * * @return $this */ - public function resetStart($startColumn = 'A') + public function resetStart(string $startColumn = 'A') { $this->startColumnIndex = Coordinate::columnIndexFromString($startColumn); $this->adjustForExistingOnlyRange(); @@ -75,13 +77,11 @@ public function resetStart($startColumn = 'A') * * @param string $endColumn The column address at which to stop iterating * - * @throws PhpSpreadsheetException - * * @return $this */ public function resetEnd($endColumn = null) { - $endColumn = $endColumn ? $endColumn : $this->worksheet->getHighestColumn(); + $endColumn = $endColumn ?: $this->worksheet->getHighestColumn(); $this->endColumnIndex = Coordinate::columnIndexFromString($endColumn); $this->adjustForExistingOnlyRange(); @@ -93,18 +93,18 @@ public function resetEnd($endColumn = null) * * @param string $column The column address to set the current pointer at * - * @throws PhpSpreadsheetException - * * @return $this */ - public function seek($column = 'A') + public function seek(string $column = 'A') { + $columnx = $column; $column = Coordinate::columnIndexFromString($column); - if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { - throw new PhpSpreadsheetException("Column $column is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); - } elseif ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($column, $this->rowIndex))) { + if ($this->onlyExistingCells && !($this->worksheet->cellExistsByColumnAndRow($column, $this->rowIndex))) { throw new PhpSpreadsheetException('In "IterateOnlyExistingCells" mode and Cell does not exist'); } + if (($column < $this->startColumnIndex) || ($column > $this->endColumnIndex)) { + throw new PhpSpreadsheetException("Column $columnx is out of range ({$this->startColumnIndex} - {$this->endColumnIndex})"); + } $this->currentColumnIndex = $column; return $this; @@ -113,27 +113,23 @@ public function seek($column = 'A') /** * Rewind the iterator to the starting column. */ - public function rewind() + public function rewind(): void { $this->currentColumnIndex = $this->startColumnIndex; } /** * Return the current cell in this worksheet row. - * - * @return \PhpOffice\PhpSpreadsheet\Cell\Cell */ - public function current() + public function current(): ?Cell { return $this->worksheet->getCellByColumnAndRow($this->currentColumnIndex, $this->rowIndex); } /** * Return the current iterator key. - * - * @return string */ - public function key() + public function key(): string { return Coordinate::stringFromColumnIndex($this->currentColumnIndex); } @@ -141,7 +137,7 @@ public function key() /** * Set the iterator to its next value. */ - public function next() + public function next(): void { do { ++$this->currentColumnIndex; @@ -150,10 +146,8 @@ public function next() /** * Set the iterator to its previous value. - * - * @throws PhpSpreadsheetException */ - public function prev() + public function prev(): void { do { --$this->currentColumnIndex; @@ -162,44 +156,32 @@ public function prev() /** * Indicate if more columns exist in the worksheet range of columns that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->currentColumnIndex <= $this->endColumnIndex && $this->currentColumnIndex >= $this->startColumnIndex; } /** * Return the current iterator position. - * - * @return int */ - public function getCurrentColumnIndex() + public function getCurrentColumnIndex(): int { return $this->currentColumnIndex; } /** * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary. - * - * @throws PhpSpreadsheetException */ - protected function adjustForExistingOnlyRange() + protected function adjustForExistingOnlyRange(): void { if ($this->onlyExistingCells) { while ((!$this->worksheet->cellExistsByColumnAndRow($this->startColumnIndex, $this->rowIndex)) && ($this->startColumnIndex <= $this->endColumnIndex)) { ++$this->startColumnIndex; } - if ($this->startColumnIndex > $this->endColumnIndex) { - throw new PhpSpreadsheetException('No cells exist within the specified range'); - } while ((!$this->worksheet->cellExistsByColumnAndRow($this->endColumnIndex, $this->rowIndex)) && ($this->endColumnIndex >= $this->startColumnIndex)) { --$this->endColumnIndex; } - if ($this->endColumnIndex < $this->startColumnIndex) { - throw new PhpSpreadsheetException('No cells exist within the specified range'); - } } } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php index c4a87bdb..acaafac5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowDimension.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use PhpOffice\PhpSpreadsheet\Helper\Dimension as CssDimension; + class RowDimension extends Dimension { /** @@ -30,12 +32,12 @@ class RowDimension extends Dimension /** * Create a new RowDimension. * - * @param int $pIndex Numeric row index + * @param int $index Numeric row index */ - public function __construct($pIndex = 0) + public function __construct($index = 0) { // Initialise values - $this->rowIndex = $pIndex; + $this->rowIndex = $index; // set dimension as unformatted by default parent::__construct(null); @@ -43,10 +45,8 @@ public function __construct($pIndex = 0) /** * Get Row Index. - * - * @return int */ - public function getRowIndex() + public function getRowIndex(): int { return $this->rowIndex; } @@ -54,47 +54,52 @@ public function getRowIndex() /** * Set Row Index. * - * @param int $pValue - * * @return $this */ - public function setRowIndex($pValue) + public function setRowIndex(int $index) { - $this->rowIndex = $pValue; + $this->rowIndex = $index; return $this; } /** * Get Row Height. + * By default, this will be in points; but this method also accepts an optional unit of measure + * argument, and will convert the value from points to the specified UoM. + * A value of -1 tells Excel to display this column in its default height. * * @return float */ - public function getRowHeight() + public function getRowHeight(?string $unitOfMeasure = null) { - return $this->height; + return ($unitOfMeasure === null || $this->height < 0) + ? $this->height + : (new CssDimension($this->height . CssDimension::UOM_POINTS))->toUnit($unitOfMeasure); } /** * Set Row Height. * - * @param float $pValue + * @param float $height in points. A value of -1 tells Excel to display this column in its default height. + * By default, this will be the passed argument value; but this method also accepts an optional unit of measure + * argument, and will convert the passed argument value to points from the specified UoM * * @return $this */ - public function setRowHeight($pValue) + public function setRowHeight($height, ?string $unitOfMeasure = null) { - $this->height = $pValue; + $this->height = ($unitOfMeasure === null || $height < 0) + ? $height + : (new CssDimension("{$height}{$unitOfMeasure}"))->height(); return $this; } /** * Get ZeroHeight. - * - * @return bool */ - public function getZeroHeight() + public function getZeroHeight(): bool { return $this->zeroHeight; } @@ -102,13 +107,11 @@ public function getZeroHeight() /** * Set ZeroHeight. * - * @param bool $pValue - * * @return $this */ - public function setZeroHeight($pValue) + public function setZeroHeight(bool $zeroHeight) { - $this->zeroHeight = $pValue; + $this->zeroHeight = $zeroHeight; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php index 3b9d0e26..5c51bfee 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/RowIterator.php @@ -2,9 +2,13 @@ namespace PhpOffice\PhpSpreadsheet\Worksheet; +use Iterator; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; -class RowIterator implements \Iterator +/** + * @implements Iterator + */ +class RowIterator implements Iterator { /** * Worksheet to iterate. @@ -49,27 +53,19 @@ public function __construct(Worksheet $subject, $startRow = 1, $endRow = null) $this->resetStart($startRow); } - /** - * Destructor. - */ - public function __destruct() - { - unset($this->subject); - } - /** * (Re)Set the start row and the current row pointer. * * @param int $startRow The row number at which to start iterating * - * @throws PhpSpreadsheetException - * * @return $this */ - public function resetStart($startRow = 1) + public function resetStart(int $startRow = 1) { if ($startRow > $this->subject->getHighestRow()) { - throw new PhpSpreadsheetException("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})"); + throw new PhpSpreadsheetException( + "Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})" + ); } $this->startRow = $startRow; @@ -90,7 +86,7 @@ public function resetStart($startRow = 1) */ public function resetEnd($endRow = null) { - $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow(); + $this->endRow = $endRow ?: $this->subject->getHighestRow(); return $this; } @@ -100,11 +96,9 @@ public function resetEnd($endRow = null) * * @param int $row The row number to set the current pointer at * - * @throws PhpSpreadsheetException - * * @return $this */ - public function seek($row = 1) + public function seek(int $row = 1) { if (($row < $this->startRow) || ($row > $this->endRow)) { throw new PhpSpreadsheetException("Row $row is out of range ({$this->startRow} - {$this->endRow})"); @@ -117,27 +111,23 @@ public function seek($row = 1) /** * Rewind the iterator to the starting row. */ - public function rewind() + public function rewind(): void { $this->position = $this->startRow; } /** * Return the current row in this worksheet. - * - * @return Row */ - public function current() + public function current(): Row { return new Row($this->subject, $this->position); } /** * Return the current iterator key. - * - * @return int */ - public function key() + public function key(): int { return $this->position; } @@ -145,7 +135,7 @@ public function key() /** * Set the iterator to its next value. */ - public function next() + public function next(): void { ++$this->position; } @@ -153,17 +143,15 @@ public function next() /** * Set the iterator to its previous value. */ - public function prev() + public function prev(): void { --$this->position; } /** * Indicate if more rows exist in the worksheet range of rows that we're iterating. - * - * @return bool */ - public function valid() + public function valid(): bool { return $this->position <= $this->endRow && $this->position >= $this->startRow; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php index fa85bd27..80c4433c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/SheetView.php @@ -75,18 +75,16 @@ public function getZoomScale() * Set ZoomScale. * Valid values range from 10 to 400. * - * @param int $pValue - * - * @throws PhpSpreadsheetException + * @param int $zoomScale * * @return $this */ - public function setZoomScale($pValue) + public function setZoomScale($zoomScale) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 1 - if (($pValue >= 1) || $pValue === null) { - $this->zoomScale = $pValue; + if (($zoomScale >= 1) || $zoomScale === null) { + $this->zoomScale = $zoomScale; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } @@ -108,16 +106,14 @@ public function getZoomScaleNormal() * Set ZoomScale. * Valid values range from 10 to 400. * - * @param int $pValue - * - * @throws PhpSpreadsheetException + * @param int $zoomScaleNormal * * @return $this */ - public function setZoomScaleNormal($pValue) + public function setZoomScaleNormal($zoomScaleNormal) { - if (($pValue >= 1) || $pValue === null) { - $this->zoomScaleNormal = $pValue; + if (($zoomScaleNormal >= 1) || $zoomScaleNormal === null) { + $this->zoomScaleNormal = $zoomScaleNormal; } else { throw new PhpSpreadsheetException('Scale must be greater than or equal to 1.'); } @@ -128,11 +124,11 @@ public function setZoomScaleNormal($pValue) /** * Set ShowZeroes setting. * - * @param bool $pValue + * @param bool $showZeros */ - public function setShowZeros($pValue) + public function setShowZeros($showZeros): void { - $this->showZeros = $pValue; + $this->showZeros = $showZeros; } /** @@ -161,20 +157,18 @@ public function getView() * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW * - * @param string $pValue - * - * @throws PhpSpreadsheetException + * @param string $sheetViewType * * @return $this */ - public function setView($pValue) + public function setView($sheetViewType) { // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface - if ($pValue === null) { - $pValue = self::SHEETVIEW_NORMAL; + if ($sheetViewType === null) { + $sheetViewType = self::SHEETVIEW_NORMAL; } - if (in_array($pValue, self::$sheetViewTypes)) { - $this->sheetviewType = $pValue; + if (in_array($sheetViewType, self::$sheetViewTypes)) { + $this->sheetviewType = $sheetViewType; } else { throw new PhpSpreadsheetException('Invalid sheetview layout type.'); } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php new file mode 100644 index 00000000..66839d41 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table.php @@ -0,0 +1,454 @@ +|string $range + * A simple string containing a Cell range like 'A1:E10' is permitted + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * @param string $name (e.g. Table1) + */ + public function __construct($range = '', string $name = '') + { + $this->setRange($range); + $this->setName($name); + $this->style = new TableStyle(); + } + + /** + * Get Table name. + */ + public function getName(): string + { + return $this->name; + } + + /** + * Set Table name. + */ + public function setName(string $name): self + { + $name = trim($name); + + if (!empty($name)) { + if (strlen($name) === 1 && in_array($name, ['C', 'c', 'R', 'r'])) { + throw new PhpSpreadsheetException('The table name is invalid'); + } + if (strlen($name) > 255) { + throw new PhpSpreadsheetException('The table name cannot be longer than 255 characters'); + } + // Check for A1 or R1C1 cell reference notation + if ( + preg_match(Coordinate::A1_COORDINATE_REGEX, $name) || + preg_match('/^R\[?\-?[0-9]*\]?C\[?\-?[0-9]*\]?$/i', $name) + ) { + throw new PhpSpreadsheetException('The table name can\'t be the same as a cell reference'); + } + if (!preg_match('/^[\p{L}_\\\\]/iu', $name)) { + throw new PhpSpreadsheetException('The table name must begin a name with a letter, an underscore character (_), or a backslash (\)'); + } + if (!preg_match('/^[\p{L}_\\\\][\p{L}\p{M}0-9\._]+$/iu', $name)) { + throw new PhpSpreadsheetException('The table name contains invalid characters'); + } + } + + $this->name = $name; + + return $this; + } + + /** + * Get show Header Row. + */ + public function getShowHeaderRow(): bool + { + return $this->showHeaderRow; + } + + /** + * Set show Header Row. + */ + public function setShowHeaderRow(bool $showHeaderRow): self + { + $this->showHeaderRow = $showHeaderRow; + + return $this; + } + + /** + * Get show Totals Row. + */ + public function getShowTotalsRow(): bool + { + return $this->showTotalsRow; + } + + /** + * Set show Totals Row. + */ + public function setShowTotalsRow(bool $showTotalsRow): self + { + $this->showTotalsRow = $showTotalsRow; + + return $this; + } + + /** + * Get Table Range. + */ + public function getRange(): string + { + return $this->range; + } + + /** + * Set Table Cell Range. + * + * @param AddressRange|array|string $range + * A simple string containing a Cell range like 'A1:E10' is permitted + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + */ + public function setRange($range = ''): self + { + // extract coordinate + if ($range !== '') { + [, $range] = Worksheet::extractSheetTitle(Validations::validateCellRange($range), true); + } + if (empty($range)) { + // Discard all column rules + $this->columns = []; + $this->range = ''; + + return $this; + } + + if (strpos($range, ':') === false) { + throw new PhpSpreadsheetException('Table must be set on a range of cells.'); + } + + [$width, $height] = Coordinate::rangeDimension($range); + if ($width < 1 || $height < 2) { + throw new PhpSpreadsheetException('The table range must be at least 1 column and 2 rows'); + } + + $this->range = $range; + // Discard any column ruless that are no longer valid within this range + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + foreach ($this->columns as $key => $value) { + $colIndex = Coordinate::columnIndexFromString($key); + if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { + unset($this->columns[$key]); + } + } + + return $this; + } + + /** + * Set Table Cell Range to max row. + */ + public function setRangeToMaxRow(): self + { + if ($this->workSheet !== null) { + $thisrange = $this->range; + $range = preg_replace('/\\d+$/', (string) $this->workSheet->getHighestRow(), $thisrange) ?? ''; + if ($range !== $thisrange) { + $this->setRange($range); + } + } + + return $this; + } + + /** + * Get Table's Worksheet. + */ + public function getWorksheet(): ?Worksheet + { + return $this->workSheet; + } + + /** + * Set Table's Worksheet. + */ + public function setWorksheet(?Worksheet $worksheet = null): self + { + if ($this->name !== '' && $worksheet !== null) { + $spreadsheet = $worksheet->getParent(); + $tableName = StringHelper::strToUpper($this->name); + + foreach ($spreadsheet->getWorksheetIterator() as $sheet) { + foreach ($sheet->getTableCollection() as $table) { + if (StringHelper::strToUpper($table->getName()) === $tableName) { + throw new PhpSpreadsheetException("Workbook already contains a table named '{$this->name}'"); + } + } + } + } + + $this->workSheet = $worksheet; + + return $this; + } + + /** + * Get all Table Columns. + * + * @return Table\Column[] + */ + public function getColumns(): array + { + return $this->columns; + } + + /** + * Validate that the specified column is in the Table range. + * + * @param string $column Column name (e.g. A) + * + * @return int The column offset within the table range + */ + public function isColumnInRange(string $column): int + { + if (empty($this->range)) { + throw new PhpSpreadsheetException('No table range is defined.'); + } + + $columnIndex = Coordinate::columnIndexFromString($column); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { + throw new PhpSpreadsheetException('Column is outside of current table range.'); + } + + return $columnIndex - $rangeStart[0]; + } + + /** + * Get a specified Table Column Offset within the defined Table range. + * + * @param string $column Column name (e.g. A) + * + * @return int The offset of the specified column within the table range + */ + public function getColumnOffset($column): int + { + return $this->isColumnInRange($column); + } + + /** + * Get a specified Table Column. + * + * @param string $column Column name (e.g. A) + */ + public function getColumn($column): Table\Column + { + $this->isColumnInRange($column); + + if (!isset($this->columns[$column])) { + $this->columns[$column] = new Table\Column($column, $this); + } + + return $this->columns[$column]; + } + + /** + * Get a specified Table Column by it's offset. + * + * @param int $columnOffset Column offset within range (starting from 0) + */ + public function getColumnByOffset($columnOffset): Table\Column + { + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($this->range); + $pColumn = Coordinate::stringFromColumnIndex($rangeStart[0] + $columnOffset); + + return $this->getColumn($pColumn); + } + + /** + * Set Table. + * + * @param string|Table\Column $columnObjectOrString + * A simple string containing a Column ID like 'A' is permitted + */ + public function setColumn($columnObjectOrString): self + { + if ((is_string($columnObjectOrString)) && (!empty($columnObjectOrString))) { + $column = $columnObjectOrString; + } elseif (is_object($columnObjectOrString) && ($columnObjectOrString instanceof Table\Column)) { + $column = $columnObjectOrString->getColumnIndex(); + } else { + throw new PhpSpreadsheetException('Column is not within the table range.'); + } + $this->isColumnInRange($column); + + if (is_string($columnObjectOrString)) { + $this->columns[$columnObjectOrString] = new Table\Column($columnObjectOrString, $this); + } else { + $columnObjectOrString->setTable($this); + $this->columns[$column] = $columnObjectOrString; + } + ksort($this->columns); + + return $this; + } + + /** + * Clear a specified Table Column. + * + * @param string $column Column name (e.g. A) + */ + public function clearColumn($column): self + { + $this->isColumnInRange($column); + + if (isset($this->columns[$column])) { + unset($this->columns[$column]); + } + + return $this; + } + + /** + * Shift an Table Column Rule to a different column. + * + * Note: This method bypasses validation of the destination column to ensure it is within this Table range. + * Nor does it verify whether any column rule already exists at $toColumn, but will simply override any existing value. + * Use with caution. + * + * @param string $fromColumn Column name (e.g. A) + * @param string $toColumn Column name (e.g. B) + */ + public function shiftColumn($fromColumn, $toColumn): self + { + $fromColumn = strtoupper($fromColumn); + $toColumn = strtoupper($toColumn); + + if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { + $this->columns[$fromColumn]->setTable(); + $this->columns[$fromColumn]->setColumnIndex($toColumn); + $this->columns[$toColumn] = $this->columns[$fromColumn]; + $this->columns[$toColumn]->setTable($this); + unset($this->columns[$fromColumn]); + + ksort($this->columns); + } + + return $this; + } + + /** + * Get table Style. + */ + public function getStyle(): Table\TableStyle + { + return $this->style; + } + + /** + * Set table Style. + */ + public function setStyle(TableStyle $style): self + { + $this->style = $style; + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key === 'workSheet') { + // Detach from worksheet + $this->{$key} = null; + } else { + $this->{$key} = clone $value; + } + } elseif ((is_array($value)) && ($key === 'columns')) { + // The columns array of \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\Table objects + $this->{$key} = []; + foreach ($value as $k => $v) { + $this->{$key}[$k] = clone $v; + // attach the new cloned Column to this new cloned Table object + $this->{$key}[$k]->setTable($this); + } + } else { + $this->{$key} = $value; + } + } + } + + /** + * toString method replicates previous behavior by returning the range if object is + * referenced as a property of its worksheet. + */ + public function __toString() + { + return (string) $this->range; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php new file mode 100644 index 00000000..a7c445f5 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/Column.php @@ -0,0 +1,203 @@ +columnIndex = $column; + $this->table = $table; + } + + /** + * Get Table column index as string eg: 'A'. + */ + public function getColumnIndex(): string + { + return $this->columnIndex; + } + + /** + * Set Table column index as string eg: 'A'. + * + * @param string $column Column (e.g. A) + */ + public function setColumnIndex($column): self + { + // Uppercase coordinate + $column = strtoupper($column); + if ($this->table !== null) { + $this->table->isColumnInRange($column); + } + + $this->columnIndex = $column; + + return $this; + } + + /** + * Get show Filter Button. + */ + public function getShowFilterButton(): bool + { + return $this->showFilterButton; + } + + /** + * Set show Filter Button. + */ + public function setShowFilterButton(bool $showFilterButton): self + { + $this->showFilterButton = $showFilterButton; + + return $this; + } + + /** + * Get total Row Label. + */ + public function getTotalsRowLabel(): ?string + { + return $this->totalsRowLabel; + } + + /** + * Set total Row Label. + */ + public function setTotalsRowLabel(string $totalsRowLabel): self + { + $this->totalsRowLabel = $totalsRowLabel; + + return $this; + } + + /** + * Get total Row Function. + */ + public function getTotalsRowFunction(): ?string + { + return $this->totalsRowFunction; + } + + /** + * Set total Row Function. + */ + public function setTotalsRowFunction(string $totalsRowFunction): self + { + $this->totalsRowFunction = $totalsRowFunction; + + return $this; + } + + /** + * Get total Row Formula. + */ + public function getTotalsRowFormula(): ?string + { + return $this->totalsRowFormula; + } + + /** + * Set total Row Formula. + */ + public function setTotalsRowFormula(string $totalsRowFormula): self + { + $this->totalsRowFormula = $totalsRowFormula; + + return $this; + } + + /** + * Get column Formula. + */ + public function getColumnFormula(): ?string + { + return $this->columnFormula; + } + + /** + * Set column Formula. + */ + public function setColumnFormula(string $columnFormula): self + { + $this->columnFormula = $columnFormula; + + return $this; + } + + /** + * Get this Column's Table. + */ + public function getTable(): ?Table + { + return $this->table; + } + + /** + * Set this Column's Table. + */ + public function setTable(?Table $table = null): self + { + $this->table = $table; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php new file mode 100644 index 00000000..78643c72 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Table/TableStyle.php @@ -0,0 +1,230 @@ +theme = $theme; + } + + /** + * Get theme. + */ + public function getTheme(): string + { + return $this->theme; + } + + /** + * Set theme. + */ + public function setTheme(string $theme): self + { + $this->theme = $theme; + + return $this; + } + + /** + * Get show First Column. + */ + public function getShowFirstColumn(): bool + { + return $this->showFirstColumn; + } + + /** + * Set show First Column. + */ + public function setShowFirstColumn(bool $showFirstColumn): self + { + $this->showFirstColumn = $showFirstColumn; + + return $this; + } + + /** + * Get show Last Column. + */ + public function getShowLastColumn(): bool + { + return $this->showLastColumn; + } + + /** + * Set show Last Column. + */ + public function setShowLastColumn(bool $showLastColumn): self + { + $this->showLastColumn = $showLastColumn; + + return $this; + } + + /** + * Get show Row Stripes. + */ + public function getShowRowStripes(): bool + { + return $this->showRowStripes; + } + + /** + * Set show Row Stripes. + */ + public function setShowRowStripes(bool $showRowStripes): self + { + $this->showRowStripes = $showRowStripes; + + return $this; + } + + /** + * Get show Column Stripes. + */ + public function getShowColumnStripes(): bool + { + return $this->showColumnStripes; + } + + /** + * Set show Column Stripes. + */ + public function setShowColumnStripes(bool $showColumnStripes): self + { + $this->showColumnStripes = $showColumnStripes; + + return $this; + } + + /** + * Get this Style's Table. + */ + public function getTable(): ?Table + { + return $this->table; + } + + /** + * Set this Style's Table. + */ + public function setTable(?Table $table = null): self + { + $this->table = $table; + + return $this; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php new file mode 100644 index 00000000..b31b0813 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Validations.php @@ -0,0 +1,100 @@ +|CellAddress|string $cellAddress Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + */ + public static function validateCellAddress($cellAddress): string + { + if (is_string($cellAddress)) { + [$worksheet, $address] = Worksheet::extractSheetTitle($cellAddress, true); +// if (!empty($worksheet) && $worksheet !== $this->getTitle()) { +// throw new Exception('Reference is not for this worksheet'); +// } + + return empty($worksheet) ? strtoupper($address) : $worksheet . '!' . strtoupper($address); + } + + if (is_array($cellAddress)) { + $cellAddress = CellAddress::fromColumnRowArray($cellAddress); + } + + return (string) $cellAddress; + } + + /** + * Validate a cell address or cell range. + * + * @param AddressRange|array|CellAddress|int|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; + * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), + * or as a CellAddress or AddressRange object. + */ + public static function validateCellOrCellRange($cellRange): string + { + if (is_string($cellRange) || is_numeric($cellRange)) { + $cellRange = (string) $cellRange; + // Convert a single column reference like 'A' to 'A:A' + $cellRange = (string) preg_replace('/^([A-Z]+)$/', '${1}:${1}', $cellRange); + // Convert a single row reference like '1' to '1:1' + $cellRange = (string) preg_replace('/^(\d+)$/', '${1}:${1}', $cellRange); + } elseif (is_object($cellRange) && $cellRange instanceof CellAddress) { + $cellRange = new CellRange($cellRange, $cellRange); + } + + return self::validateCellRange($cellRange); + } + + /** + * Validate a cell range. + * + * @param AddressRange|array|string $cellRange Coordinate of the cells as a string, eg: 'C5:F12'; + * or as an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 12]), + * or as an AddressRange object. + */ + public static function validateCellRange($cellRange): string + { + if (is_string($cellRange)) { + [$worksheet, $addressRange] = Worksheet::extractSheetTitle($cellRange, true); + + // Convert Column ranges like 'A:C' to 'A1:C1048576' + $addressRange = (string) preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $addressRange); + // Convert Row ranges like '1:3' to 'A1:XFD3' + $addressRange = (string) preg_replace('/^(\\d+):(\\d+)$/', 'A${1}:XFD${2}', $addressRange); + + return empty($worksheet) ? strtoupper($addressRange) : $worksheet . '!' . strtoupper($addressRange); + } + + if (is_array($cellRange)) { + [$from, $to] = array_chunk($cellRange, 2); + $cellRange = new CellRange(CellAddress::fromColumnRowArray($from), CellAddress::fromColumnRowArray($to)); + } + + return (string) $cellRange; + } + + public static function definedNameToCoordinate(string $coordinate, Worksheet $worksheet): string + { + // Uppercase coordinate + $testCoordinate = strtoupper($coordinate); + // Eliminate leading equal sign + $testCoordinate = (string) preg_replace('/^=/', '', $coordinate); + $defined = $worksheet->getParent()->getDefinedName($testCoordinate, $worksheet); + if ($defined !== null) { + if ($defined->getWorksheet() === $worksheet && !$defined->isFormula()) { + $coordinate = (string) preg_replace('/^=/', '', $defined->getValue()); + } + } + + return $coordinate; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php index 9a3f9647..0baf6ecd 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php @@ -4,7 +4,11 @@ use ArrayObject; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; +use PhpOffice\PhpSpreadsheet\Calculation\Functions; +use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; +use PhpOffice\PhpSpreadsheet\Cell\CellAddress; +use PhpOffice\PhpSpreadsheet\Cell\CellRange; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Cell\DataValidation; @@ -13,9 +17,9 @@ use PhpOffice\PhpSpreadsheet\Collection\Cells; use PhpOffice\PhpSpreadsheet\Collection\CellsFactory; use PhpOffice\PhpSpreadsheet\Comment; +use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\IComparable; -use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared; @@ -96,16 +100,23 @@ class Worksheet implements IComparable /** * Collection of drawings. * - * @var BaseDrawing[] + * @var ArrayObject */ private $drawingCollection; /** * Collection of Chart objects. * - * @var Chart[] + * @var ArrayObject */ - private $chartCollection = []; + private $chartCollection; + + /** + * Collection of Table objects. + * + * @var ArrayObject + */ + private $tableCollection; /** * Worksheet title. @@ -180,21 +191,21 @@ class Worksheet implements IComparable /** * Collection of breaks. * - * @var array + * @var int[] */ private $breaks = []; /** * Collection of merged cell ranges. * - * @var array + * @var string[] */ private $mergeCells = []; /** * Collection of protected cell ranges. * - * @var array + * @var string[] */ private $protectedCells = []; @@ -278,9 +289,9 @@ class Worksheet implements IComparable /** * Cached highest column. * - * @var string + * @var int */ - private $cachedHighestColumn = 'A'; + private $cachedHighestColumn = 1; /** * Cached highest row. @@ -313,7 +324,7 @@ class Worksheet implements IComparable /** * Tab color. * - * @var Color + * @var null|Color */ private $tabColor; @@ -341,14 +352,13 @@ class Worksheet implements IComparable /** * Create a new worksheet. * - * @param Spreadsheet $parent - * @param string $pTitle + * @param string $title */ - public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet') + public function __construct(?Spreadsheet $parent = null, $title = 'Worksheet') { // Set parent and title $this->parent = $parent; - $this->setTitle($pTitle, false); + $this->setTitle($title, false); // setTitle can change $pTitle $this->setCodeName($this->getTitle()); $this->setSheetState(self::SHEETSTATE_VISIBLE); @@ -363,29 +373,34 @@ public function __construct(Spreadsheet $parent = null, $pTitle = 'Worksheet') // Set sheet view $this->sheetView = new SheetView(); // Drawing collection - $this->drawingCollection = new \ArrayObject(); + $this->drawingCollection = new ArrayObject(); // Chart collection - $this->chartCollection = new \ArrayObject(); + $this->chartCollection = new ArrayObject(); // Protection $this->protection = new Protection(); // Default row dimension $this->defaultRowDimension = new RowDimension(null); // Default column dimension $this->defaultColumnDimension = new ColumnDimension(null); - $this->autoFilter = new AutoFilter(null, $this); + // AutoFilter + $this->autoFilter = new AutoFilter('', $this); + // Table collection + $this->tableCollection = new ArrayObject(); } /** * Disconnect all cells from this Worksheet object, * typically so that the worksheet object can be unset. */ - public function disconnectCells() + public function disconnectCells(): void { if ($this->cellCollection !== null) { $this->cellCollection->unsetWorksheetCells(); + // @phpstan-ignore-next-line $this->cellCollection = null; } // detach ourself from the workbook, so that it can then delete this worksheet successfully + // @phpstan-ignore-next-line $this->parent = null; } @@ -397,6 +412,7 @@ public function __destruct() Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); $this->disconnectCells(); + $this->rowDimensions = []; } /** @@ -422,55 +438,53 @@ public static function getInvalidCharacters() /** * Check sheet code name for valid Excel syntax. * - * @param string $pValue The string to check - * - * @throws Exception + * @param string $sheetCodeName The string to check * * @return string The valid string */ - private static function checkSheetCodeName($pValue) + private static function checkSheetCodeName($sheetCodeName) { - $CharCount = Shared\StringHelper::countCharacters($pValue); - if ($CharCount == 0) { + $charCount = Shared\StringHelper::countCharacters($sheetCodeName); + if ($charCount == 0) { throw new Exception('Sheet code name cannot be empty.'); } // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" - if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) || - (Shared\StringHelper::substring($pValue, -1, 1) == '\'') || - (Shared\StringHelper::substring($pValue, 0, 1) == '\'')) { + if ( + (str_replace(self::$invalidCharacters, '', $sheetCodeName) !== $sheetCodeName) || + (Shared\StringHelper::substring($sheetCodeName, -1, 1) == '\'') || + (Shared\StringHelper::substring($sheetCodeName, 0, 1) == '\'') + ) { throw new Exception('Invalid character found in sheet code name'); } // Enforce maximum characters allowed for sheet title - if ($CharCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { + if ($charCount > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet code name.'); } - return $pValue; + return $sheetCodeName; } /** * Check sheet title for valid Excel syntax. * - * @param string $pValue The string to check - * - * @throws Exception + * @param string $sheetTitle The string to check * * @return string The valid string */ - private static function checkSheetTitle($pValue) + private static function checkSheetTitle($sheetTitle) { // Some of the printable ASCII characters are invalid: * : / \ ? [ ] - if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) { + if (str_replace(self::$invalidCharacters, '', $sheetTitle) !== $sheetTitle) { throw new Exception('Invalid character found in sheet title'); } // Enforce maximum characters allowed for sheet title - if (Shared\StringHelper::countCharacters($pValue) > self::SHEET_TITLE_MAXIMUM_LENGTH) { + if (Shared\StringHelper::countCharacters($sheetTitle) > self::SHEET_TITLE_MAXIMUM_LENGTH) { throw new Exception('Maximum ' . self::SHEET_TITLE_MAXIMUM_LENGTH . ' characters allowed in sheet title.'); } - return $pValue; + return $sheetTitle; } /** @@ -536,7 +550,7 @@ public function getDefaultColumnDimension() /** * Get collection of drawings. * - * @return BaseDrawing[] + * @return ArrayObject */ public function getDrawingCollection() { @@ -546,7 +560,7 @@ public function getDrawingCollection() /** * Get collection of charts. * - * @return Chart[] + * @return ArrayObject */ public function getChartCollection() { @@ -556,22 +570,22 @@ public function getChartCollection() /** * Add chart. * - * @param Chart $pChart - * @param null|int $iChartIndex Index where chart should go (0,1,..., or null for last) + * @param null|int $chartIndex Index where chart should go (0,1,..., or null for last) * * @return Chart */ - public function addChart(Chart $pChart, $iChartIndex = null) + public function addChart(Chart $chart, $chartIndex = null) { - $pChart->setWorksheet($this); - if ($iChartIndex === null) { - $this->chartCollection[] = $pChart; + $chart->setWorksheet($this); + if ($chartIndex === null) { + $this->chartCollection[] = $chart; } else { // Insert the chart at the requested index - array_splice($this->chartCollection, $iChartIndex, 0, [$pChart]); + // @phpstan-ignore-next-line + array_splice($this->chartCollection, $chartIndex, 0, [$chart]); } - return $pChart; + return $chart; } /** @@ -729,9 +743,19 @@ public function calculateColumnWidths() } } + $autoFilterRange = $autoFilterFirstRowRange = $this->autoFilter->getRange(); + if (!empty($autoFilterRange)) { + $autoFilterRangeBoundaries = Coordinate::rangeBoundaries($autoFilterRange); + $autoFilterFirstRowRange = (string) new CellRange( + CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[0][0], $autoFilterRangeBoundaries[0][1]), + CellAddress::fromColumnAndRow($autoFilterRangeBoundaries[1][0], $autoFilterRangeBoundaries[0][1]) + ); + } + // loop through all cells in the worksheet foreach ($this->getCoordinates(false) as $coordinate) { - $cell = $this->getCell($coordinate, false); + $cell = $this->getCellOrNull($coordinate); + if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { //Determine if cell is in merge range $isMerged = isset($isMergeCell[$this->cellCollection->getCurrentCoordinate()]); @@ -748,24 +772,36 @@ public function calculateColumnWidths() } } - // Determine width if cell does not participate in a merge or does and is a value cell of 1-column wide range + // Determine width if cell is not part of a merge or does and is a value cell of 1-column wide range if (!$isMerged || $isMergedButProceed) { + // Determine if we need to make an adjustment for the first row in an AutoFilter range that + // has a column filter dropdown + $filterAdjustment = false; + if (!empty($autoFilterRange) && $cell->isInRange($autoFilterFirstRowRange)) { + $filterAdjustment = true; + } + // Calculated value // To formatted string $cellValue = NumberFormat::toFormattedString( $cell->getCalculatedValue(), - $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() + $this->getParent()->getCellXfByIndex($cell->getXfIndex()) + ->getNumberFormat()->getFormatCode() ); - $autoSizes[$this->cellCollection->getCurrentColumn()] = max( - (float) $autoSizes[$this->cellCollection->getCurrentColumn()], - (float) Shared\Font::calculateColumnWidth( - $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), - $cellValue, - $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), - $this->getParent()->getDefaultStyle()->getFont() - ) - ); + if ($cellValue !== null && $cellValue !== '') { + $autoSizes[$this->cellCollection->getCurrentColumn()] = max( + (float) $autoSizes[$this->cellCollection->getCurrentColumn()], + (float) Shared\Font::calculateColumnWidth( + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), + $cellValue, + $this->getParent()->getCellXfByIndex($cell->getXfIndex()) + ->getAlignment()->getTextRotation(), + $this->getParent()->getDefaultStyle()->getFont(), + $filterAdjustment + ) + ); + } } } } @@ -795,16 +831,14 @@ public function getParent() /** * Re-bind parent. * - * @param Spreadsheet $parent - * * @return $this */ public function rebindParent(Spreadsheet $parent) { if ($this->parent !== null) { - $namedRanges = $this->parent->getNamedRanges(); - foreach ($namedRanges as $namedRange) { - $parent->addNamedRange($namedRange); + $definedNames = $this->parent->getDefinedNames(); + foreach ($definedNames as $definedName) { + $parent->addDefinedName($definedName); } $this->parent->removeSheetByIndex( @@ -829,7 +863,7 @@ public function getTitle() /** * Set title. * - * @param string $pValue String containing the dimension of this worksheet + * @param string $title String containing the dimension of this worksheet * @param bool $updateFormulaCellReferences Flag indicating whether cell references in formulae should * be updated to reflect the new sheet name. * This should be left as the default true, unless you are @@ -840,10 +874,10 @@ public function getTitle() * * @return $this */ - public function setTitle($pValue, $updateFormulaCellReferences = true, $validate = true) + public function setTitle($title, $updateFormulaCellReferences = true, $validate = true) { // Is this a 'rename' or not? - if ($this->getTitle() == $pValue) { + if ($this->getTitle() == $title) { return $this; } @@ -852,37 +886,37 @@ public function setTitle($pValue, $updateFormulaCellReferences = true, $validate if ($validate) { // Syntax check - self::checkSheetTitle($pValue); + self::checkSheetTitle($title); if ($this->parent) { // Is there already such sheet name? - if ($this->parent->sheetNameExists($pValue)) { + if ($this->parent->sheetNameExists($title)) { // Use name, but append with lowest possible integer - if (Shared\StringHelper::countCharacters($pValue) > 29) { - $pValue = Shared\StringHelper::substring($pValue, 0, 29); + if (Shared\StringHelper::countCharacters($title) > 29) { + $title = Shared\StringHelper::substring($title, 0, 29); } $i = 1; - while ($this->parent->sheetNameExists($pValue . ' ' . $i)) { + while ($this->parent->sheetNameExists($title . ' ' . $i)) { ++$i; if ($i == 10) { - if (Shared\StringHelper::countCharacters($pValue) > 28) { - $pValue = Shared\StringHelper::substring($pValue, 0, 28); + if (Shared\StringHelper::countCharacters($title) > 28) { + $title = Shared\StringHelper::substring($title, 0, 28); } } elseif ($i == 100) { - if (Shared\StringHelper::countCharacters($pValue) > 27) { - $pValue = Shared\StringHelper::substring($pValue, 0, 27); + if (Shared\StringHelper::countCharacters($title) > 27) { + $title = Shared\StringHelper::substring($title, 0, 27); } } } - $pValue .= " $i"; + $title .= " $i"; } } } // Set title - $this->title = $pValue; + $this->title = $title; $this->dirty = true; if ($this->parent && $this->parent->getCalculationEngine()) { @@ -935,13 +969,11 @@ public function getPageSetup() /** * Set page setup. * - * @param PageSetup $pValue - * * @return $this */ - public function setPageSetup(PageSetup $pValue) + public function setPageSetup(PageSetup $pageSetup) { - $this->pageSetup = $pValue; + $this->pageSetup = $pageSetup; return $this; } @@ -959,13 +991,11 @@ public function getPageMargins() /** * Set page margins. * - * @param PageMargins $pValue - * * @return $this */ - public function setPageMargins(PageMargins $pValue) + public function setPageMargins(PageMargins $pageMargins) { - $this->pageMargins = $pValue; + $this->pageMargins = $pageMargins; return $this; } @@ -983,13 +1013,11 @@ public function getHeaderFooter() /** * Set page header/footer. * - * @param HeaderFooter $pValue - * * @return $this */ - public function setHeaderFooter(HeaderFooter $pValue) + public function setHeaderFooter(HeaderFooter $headerFooter) { - $this->headerFooter = $pValue; + $this->headerFooter = $headerFooter; return $this; } @@ -1007,13 +1035,11 @@ public function getSheetView() /** * Set sheet view. * - * @param SheetView $pValue - * * @return $this */ - public function setSheetView(SheetView $pValue) + public function setSheetView(SheetView $sheetView) { - $this->sheetView = $pValue; + $this->sheetView = $sheetView; return $this; } @@ -1031,13 +1057,11 @@ public function getProtection() /** * Set Protection. * - * @param Protection $pValue - * * @return $this */ - public function setProtection(Protection $pValue) + public function setProtection(Protection $protection) { - $this->protection = $pValue; + $this->protection = $protection; $this->dirty = true; return $this; @@ -1046,15 +1070,15 @@ public function setProtection(Protection $pValue) /** * Get highest worksheet column. * - * @param string $row Return the data highest column for the specified row, + * @param null|int|string $row Return the data highest column for the specified row, * or the highest column of any row if no row number is passed * * @return string Highest column name */ public function getHighestColumn($row = null) { - if ($row == null) { - return $this->cachedHighestColumn; + if ($row === null) { + return Coordinate::stringFromColumnIndex($this->cachedHighestColumn); } return $this->getHighestDataColumn($row); @@ -1063,7 +1087,7 @@ public function getHighestColumn($row = null) /** * Get highest worksheet column that contains data. * - * @param string $row Return the highest data column for the specified row, + * @param null|int|string $row Return the highest data column for the specified row, * or the highest data column of any row if no row number is passed * * @return string Highest column name that contains data @@ -1076,14 +1100,14 @@ public function getHighestDataColumn($row = null) /** * Get highest worksheet row. * - * @param string $column Return the highest data row for the specified column, + * @param null|string $column Return the highest data row for the specified column, * or the highest row of any column if no column letter is passed * * @return int Highest row number */ public function getHighestRow($column = null) { - if ($column == null) { + if ($column === null) { return $this->cachedHighestRow; } @@ -1093,7 +1117,7 @@ public function getHighestRow($column = null) /** * Get highest worksheet row that contains data. * - * @param string $column Return the highest data row for the specified column, + * @param null|string $column Return the highest data row for the specified column, * or the highest data row of any column if no column letter is passed * * @return int Highest row number that contains data @@ -1116,14 +1140,16 @@ public function getHighestRowAndColumn() /** * Set a cell value. * - * @param string $pCoordinate Coordinate of the cell, eg: 'A1' - * @param mixed $pValue Value of the cell + * @param array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * @param mixed $value Value for the cell * * @return $this */ - public function setCellValue($pCoordinate, $pValue) + public function setCellValue($coordinate, $value) { - $this->getCell($pCoordinate)->setValue($pValue); + $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); + $this->getCell($cellAddress)->setValue($value); return $this; } @@ -1131,6 +1157,10 @@ public function setCellValue($pCoordinate, $pValue) /** * Set a cell value by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the setCellValue() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell @@ -1139,7 +1169,7 @@ public function setCellValue($pCoordinate, $pValue) */ public function setCellValueByColumnAndRow($columnIndex, $row, $value) { - $this->getCellByColumnAndRow($columnIndex, $row)->setValue($value); + $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row)->setValue($value); return $this; } @@ -1147,16 +1177,17 @@ public function setCellValueByColumnAndRow($columnIndex, $row, $value) /** * Set a cell value. * - * @param string $pCoordinate Coordinate of the cell, eg: 'A1' - * @param mixed $pValue Value of the cell - * @param string $pDataType Explicit data type, see DataType::TYPE_* + * @param array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * @param mixed $value Value of the cell + * @param string $dataType Explicit data type, see DataType::TYPE_* * * @return $this */ - public function setCellValueExplicit($pCoordinate, $pValue, $pDataType) + public function setCellValueExplicit($coordinate, $value, $dataType) { - // Set value - $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType); + $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); + $this->getCell($cellAddress)->setValueExplicit($value, $dataType); return $this; } @@ -1164,6 +1195,10 @@ public function setCellValueExplicit($pCoordinate, $pValue, $pDataType) /** * Set a cell value by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the setCellValueExplicit() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param mixed $value Value of the cell @@ -1173,7 +1208,7 @@ public function setCellValueExplicit($pCoordinate, $pValue, $pDataType) */ public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $dataType) { - $this->getCellByColumnAndRow($columnIndex, $row)->setValueExplicit($value, $dataType); + $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row)->setValueExplicit($value, $dataType); return $this; } @@ -1181,101 +1216,144 @@ public function setCellValueExplicitByColumnAndRow($columnIndex, $row, $value, $ /** * Get cell at a specific coordinate. * - * @param string $pCoordinate Coordinate of the cell, eg: 'A1' - * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't - * already exist, or a null should be returned instead - * - * @throws Exception + * @param array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * - * @return null|Cell Cell that was found/created or null + * @return Cell Cell that was found or created */ - public function getCell($pCoordinate, $createIfNotExists = true) + public function getCell($coordinate): Cell { - // Uppercase coordinate - $pCoordinateUpper = strtoupper($pCoordinate); + $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); - // Check cell collection - if ($this->cellCollection->has($pCoordinateUpper)) { - return $this->cellCollection->get($pCoordinateUpper); + // Shortcut for increased performance for the vast majority of simple cases + if ($this->cellCollection->has($cellAddress)) { + /** @var Cell $cell */ + $cell = $this->cellCollection->get($cellAddress); + + return $cell; } + /** @var Worksheet $sheet */ + [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); + $cell = $sheet->cellCollection->get($finalCoordinate); + + return $cell ?? $sheet->createNewCell($finalCoordinate); + } + + /** + * Get the correct Worksheet and coordinate from a coordinate that may + * contains reference to another sheet or a named range. + * + * @return array{0: Worksheet, 1: string} + */ + private function getWorksheetAndCoordinate(string $coordinate): array + { + $sheet = null; + $finalCoordinate = null; + // Worksheet reference? - if (strpos($pCoordinate, '!') !== false) { - $worksheetReference = self::extractSheetTitle($pCoordinate, true); + if (strpos($coordinate, '!') !== false) { + $worksheetReference = self::extractSheetTitle($coordinate, true); - return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); - } + $sheet = $this->parent->getSheetByName($worksheetReference[0]); + $finalCoordinate = strtoupper($worksheetReference[1]); - // Named range? - if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && - (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { - $namedRange = NamedRange::resolveRange($pCoordinate, $this); + if ($sheet === null) { + throw new Exception('Sheet not found for name: ' . $worksheetReference[0]); + } + } elseif ( + !preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $coordinate) && + preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/i', $coordinate) + ) { + // Named range? + $namedRange = $this->validateNamedRange($coordinate, true); if ($namedRange !== null) { - $pCoordinate = $namedRange->getRange(); + $sheet = $namedRange->getWorksheet(); + if ($sheet === null) { + throw new Exception('Sheet not found for named range: ' . $namedRange->getName()); + } - return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); + /** @phpstan-ignore-next-line */ + $cellCoordinate = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $finalCoordinate = str_replace('$', '', $cellCoordinate); } } - if (Coordinate::coordinateIsRange($pCoordinate)) { - throw new Exception('Cell coordinate can not be a range of cells.'); - } elseif (strpos($pCoordinate, '$') !== false) { + if ($sheet === null || $finalCoordinate === null) { + $sheet = $this; + $finalCoordinate = strtoupper($coordinate); + } + + if (Coordinate::coordinateIsRange($finalCoordinate)) { + throw new Exception('Cell coordinate string can not be a range of cells.'); + } elseif (strpos($finalCoordinate, '$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } - // Create new cell object, if required - return $createIfNotExists ? $this->createNewCell($pCoordinateUpper) : null; + return [$sheet, $finalCoordinate]; } /** - * Get cell at a specific coordinate by using numeric cell coordinates. + * Get an existing cell at a specific coordinate, or null. * - * @param int $columnIndex Numeric column coordinate of the cell - * @param int $row Numeric row coordinate of the cell - * @param bool $createIfNotExists Flag indicating whether a new cell should be created if it doesn't - * already exist, or a null should be returned instead + * @param string $coordinate Coordinate of the cell, eg: 'A1' * - * @return null|Cell Cell that was found/created or null + * @return null|Cell Cell that was found or null */ - public function getCellByColumnAndRow($columnIndex, $row, $createIfNotExists = true) + private function getCellOrNull($coordinate): ?Cell { - $columnLetter = Coordinate::stringFromColumnIndex($columnIndex); - $coordinate = $columnLetter . $row; - + // Check cell collection if ($this->cellCollection->has($coordinate)) { return $this->cellCollection->get($coordinate); } - // Create new cell object, if required - return $createIfNotExists ? $this->createNewCell($coordinate) : null; + return null; + } + + /** + * Get cell at a specific coordinate by using numeric cell coordinates. + * + * @Deprecated 1.23.0 + * Use the getCell() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * + * @param int $columnIndex Numeric column coordinate of the cell + * @param int $row Numeric row coordinate of the cell + * + * @return Cell Cell that was found/created or null + */ + public function getCellByColumnAndRow($columnIndex, $row): Cell + { + return $this->getCell(Coordinate::stringFromColumnIndex($columnIndex) . $row); } /** * Create a new cell at the specified coordinate. * - * @param string $pCoordinate Coordinate of the cell + * @param string $coordinate Coordinate of the cell * * @return Cell Cell that was created */ - private function createNewCell($pCoordinate) + public function createNewCell($coordinate) { $cell = new Cell(null, DataType::TYPE_NULL, $this); - $this->cellCollection->add($pCoordinate, $cell); + $this->cellCollection->add($coordinate, $cell); $this->cellCollectionIsSorted = false; // Coordinates - $aCoordinates = Coordinate::coordinateFromString($pCoordinate); - if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($aCoordinates[0])) { - $this->cachedHighestColumn = $aCoordinates[0]; + [$column, $row] = Coordinate::coordinateFromString($coordinate); + $aIndexes = Coordinate::indexesFromString($coordinate); + if ($this->cachedHighestColumn < $aIndexes[0]) { + $this->cachedHighestColumn = $aIndexes[0]; } - if ($aCoordinates[1] > $this->cachedHighestRow) { - $this->cachedHighestRow = $aCoordinates[1]; + if ($aIndexes[1] > $this->cachedHighestRow) { + $this->cachedHighestRow = $aIndexes[1]; } // Cell needs appropriate xfIndex from dimensions records // but don't create dimension records if they don't already exist - $rowDimension = $this->getRowDimension($aCoordinates[1], false); - $columnDimension = $this->getColumnDimension($aCoordinates[0], false); + $rowDimension = $this->rowDimensions[$row] ?? null; + $columnDimension = $this->columnDimensions[$column] ?? null; if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { // then there is a row dimension with explicit style, assign it to the cell @@ -1291,61 +1369,29 @@ private function createNewCell($pCoordinate) /** * Does the cell at a specific coordinate exist? * - * @param string $pCoordinate Coordinate of the cell eg: 'A1' - * - * @throws Exception - * - * @return bool + * @param array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. */ - public function cellExists($pCoordinate) + public function cellExists($coordinate): bool { - // Worksheet reference? - if (strpos($pCoordinate, '!') !== false) { - $worksheetReference = self::extractSheetTitle($pCoordinate, true); - - return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); - } - - // Named range? - if ((!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $pCoordinate, $matches)) && - (preg_match('/^' . Calculation::CALCULATION_REGEXP_NAMEDRANGE . '$/i', $pCoordinate, $matches))) { - $namedRange = NamedRange::resolveRange($pCoordinate, $this); - if ($namedRange !== null) { - $pCoordinate = $namedRange->getRange(); - if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { - if (!$namedRange->getLocalOnly()) { - return $namedRange->getWorksheet()->cellExists($pCoordinate); - } - - throw new Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); - } - } else { - return false; - } - } - - // Uppercase coordinate - $pCoordinate = strtoupper($pCoordinate); + $cellAddress = Validations::validateCellAddress($coordinate); + /** @var Worksheet $sheet */ + [$sheet, $finalCoordinate] = $this->getWorksheetAndCoordinate($cellAddress); - if (Coordinate::coordinateIsRange($pCoordinate)) { - throw new Exception('Cell coordinate can not be a range of cells.'); - } elseif (strpos($pCoordinate, '$') !== false) { - throw new Exception('Cell coordinate must not be absolute.'); - } - - // Cell exists? - return $this->cellCollection->has($pCoordinate); + return $sheet->cellCollection->has($finalCoordinate); } /** * Cell at a specific coordinate by using numeric cell coordinates exists? * + * @Deprecated 1.23.0 + * Use the cellExists() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell - * - * @return bool */ - public function cellExistsByColumnAndRow($columnIndex, $row) + public function cellExistsByColumnAndRow($columnIndex, $row): bool { return $this->cellExists(Coordinate::stringFromColumnIndex($columnIndex) . $row); } @@ -1353,65 +1399,49 @@ public function cellExistsByColumnAndRow($columnIndex, $row) /** * Get row dimension at a specific row. * - * @param int $pRow Numeric index of the row - * @param bool $create - * - * @return RowDimension + * @param int $row Numeric index of the row */ - public function getRowDimension($pRow, $create = true) + public function getRowDimension(int $row): RowDimension { - // Found - $found = null; - // Get row dimension - if (!isset($this->rowDimensions[$pRow])) { - if (!$create) { - return null; - } - $this->rowDimensions[$pRow] = new RowDimension($pRow); + if (!isset($this->rowDimensions[$row])) { + $this->rowDimensions[$row] = new RowDimension($row); - $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); + $this->cachedHighestRow = max($this->cachedHighestRow, $row); } - return $this->rowDimensions[$pRow]; + return $this->rowDimensions[$row]; } /** * Get column dimension at a specific column. * - * @param string $pColumn String index of the column eg: 'A' - * @param bool $create - * - * @return ColumnDimension + * @param string $column String index of the column eg: 'A' */ - public function getColumnDimension($pColumn, $create = true) + public function getColumnDimension(string $column): ColumnDimension { // Uppercase coordinate - $pColumn = strtoupper($pColumn); + $column = strtoupper($column); // Fetch dimensions - if (!isset($this->columnDimensions[$pColumn])) { - if (!$create) { - return null; - } - $this->columnDimensions[$pColumn] = new ColumnDimension($pColumn); + if (!isset($this->columnDimensions[$column])) { + $this->columnDimensions[$column] = new ColumnDimension($column); - if (Coordinate::columnIndexFromString($this->cachedHighestColumn) < Coordinate::columnIndexFromString($pColumn)) { - $this->cachedHighestColumn = $pColumn; + $columnIndex = Coordinate::columnIndexFromString($column); + if ($this->cachedHighestColumn < $columnIndex) { + $this->cachedHighestColumn = $columnIndex; } } - return $this->columnDimensions[$pColumn]; + return $this->columnDimensions[$column]; } /** * Get column dimension at a specific column by using numeric cell coordinates. * * @param int $columnIndex Numeric column coordinate of the cell - * - * @return ColumnDimension */ - public function getColumnDimensionByColumn($columnIndex) + public function getColumnDimensionByColumn(int $columnIndex): ColumnDimension { return $this->getColumnDimension(Coordinate::stringFromColumnIndex($columnIndex)); } @@ -1429,62 +1459,130 @@ public function getStyles() /** * Get style for cell. * - * @param string $pCellCoordinate Cell coordinate (or range) to get style for, eg: 'A1' - * - * @throws Exception - * - * @return Style + * @param AddressRange|array|CellAddress|int|string $cellCoordinate + * A simple string containing a cell address like 'A1' or a cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or a CellAddress or AddressRange object. */ - public function getStyle($pCellCoordinate) + public function getStyle($cellCoordinate): Style { + $cellCoordinate = Validations::validateCellOrCellRange($cellCoordinate); + // set this sheet as active $this->parent->setActiveSheetIndex($this->parent->getIndex($this)); // set cell coordinate as active - $this->setSelectedCells($pCellCoordinate); + $this->setSelectedCells($cellCoordinate); return $this->parent->getCellXfSupervisor(); } + /** + * Get style for cell by using numeric cell coordinates. + * + * @Deprecated 1.23.0 + * Use the getStyle() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * + * @param int $columnIndex1 Numeric column coordinate of the cell + * @param int $row1 Numeric row coordinate of the cell + * @param null|int $columnIndex2 Numeric column coordinate of the range cell + * @param null|int $row2 Numeric row coordinate of the range cell + * + * @return Style + */ + public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null) + { + if ($columnIndex2 !== null && $row2 !== null) { + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) + ); + + return $this->getStyle($cellRange); + } + + return $this->getStyle(CellAddress::fromColumnAndRow($columnIndex1, $row1)); + } + /** * Get conditional styles for a cell. * - * @param string $pCoordinate eg: 'A1' + * @param string $coordinate eg: 'A1' or 'A1:A3'. + * If a single cell is referenced, then the array of conditional styles will be returned if the cell is + * included in a conditional style range. + * If a range of cells is specified, then the styles will only be returned if the range matches the entire + * range of the conditional. * * @return Conditional[] */ - public function getConditionalStyles($pCoordinate) + public function getConditionalStyles(string $coordinate): array + { + $coordinate = strtoupper($coordinate); + if (strpos($coordinate, ':') !== false) { + return $this->conditionalStylesCollection[$coordinate] ?? []; + } + + $cell = $this->getCell($coordinate); + foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { + if ($cell->isInRange($conditionalRange)) { + return $this->conditionalStylesCollection[$conditionalRange]; + } + } + + return []; + } + + public function getConditionalRange(string $coordinate): ?string { - $pCoordinate = strtoupper($pCoordinate); - if (!isset($this->conditionalStylesCollection[$pCoordinate])) { - $this->conditionalStylesCollection[$pCoordinate] = []; + $coordinate = strtoupper($coordinate); + $cell = $this->getCell($coordinate); + foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { + if ($cell->isInRange($conditionalRange)) { + return $conditionalRange; + } } - return $this->conditionalStylesCollection[$pCoordinate]; + return null; } /** * Do conditional styles exist for this cell? * - * @param string $pCoordinate eg: 'A1' - * - * @return bool + * @param string $coordinate eg: 'A1' or 'A1:A3'. + * If a single cell is specified, then this method will return true if that cell is included in a + * conditional style range. + * If a range of cells is specified, then true will only be returned if the range matches the entire + * range of the conditional. */ - public function conditionalStylesExists($pCoordinate) + public function conditionalStylesExists($coordinate): bool { - return isset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); + $coordinate = strtoupper($coordinate); + if (strpos($coordinate, ':') !== false) { + return isset($this->conditionalStylesCollection[$coordinate]); + } + + $cell = $this->getCell($coordinate); + foreach (array_keys($this->conditionalStylesCollection) as $conditionalRange) { + if ($cell->isInRange($conditionalRange)) { + return true; + } + } + + return false; } /** * Removes conditional styles for a cell. * - * @param string $pCoordinate eg: 'A1' + * @param string $coordinate eg: 'A1' * * @return $this */ - public function removeConditionalStyles($pCoordinate) + public function removeConditionalStyles($coordinate) { - unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); + unset($this->conditionalStylesCollection[strtoupper($coordinate)]); return $this; } @@ -1502,66 +1600,43 @@ public function getConditionalStylesCollection() /** * Set conditional styles. * - * @param string $pCoordinate eg: 'A1' - * @param $pValue Conditional[] + * @param string $coordinate eg: 'A1' + * @param Conditional[] $styles * * @return $this */ - public function setConditionalStyles($pCoordinate, $pValue) + public function setConditionalStyles($coordinate, $styles) { - $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue; + $this->conditionalStylesCollection[strtoupper($coordinate)] = $styles; return $this; } - /** - * Get style for cell by using numeric cell coordinates. - * - * @param int $columnIndex1 Numeric column coordinate of the cell - * @param int $row1 Numeric row coordinate of the cell - * @param null|int $columnIndex2 Numeric column coordinate of the range cell - * @param null|int $row2 Numeric row coordinate of the range cell - * - * @return Style - */ - public function getStyleByColumnAndRow($columnIndex1, $row1, $columnIndex2 = null, $row2 = null) - { - if ($columnIndex2 !== null && $row2 !== null) { - $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; - - return $this->getStyle($cellRange); - } - - return $this->getStyle(Coordinate::stringFromColumnIndex($columnIndex1) . $row1); - } - /** * Duplicate cell style to a range of cells. * * Please note that this will overwrite existing cell styles for cells in range! * - * @param Style $pCellStyle Cell style to duplicate - * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") - * - * @throws Exception + * @param Style $style Cell style to duplicate + * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ - public function duplicateStyle(Style $pCellStyle, $pRange) + public function duplicateStyle(Style $style, $range) { // Add the style to the workbook if necessary $workbook = $this->parent; - if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) { + if ($existingStyle = $this->parent->getCellXfByHashCode($style->getHashCode())) { // there is already such cell Xf in our collection $xfIndex = $existingStyle->getIndex(); } else { // we don't have such a cell Xf, need to add - $workbook->addCellXf($pCellStyle); - $xfIndex = $pCellStyle->getIndex(); + $workbook->addCellXf($style); + $xfIndex = $style->getIndex(); } // Calculate range outer borders - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange . ':' . $pRange); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { @@ -1585,23 +1660,21 @@ public function duplicateStyle(Style $pCellStyle, $pRange) * * Please note that this will overwrite existing cell styles for cells in range! * - * @param Conditional[] $pCellStyle Cell style to duplicate - * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") - * - * @throws Exception + * @param Conditional[] $styles Cell style to duplicate + * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * * @return $this */ - public function duplicateConditionalStyle(array $pCellStyle, $pRange = '') + public function duplicateConditionalStyle(array $styles, $range = '') { - foreach ($pCellStyle as $cellStyle) { + foreach ($styles as $cellStyle) { if (!($cellStyle instanceof Conditional)) { throw new Exception('Style is not a conditional style'); } } // Calculate range outer borders - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange . ':' . $pRange); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range . ':' . $range); // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { @@ -1613,7 +1686,7 @@ public function duplicateConditionalStyle(array $pCellStyle, $pRange = '') // Loop through cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { - $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $pCellStyle); + $this->setConditionalStyles(Coordinate::stringFromColumnIndex($col) . $row, $styles); } } @@ -1623,28 +1696,22 @@ public function duplicateConditionalStyle(array $pCellStyle, $pRange = '') /** * Set break on a cell. * - * @param string $pCoordinate Cell coordinate (e.g. A1) - * @param int $pBreak Break type (type of Worksheet::BREAK_*) - * - * @throws Exception + * @param array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * @param int $break Break type (type of Worksheet::BREAK_*) * * @return $this */ - public function setBreak($pCoordinate, $pBreak) + public function setBreak($coordinate, $break) { - // Uppercase coordinate - $pCoordinate = strtoupper($pCoordinate); + $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)); - if ($pCoordinate != '') { - if ($pBreak == self::BREAK_NONE) { - if (isset($this->breaks[$pCoordinate])) { - unset($this->breaks[$pCoordinate]); - } - } else { - $this->breaks[$pCoordinate] = $pBreak; + if ($break === self::BREAK_NONE) { + if (isset($this->breaks[$cellAddress])) { + unset($this->breaks[$cellAddress]); } } else { - throw new Exception('No cell coordinate specified.'); + $this->breaks[$cellAddress] = $break; } return $this; @@ -1653,6 +1720,10 @@ public function setBreak($pCoordinate, $pBreak) /** * Set break on a cell by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the setBreak() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @param int $break Break type (type of Worksheet::BREAK_*) @@ -1667,7 +1738,7 @@ public function setBreakByColumnAndRow($columnIndex, $row, $break) /** * Get breaks. * - * @return array[] + * @return int[] */ public function getBreaks() { @@ -1677,37 +1748,38 @@ public function getBreaks() /** * Set merge on a cell range. * - * @param string $pRange Cell range (e.g. A1:E1) - * - * @throws Exception + * @param AddressRange|array|string $range A simple string containing a Cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange. * * @return $this */ - public function mergeCells($pRange) + public function mergeCells($range) { - // Uppercase coordinate - $pRange = strtoupper($pRange); - - if (strpos($pRange, ':') !== false) { - $this->mergeCells[$pRange] = $pRange; + $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); - // make sure cells are created - - // get the cells in the range - $aReferences = Coordinate::extractAllCellReferencesInRange($pRange); + if (preg_match('/^([A-Z]+)(\\d+):([A-Z]+)(\\d+)$/', $range, $matches) === 1) { + $this->mergeCells[$range] = $range; + $firstRow = (int) $matches[2]; + $lastRow = (int) $matches[4]; + $firstColumn = $matches[1]; + $lastColumn = $matches[3]; + $firstColumnIndex = Coordinate::columnIndexFromString($firstColumn); + $lastColumnIndex = Coordinate::columnIndexFromString($lastColumn); + $numberRows = $lastRow - $firstRow; + $numberColumns = $lastColumnIndex - $firstColumnIndex; // create upper left cell if it does not already exist - $upperLeft = $aReferences[0]; + $upperLeft = "{$firstColumn}{$firstRow}"; if (!$this->cellExists($upperLeft)) { $this->getCell($upperLeft)->setValueExplicit(null, DataType::TYPE_NULL); } // Blank out the rest of the cells in the range (if they exist) - $count = count($aReferences); - for ($i = 1; $i < $count; ++$i) { - if ($this->cellExists($aReferences[$i])) { - $this->getCell($aReferences[$i])->setValueExplicit(null, DataType::TYPE_NULL); - } + if ($numberRows > $numberColumns) { + $this->clearMergeCellsByColumn($firstColumn, $lastColumn, $firstRow, $lastRow, $upperLeft); + } else { + $this->clearMergeCellsByRow($firstColumn, $lastColumnIndex, $firstRow, $lastRow, $upperLeft); } } else { throw new Exception('Merge must be set on a range of cells.'); @@ -1716,21 +1788,68 @@ public function mergeCells($pRange) return $this; } + private function clearMergeCellsByColumn(string $firstColumn, string $lastColumn, int $firstRow, int $lastRow, string $upperLeft): void + { + foreach ($this->getColumnIterator($firstColumn, $lastColumn) as $column) { + $iterator = $column->getCellIterator($firstRow); + $iterator->setIterateOnlyExistingCells(true); + foreach ($iterator as $cell) { + if ($cell !== null) { + $row = $cell->getRow(); + if ($row > $lastRow) { + break; + } + $thisCell = $cell->getColumn() . $row; + if ($upperLeft !== $thisCell) { + $cell->setValueExplicit(null, DataType::TYPE_NULL); + } + } + } + } + } + + private function clearMergeCellsByRow(string $firstColumn, int $lastColumnIndex, int $firstRow, int $lastRow, string $upperLeft): void + { + foreach ($this->getRowIterator($firstRow, $lastRow) as $row) { + $iterator = $row->getCellIterator($firstColumn); + $iterator->setIterateOnlyExistingCells(true); + foreach ($iterator as $cell) { + if ($cell !== null) { + $column = $cell->getColumn(); + $columnIndex = Coordinate::columnIndexFromString($column); + if ($columnIndex > $lastColumnIndex) { + break; + } + $thisCell = $column . $cell->getRow(); + if ($upperLeft !== $thisCell) { + $cell->setValueExplicit(null, DataType::TYPE_NULL); + } + } + } + } + } + /** * Set merge on a cell range by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the mergeCells() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * - * @throws Exception - * * @return $this */ public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { - $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) + ); return $this->mergeCells($cellRange); } @@ -1738,22 +1857,21 @@ public function mergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $r /** * Remove merge on a cell range. * - * @param string $pRange Cell range (e.g. A1:E1) - * - * @throws Exception + * @param AddressRange|array|string $range A simple string containing a Cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange. * * @return $this */ - public function unmergeCells($pRange) + public function unmergeCells($range) { - // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = Functions::trimSheetFromCellReference(Validations::validateCellRange($range)); - if (strpos($pRange, ':') !== false) { - if (isset($this->mergeCells[$pRange])) { - unset($this->mergeCells[$pRange]); + if (strpos($range, ':') !== false) { + if (isset($this->mergeCells[$range])) { + unset($this->mergeCells[$range]); } else { - throw new Exception('Cell range ' . $pRange . ' not known as merged.'); + throw new Exception('Cell range ' . $range . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); @@ -1765,18 +1883,24 @@ public function unmergeCells($pRange) /** * Remove merge on a cell range by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the unmergeCells() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * - * @throws Exception - * * @return $this */ public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { - $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) + ); return $this->unmergeCells($cellRange); } @@ -1784,7 +1908,7 @@ public function unmergeCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, /** * Get merge cells array. * - * @return array[] + * @return string[] */ public function getMergeCells() { @@ -1795,35 +1919,36 @@ public function getMergeCells() * Set merge cells array for the entire sheet. Use instead mergeCells() to merge * a single cell range. * - * @param array $pValue + * @param string[] $mergeCells * * @return $this */ - public function setMergeCells(array $pValue) + public function setMergeCells(array $mergeCells) { - $this->mergeCells = $pValue; + $this->mergeCells = $mergeCells; return $this; } /** - * Set protection on a cell range. + * Set protection on a cell or cell range. * - * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) - * @param string $pPassword Password to unlock the protection - * @param bool $pAlreadyHashed If the password has already been hashed, set this to true + * @param AddressRange|array|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or a CellAddress or AddressRange object. + * @param string $password Password to unlock the protection + * @param bool $alreadyHashed If the password has already been hashed, set this to true * * @return $this */ - public function protectCells($pRange, $pPassword, $pAlreadyHashed = false) + public function protectCells($range, $password, $alreadyHashed = false) { - // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); - if (!$pAlreadyHashed) { - $pPassword = Shared\PasswordHasher::hashPassword($pPassword); + if (!$alreadyHashed) { + $password = Shared\PasswordHasher::hashPassword($password); } - $this->protectedCells[$pRange] = $pPassword; + $this->protectedCells[$range] = $password; return $this; } @@ -1831,6 +1956,11 @@ public function protectCells($pRange, $pPassword, $pAlreadyHashed = false) /** * Set protection on a cell range by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the protectCells() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell @@ -1842,29 +1972,31 @@ public function protectCells($pRange, $pPassword, $pAlreadyHashed = false) */ public function protectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2, $password, $alreadyHashed = false) { - $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) + ); return $this->protectCells($cellRange, $password, $alreadyHashed); } /** - * Remove protection on a cell range. + * Remove protection on a cell or cell range. * - * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) - * - * @throws Exception + * @param AddressRange|array|CellAddress|int|string $range A simple string containing a Cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or a CellAddress or AddressRange object. * * @return $this */ - public function unprotectCells($pRange) + public function unprotectCells($range) { - // Uppercase coordinate - $pRange = strtoupper($pRange); + $range = Functions::trimSheetFromCellReference(Validations::validateCellOrCellRange($range)); - if (isset($this->protectedCells[$pRange])) { - unset($this->protectedCells[$pRange]); + if (isset($this->protectedCells[$range])) { + unset($this->protectedCells[$range]); } else { - throw new Exception('Cell range ' . $pRange . ' not known as protected.'); + throw new Exception('Cell range ' . $range . ' not known as protected.'); } return $this; @@ -1873,18 +2005,24 @@ public function unprotectCells($pRange) /** * Remove protection on a cell range by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the protectCells() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object. + * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the last cell * @param int $row2 Numeric row coordinate of the last cell * - * @throws Exception - * * @return $this */ public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { - $cellRange = Coordinate::stringFromColumnIndex($columnIndex1) . $row1 . ':' . Coordinate::stringFromColumnIndex($columnIndex2) . $row2; + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) + ); return $this->unprotectCells($cellRange); } @@ -1892,7 +2030,7 @@ public function unprotectCellsByColumnAndRow($columnIndex1, $row1, $columnIndex2 /** * Get protected cells. * - * @return array[] + * @return string[] */ public function getProtectedCells() { @@ -1912,19 +2050,21 @@ public function getAutoFilter() /** * Set AutoFilter. * - * @param AutoFilter|string $pValue + * @param AddressRange|array|AutoFilter|string $autoFilterOrRange * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility - * - * @throws Exception + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange. * * @return $this */ - public function setAutoFilter($pValue) + public function setAutoFilter($autoFilterOrRange) { - if (is_string($pValue)) { - $this->autoFilter->setRange($pValue); - } elseif (is_object($pValue) && ($pValue instanceof AutoFilter)) { - $this->autoFilter = $pValue; + if (is_object($autoFilterOrRange) && ($autoFilterOrRange instanceof AutoFilter)) { + $this->autoFilter = $autoFilterOrRange; + } else { + $cellRange = Functions::trimSheetFromCellReference(Validations::validateCellRange($autoFilterOrRange)); + + $this->autoFilter->setRange($cellRange); } return $this; @@ -1933,32 +2073,86 @@ public function setAutoFilter($pValue) /** * Set Autofilter Range by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the setAutoFilter() method with a cell address range such as 'C5:F8' instead;, + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or an AddressRange object or AutoFilter object. + * * @param int $columnIndex1 Numeric column coordinate of the first cell * @param int $row1 Numeric row coordinate of the first cell * @param int $columnIndex2 Numeric column coordinate of the second cell * @param int $row2 Numeric row coordinate of the second cell * - * @throws Exception - * * @return $this */ public function setAutoFilterByColumnAndRow($columnIndex1, $row1, $columnIndex2, $row2) { - return $this->setAutoFilter( - Coordinate::stringFromColumnIndex($columnIndex1) . $row1 - . ':' . - Coordinate::stringFromColumnIndex($columnIndex2) . $row2 + $cellRange = new CellRange( + CellAddress::fromColumnAndRow($columnIndex1, $row1), + CellAddress::fromColumnAndRow($columnIndex2, $row2) ); + + return $this->setAutoFilter($cellRange); } /** * Remove autofilter. + */ + public function removeAutoFilter(): self + { + $this->autoFilter->setRange(''); + + return $this; + } + + /** + * Get collection of Tables. + * + * @return ArrayObject + */ + public function getTableCollection() + { + return $this->tableCollection; + } + + /** + * Add Table. * * @return $this */ - public function removeAutoFilter() + public function addTable(Table $table): self { - $this->autoFilter->setRange(null); + $table->setWorksheet($this); + $this->tableCollection[] = $table; + + return $this; + } + + /** + * Remove Table by name. + * + * @param string $name Table name + * + * @return $this + */ + public function removeTableByName(string $name): self + { + $name = Shared\StringHelper::strToUpper($name); + foreach ($this->tableCollection as $key => $table) { + if (Shared\StringHelper::strToUpper($table->getName()) === $name) { + unset($this->tableCollection[$key]); + } + } + + return $this; + } + + /** + * Remove collection of Tables. + */ + public function removeTableCollection(): self + { + $this->tableCollection = new ArrayObject(); return $this; } @@ -1966,7 +2160,7 @@ public function removeAutoFilter() /** * Get Freeze Pane. * - * @return string + * @return null|string */ public function getFreezePane() { @@ -1982,25 +2176,40 @@ public function getFreezePane() * - B1 will freeze the columns to the left of cell B1 (i.e column A) * - B2 will freeze the rows above and to the left of cell B2 (i.e row 1 and column A) * - * @param null|string $cell Position of the split - * @param null|string $topLeftCell default position of the right bottom pane - * - * @throws Exception + * @param null|array|CellAddress|string $coordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * Passing a null value for this argument will clear any existing freeze pane for this worksheet. + * @param null|array|CellAddress|string $topLeftCell default position of the right bottom pane + * Coordinate of the cell as a string, eg: 'C5'; or as an array of [$columnIndex, $row] (e.g. [3, 5]), + * or a CellAddress object. * * @return $this */ - public function freezePane($cell, $topLeftCell = null) + public function freezePane($coordinate, $topLeftCell = null) { - if (is_string($cell) && Coordinate::coordinateIsRange($cell)) { + $cellAddress = ($coordinate !== null) + ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($coordinate)) + : null; + if ($cellAddress !== null && Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Freeze pane can not be set on a range of cells.'); } + $topLeftCell = ($topLeftCell !== null) + ? Functions::trimSheetFromCellReference(Validations::validateCellAddress($topLeftCell)) + : null; - if ($cell !== null && $topLeftCell === null) { - $coordinate = Coordinate::coordinateFromString($cell); + if ($cellAddress !== null && $topLeftCell === null) { + $coordinate = Coordinate::coordinateFromString($cellAddress); $topLeftCell = $coordinate[0] . $coordinate[1]; } - $this->freezePane = $cell; + $this->freezePane = $cellAddress; + $this->topLeftCell = $topLeftCell; + + return $this; + } + + public function setTopLeftCell(string $topLeftCell): self + { $this->topLeftCell = $topLeftCell; return $this; @@ -2009,6 +2218,10 @@ public function freezePane($cell, $topLeftCell = null) /** * Freeze Pane by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the freezePane() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @@ -2032,7 +2245,7 @@ public function unfreezePane() /** * Get the default position of the right bottom pane. * - * @return int + * @return null|string */ public function getTopLeftCell() { @@ -2042,18 +2255,16 @@ public function getTopLeftCell() /** * Insert a new row, updating all possible related data. * - * @param int $pBefore Insert before this one - * @param int $pNumRows Number of rows to insert - * - * @throws Exception + * @param int $before Insert before this one + * @param int $numberOfRows Number of rows to insert * * @return $this */ - public function insertNewRowBefore($pBefore, $pNumRows = 1) + public function insertNewRowBefore($before, $numberOfRows = 1) { - if ($pBefore >= 1) { + if ($before >= 1) { $objReferenceHelper = ReferenceHelper::getInstance(); - $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); + $objReferenceHelper->insertNewBefore('A' . $before, 0, $numberOfRows, $this); } else { throw new Exception('Rows can only be inserted before at least row 1.'); } @@ -2064,18 +2275,16 @@ public function insertNewRowBefore($pBefore, $pNumRows = 1) /** * Insert a new column, updating all possible related data. * - * @param string $pBefore Insert before this one, eg: 'A' - * @param int $pNumCols Number of columns to insert - * - * @throws Exception + * @param string $before Insert before this one, eg: 'A' + * @param int $numberOfColumns Number of columns to insert * * @return $this */ - public function insertNewColumnBefore($pBefore, $pNumCols = 1) + public function insertNewColumnBefore($before, $numberOfColumns = 1) { - if (!is_numeric($pBefore)) { + if (!is_numeric($before)) { $objReferenceHelper = ReferenceHelper::getInstance(); - $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); + $objReferenceHelper->insertNewBefore($before . '1', $numberOfColumns, 0, $this); } else { throw new Exception('Column references should not be numeric.'); } @@ -2087,16 +2296,14 @@ public function insertNewColumnBefore($pBefore, $pNumCols = 1) * Insert a new column, updating all possible related data. * * @param int $beforeColumnIndex Insert before this one (numeric column coordinate of the cell) - * @param int $pNumCols Number of columns to insert - * - * @throws Exception + * @param int $numberOfColumns Number of columns to insert * * @return $this */ - public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1) + public function insertNewColumnBeforeByIndex($beforeColumnIndex, $numberOfColumns = 1) { if ($beforeColumnIndex >= 1) { - return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $pNumCols); + return $this->insertNewColumnBefore(Coordinate::stringFromColumnIndex($beforeColumnIndex), $numberOfColumns); } throw new Exception('Columns can only be inserted before at least column A (1).'); @@ -2105,70 +2312,92 @@ public function insertNewColumnBeforeByIndex($beforeColumnIndex, $pNumCols = 1) /** * Delete a row, updating all possible related data. * - * @param int $pRow Remove starting with this one - * @param int $pNumRows Number of rows to remove - * - * @throws Exception + * @param int $row Remove starting with this one + * @param int $numberOfRows Number of rows to remove * * @return $this */ - public function removeRow($pRow, $pNumRows = 1) + public function removeRow($row, $numberOfRows = 1) { - if ($pRow < 1) { + if ($row < 1) { throw new Exception('Rows to be deleted should at least start from row 1.'); } + $holdRowDimensions = $this->removeRowDimensions($row, $numberOfRows); $highestRow = $this->getHighestDataRow(); $removedRowsCounter = 0; - for ($r = 0; $r < $pNumRows; ++$r) { - if ($pRow + $r <= $highestRow) { - $this->getCellCollection()->removeRow($pRow + $r); + for ($r = 0; $r < $numberOfRows; ++$r) { + if ($row + $r <= $highestRow) { + $this->getCellCollection()->removeRow($row + $r); ++$removedRowsCounter; } } $objReferenceHelper = ReferenceHelper::getInstance(); - $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); + $objReferenceHelper->insertNewBefore('A' . ($row + $numberOfRows), 0, -$numberOfRows, $this); for ($r = 0; $r < $removedRowsCounter; ++$r) { $this->getCellCollection()->removeRow($highestRow); --$highestRow; } + $this->rowDimensions = $holdRowDimensions; + return $this; } + private function removeRowDimensions(int $row, int $numberOfRows): array + { + $highRow = $row + $numberOfRows - 1; + $holdRowDimensions = []; + foreach ($this->rowDimensions as $rowDimension) { + $num = $rowDimension->getRowIndex(); + if ($num < $row) { + $holdRowDimensions[$num] = $rowDimension; + } elseif ($num > $highRow) { + $num -= $numberOfRows; + $cloneDimension = clone $rowDimension; + $cloneDimension->setRowIndex($num); + $holdRowDimensions[$num] = $cloneDimension; + } + } + + return $holdRowDimensions; + } + /** * Remove a column, updating all possible related data. * - * @param string $pColumn Remove starting with this one, eg: 'A' - * @param int $pNumCols Number of columns to remove - * - * @throws Exception + * @param string $column Remove starting with this one, eg: 'A' + * @param int $numberOfColumns Number of columns to remove * * @return $this */ - public function removeColumn($pColumn, $pNumCols = 1) + public function removeColumn($column, $numberOfColumns = 1) { - if (is_numeric($pColumn)) { + if (is_numeric($column)) { throw new Exception('Column references should not be numeric.'); } $highestColumn = $this->getHighestDataColumn(); $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); - $pColumnIndex = Coordinate::columnIndexFromString($pColumn); + $pColumnIndex = Coordinate::columnIndexFromString($column); + + $holdColumnDimensions = $this->removeColumnDimensions($pColumnIndex, $numberOfColumns); + + $column = Coordinate::stringFromColumnIndex($pColumnIndex + $numberOfColumns); + $objReferenceHelper = ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore($column . '1', -$numberOfColumns, 0, $this); + + $this->columnDimensions = $holdColumnDimensions; if ($pColumnIndex > $highestColumnIndex) { return $this; } - $pColumn = Coordinate::stringFromColumnIndex($pColumnIndex + $pNumCols); - $objReferenceHelper = ReferenceHelper::getInstance(); - $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); - $maxPossibleColumnsToBeRemoved = $highestColumnIndex - $pColumnIndex + 1; - for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $pNumCols); $c < $n; ++$c) { + for ($c = 0, $n = min($maxPossibleColumnsToBeRemoved, $numberOfColumns); $c < $n; ++$c) { $this->getCellCollection()->removeColumn($highestColumn); $highestColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($highestColumn) - 1); } @@ -2178,14 +2407,32 @@ public function removeColumn($pColumn, $pNumCols = 1) return $this; } + private function removeColumnDimensions(int $pColumnIndex, int $numberOfColumns): array + { + $highCol = $pColumnIndex + $numberOfColumns - 1; + $holdColumnDimensions = []; + foreach ($this->columnDimensions as $columnDimension) { + $num = $columnDimension->getColumnNumeric(); + if ($num < $pColumnIndex) { + $str = $columnDimension->getColumnIndex(); + $holdColumnDimensions[$str] = $columnDimension; + } elseif ($num > $highCol) { + $cloneDimension = clone $columnDimension; + $cloneDimension->setColumnNumeric($num - $numberOfColumns); + $str = $cloneDimension->getColumnIndex(); + $holdColumnDimensions[$str] = $cloneDimension; + } + } + + return $holdColumnDimensions; + } + /** * Remove a column, updating all possible related data. * * @param int $columnIndex Remove starting with this one (numeric column coordinate of the cell) * @param int $numColumns Number of columns to remove * - * @throws Exception - * * @return $this */ public function removeColumnByIndex($columnIndex, $numColumns = 1) @@ -2210,13 +2457,13 @@ public function getShowGridlines() /** * Set show gridlines. * - * @param bool $pValue Show gridlines (true/false) + * @param bool $showGridLines Show gridlines (true/false) * * @return $this */ - public function setShowGridlines($pValue) + public function setShowGridlines($showGridLines) { - $this->showGridlines = $pValue; + $this->showGridlines = $showGridLines; return $this; } @@ -2234,13 +2481,13 @@ public function getPrintGridlines() /** * Set print gridlines. * - * @param bool $pValue Print gridlines (true/false) + * @param bool $printGridLines Print gridlines (true/false) * * @return $this */ - public function setPrintGridlines($pValue) + public function setPrintGridlines($printGridLines) { - $this->printGridlines = $pValue; + $this->printGridlines = $printGridLines; return $this; } @@ -2258,13 +2505,13 @@ public function getShowRowColHeaders() /** * Set show row and column headers. * - * @param bool $pValue Show row and column headers (true/false) + * @param bool $showRowColHeaders Show row and column headers (true/false) * * @return $this */ - public function setShowRowColHeaders($pValue) + public function setShowRowColHeaders($showRowColHeaders) { - $this->showRowColHeaders = $pValue; + $this->showRowColHeaders = $showRowColHeaders; return $this; } @@ -2282,13 +2529,13 @@ public function getShowSummaryBelow() /** * Set show summary below. * - * @param bool $pValue Show summary below (true/false) + * @param bool $showSummaryBelow Show summary below (true/false) * * @return $this */ - public function setShowSummaryBelow($pValue) + public function setShowSummaryBelow($showSummaryBelow) { - $this->showSummaryBelow = $pValue; + $this->showSummaryBelow = $showSummaryBelow; return $this; } @@ -2306,13 +2553,13 @@ public function getShowSummaryRight() /** * Set show summary right. * - * @param bool $pValue Show summary right (true/false) + * @param bool $showSummaryRight Show summary right (true/false) * * @return $this */ - public function setShowSummaryRight($pValue) + public function setShowSummaryRight($showSummaryRight) { - $this->showSummaryRight = $pValue; + $this->showSummaryRight = $showSummaryRight; return $this; } @@ -2330,13 +2577,13 @@ public function getComments() /** * Set comments array for the entire sheet. * - * @param Comment[] $pValue + * @param Comment[] $comments * * @return $this */ - public function setComments(array $pValue) + public function setComments(array $comments) { - $this->comments = $pValue; + $this->comments = $comments; return $this; } @@ -2344,33 +2591,31 @@ public function setComments(array $pValue) /** * Get comment for cell. * - * @param string $pCellCoordinate Cell coordinate to get comment for, eg: 'A1' - * - * @throws Exception + * @param array|CellAddress|string $cellCoordinate Coordinate of the cell as a string, eg: 'C5'; + * or as an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. * * @return Comment */ - public function getComment($pCellCoordinate) + public function getComment($cellCoordinate) { - // Uppercase coordinate - $pCellCoordinate = strtoupper($pCellCoordinate); + $cellAddress = Functions::trimSheetFromCellReference(Validations::validateCellAddress($cellCoordinate)); - if (Coordinate::coordinateIsRange($pCellCoordinate)) { + if (Coordinate::coordinateIsRange($cellAddress)) { throw new Exception('Cell coordinate string can not be a range of cells.'); - } elseif (strpos($pCellCoordinate, '$') !== false) { + } elseif (strpos($cellAddress, '$') !== false) { throw new Exception('Cell coordinate string must not be absolute.'); - } elseif ($pCellCoordinate == '') { + } elseif ($cellAddress == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } // Check if we already have a comment for this cell. - if (isset($this->comments[$pCellCoordinate])) { - return $this->comments[$pCellCoordinate]; + if (isset($this->comments[$cellAddress])) { + return $this->comments[$cellAddress]; } // If not, create a new comment. $newComment = new Comment(); - $this->comments[$pCellCoordinate] = $newComment; + $this->comments[$cellAddress] = $newComment; return $newComment; } @@ -2378,6 +2623,10 @@ public function getComment($pCellCoordinate) /** * Get comment for cell by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the getComment() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * @@ -2411,46 +2660,38 @@ public function getSelectedCells() /** * Selected cell. * - * @param string $pCoordinate Cell (i.e. A1) + * @param string $coordinate Cell (i.e. A1) * * @return $this */ - public function setSelectedCell($pCoordinate) + public function setSelectedCell($coordinate) { - return $this->setSelectedCells($pCoordinate); + return $this->setSelectedCells($coordinate); } /** * Select a range of cells. * - * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6' + * @param AddressRange|array|CellAddress|int|string $coordinate A simple string containing a Cell range like 'A1:E10' + * or passing in an array of [$fromColumnIndex, $fromRow, $toColumnIndex, $toRow] (e.g. [3, 5, 6, 8]), + * or a CellAddress or AddressRange object. * * @return $this */ - public function setSelectedCells($pCoordinate) + public function setSelectedCells($coordinate) { - // Uppercase coordinate - $pCoordinate = strtoupper($pCoordinate); - - // Convert 'A' to 'A:A' - $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); - - // Convert '1' to '1:1' - $pCoordinate = preg_replace('/^(\d+)$/', '${1}:${1}', $pCoordinate); - - // Convert 'A:C' to 'A1:C1048576' - $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); - - // Convert '1:3' to 'A1:XFD3' - $pCoordinate = preg_replace('/^(\d+):(\d+)$/', 'A${1}:XFD${2}', $pCoordinate); + if (is_string($coordinate)) { + $coordinate = Validations::definedNameToCoordinate($coordinate, $this); + } + $coordinate = Validations::validateCellOrCellRange($coordinate); - if (Coordinate::coordinateIsRange($pCoordinate)) { - [$first] = Coordinate::splitRange($pCoordinate); + if (Coordinate::coordinateIsRange($coordinate)) { + [$first] = Coordinate::splitRange($coordinate); $this->activeCell = $first[0]; } else { - $this->activeCell = $pCoordinate; + $this->activeCell = $coordinate; } - $this->selectedCells = $pCoordinate; + $this->selectedCells = $coordinate; return $this; } @@ -2458,11 +2699,13 @@ public function setSelectedCells($pCoordinate) /** * Selected cell by using numeric cell coordinates. * + * @Deprecated 1.23.0 + * Use the setSelectedCells() method with a cell address such as 'C5' instead;, + * or passing in an array of [$columnIndex, $row] (e.g. [3, 5]), or a CellAddress object. + * * @param int $columnIndex Numeric column coordinate of the cell * @param int $row Numeric row coordinate of the cell * - * @throws Exception - * * @return $this */ public function setSelectedCellByColumnAndRow($columnIndex, $row) @@ -2502,8 +2745,6 @@ public function setRightToLeft($value) * @param string $startCell Insert array starting from this cell address as the top left coordinate * @param bool $strictNullComparison Apply strict comparison when testing for null values in the array * - * @throws Exception - * * @return $this */ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) @@ -2542,7 +2783,7 @@ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $ /** * Create array from a range of cells. * - * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @param string $range Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? @@ -2551,12 +2792,12 @@ public function fromArray(array $source, $nullValue = null, $startCell = 'A1', $ * * @return array */ - public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + public function rangeToArray($range, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { // Returnvalue $returnValue = []; // Identify the range that we need to extract from the worksheet - [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($pRange); + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range); $minCol = Coordinate::stringFromColumnIndex($rangeStart[0]); $minRow = $rangeStart[1]; $maxCol = Coordinate::stringFromColumnIndex($rangeEnd[0]); @@ -2609,31 +2850,59 @@ public function rangeToArray($pRange, $nullValue = null, $calculateFormulas = tr return $returnValue; } + private function validateNamedRange(string $definedName, bool $returnNullIfInvalid = false): ?DefinedName + { + $namedRange = DefinedName::resolveName($definedName, $this); + if ($namedRange === null) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception('Named Range ' . $definedName . ' does not exist.'); + } + + if ($namedRange->isFormula()) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception('Defined Named ' . $definedName . ' is a formula, not a range or cell.'); + } + + if ($namedRange->getLocalOnly() && $this->getHashCode() !== $namedRange->getWorksheet()->getHashCode()) { + if ($returnNullIfInvalid) { + return null; + } + + throw new Exception( + 'Named range ' . $definedName . ' is not accessible from within sheet ' . $this->getTitle() + ); + } + + return $namedRange; + } + /** * Create array from a range of cells. * - * @param string $pNamedRange Name of the Named Range + * @param string $definedName The Named Range that should be returned * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist * @param bool $calculateFormulas Should formulas be calculated? * @param bool $formatData Should formatting be applied to cell values? * @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero * True - Return rows and columns indexed by their actual row and column IDs * - * @throws Exception - * * @return array */ - public function namedRangeToArray($pNamedRange, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + public function namedRangeToArray(string $definedName, $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { - $namedRange = NamedRange::resolveRange($pNamedRange, $this); - if ($namedRange !== null) { - $pWorkSheet = $namedRange->getWorksheet(); - $pCellRange = $namedRange->getRange(); - - return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); - } + $namedRange = $this->validateNamedRange($definedName); + $workSheet = $namedRange->getWorksheet(); + /** @phpstan-ignore-next-line */ + $cellRange = ltrim(substr($namedRange->getValue(), strrpos($namedRange->getValue(), '!')), '!'); + $cellRange = str_replace('$', '', $cellRange); - throw new Exception('Named Range ' . $pNamedRange . ' does not exist.'); + return $workSheet->rangeToArray($cellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); } /** @@ -2713,9 +2982,9 @@ public function garbageCollect() // Cache values if ($highestColumn < 1) { - $this->cachedHighestColumn = 'A'; + $this->cachedHighestColumn = 1; } else { - $this->cachedHighestColumn = Coordinate::stringFromColumnIndex($highestColumn); + $this->cachedHighestColumn = $highestColumn; } $this->cachedHighestRow = $highestRow; @@ -2744,59 +3013,58 @@ public function getHashCode() * Example: extractSheetTitle("testSheet!A1") ==> 'A1' * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> ['testSheet 1', 'A1']; * - * @param string $pRange Range to extract title from + * @param string $range Range to extract title from * @param bool $returnRange Return range? (see example) * * @return mixed */ - public static function extractSheetTitle($pRange, $returnRange = false) + public static function extractSheetTitle($range, $returnRange = false) { // Sheet title included? - if (($sep = strrpos($pRange, '!')) === false) { - return $returnRange ? ['', $pRange] : ''; + if (($sep = strrpos($range, '!')) === false) { + return $returnRange ? ['', $range] : ''; } if ($returnRange) { - return [substr($pRange, 0, $sep), substr($pRange, $sep + 1)]; + return [substr($range, 0, $sep), substr($range, $sep + 1)]; } - return substr($pRange, $sep + 1); + return substr($range, $sep + 1); } /** * Get hyperlink. * - * @param string $pCellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' + * @param string $cellCoordinate Cell coordinate to get hyperlink for, eg: 'A1' * * @return Hyperlink */ - public function getHyperlink($pCellCoordinate) + public function getHyperlink($cellCoordinate) { // return hyperlink if we already have one - if (isset($this->hyperlinkCollection[$pCellCoordinate])) { - return $this->hyperlinkCollection[$pCellCoordinate]; + if (isset($this->hyperlinkCollection[$cellCoordinate])) { + return $this->hyperlinkCollection[$cellCoordinate]; } // else create hyperlink - $this->hyperlinkCollection[$pCellCoordinate] = new Hyperlink(); + $this->hyperlinkCollection[$cellCoordinate] = new Hyperlink(); - return $this->hyperlinkCollection[$pCellCoordinate]; + return $this->hyperlinkCollection[$cellCoordinate]; } /** * Set hyperlink. * - * @param string $pCellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' - * @param null|Hyperlink $pHyperlink + * @param string $cellCoordinate Cell coordinate to insert hyperlink, eg: 'A1' * * @return $this */ - public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null) + public function setHyperlink($cellCoordinate, ?Hyperlink $hyperlink = null) { - if ($pHyperlink === null) { - unset($this->hyperlinkCollection[$pCellCoordinate]); + if ($hyperlink === null) { + unset($this->hyperlinkCollection[$cellCoordinate]); } else { - $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink; + $this->hyperlinkCollection[$cellCoordinate] = $hyperlink; } return $this; @@ -2805,13 +3073,13 @@ public function setHyperlink($pCellCoordinate, Hyperlink $pHyperlink = null) /** * Hyperlink at a specific coordinate exists? * - * @param string $pCoordinate eg: 'A1' + * @param string $coordinate eg: 'A1' * * @return bool */ - public function hyperlinkExists($pCoordinate) + public function hyperlinkExists($coordinate) { - return isset($this->hyperlinkCollection[$pCoordinate]); + return isset($this->hyperlinkCollection[$coordinate]); } /** @@ -2827,37 +3095,36 @@ public function getHyperlinkCollection() /** * Get data validation. * - * @param string $pCellCoordinate Cell coordinate to get data validation for, eg: 'A1' + * @param string $cellCoordinate Cell coordinate to get data validation for, eg: 'A1' * * @return DataValidation */ - public function getDataValidation($pCellCoordinate) + public function getDataValidation($cellCoordinate) { // return data validation if we already have one - if (isset($this->dataValidationCollection[$pCellCoordinate])) { - return $this->dataValidationCollection[$pCellCoordinate]; + if (isset($this->dataValidationCollection[$cellCoordinate])) { + return $this->dataValidationCollection[$cellCoordinate]; } // else create data validation - $this->dataValidationCollection[$pCellCoordinate] = new DataValidation(); + $this->dataValidationCollection[$cellCoordinate] = new DataValidation(); - return $this->dataValidationCollection[$pCellCoordinate]; + return $this->dataValidationCollection[$cellCoordinate]; } /** * Set data validation. * - * @param string $pCellCoordinate Cell coordinate to insert data validation, eg: 'A1' - * @param null|DataValidation $pDataValidation + * @param string $cellCoordinate Cell coordinate to insert data validation, eg: 'A1' * * @return $this */ - public function setDataValidation($pCellCoordinate, DataValidation $pDataValidation = null) + public function setDataValidation($cellCoordinate, ?DataValidation $dataValidation = null) { - if ($pDataValidation === null) { - unset($this->dataValidationCollection[$pCellCoordinate]); + if ($dataValidation === null) { + unset($this->dataValidationCollection[$cellCoordinate]); } else { - $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation; + $this->dataValidationCollection[$cellCoordinate] = $dataValidation; } return $this; @@ -2866,13 +3133,13 @@ public function setDataValidation($pCellCoordinate, DataValidation $pDataValidat /** * Data validation at a specific coordinate exists? * - * @param string $pCoordinate eg: 'A1' + * @param string $coordinate eg: 'A1' * * @return bool */ - public function dataValidationExists($pCoordinate) + public function dataValidationExists($coordinate) { - return isset($this->dataValidationCollection[$pCoordinate]); + return isset($this->dataValidationCollection[$coordinate]); } /** @@ -2943,7 +3210,6 @@ public function getTabColor() public function resetTabColor() { $this->tabColor = null; - unset($this->tabColor); return $this; } @@ -2973,6 +3239,7 @@ public function copy() */ public function __clone() { + // @phpstan-ignore-next-line foreach ($this as $key => $val) { if ($key == 'parent') { continue; @@ -3005,59 +3272,57 @@ public function __clone() /** * Define the code name of the sheet. * - * @param string $pValue Same rule as Title minus space not allowed (but, like Excel, change + * @param string $codeName Same rule as Title minus space not allowed (but, like Excel, change * silently space to underscore) * @param bool $validate False to skip validation of new title. WARNING: This should only be set * at parse time (by Readers), where titles can be assumed to be valid. * - * @throws Exception - * * @return $this */ - public function setCodeName($pValue, $validate = true) + public function setCodeName($codeName, $validate = true) { // Is this a 'rename' or not? - if ($this->getCodeName() == $pValue) { + if ($this->getCodeName() == $codeName) { return $this; } if ($validate) { - $pValue = str_replace(' ', '_', $pValue); //Excel does this automatically without flinching, we are doing the same + $codeName = str_replace(' ', '_', $codeName); //Excel does this automatically without flinching, we are doing the same // Syntax check // throw an exception if not valid - self::checkSheetCodeName($pValue); + self::checkSheetCodeName($codeName); // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' if ($this->getParent()) { // Is there already such sheet name? - if ($this->getParent()->sheetCodeNameExists($pValue)) { + if ($this->getParent()->sheetCodeNameExists($codeName)) { // Use name, but append with lowest possible integer - if (Shared\StringHelper::countCharacters($pValue) > 29) { - $pValue = Shared\StringHelper::substring($pValue, 0, 29); + if (Shared\StringHelper::countCharacters($codeName) > 29) { + $codeName = Shared\StringHelper::substring($codeName, 0, 29); } $i = 1; - while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) { + while ($this->getParent()->sheetCodeNameExists($codeName . '_' . $i)) { ++$i; if ($i == 10) { - if (Shared\StringHelper::countCharacters($pValue) > 28) { - $pValue = Shared\StringHelper::substring($pValue, 0, 28); + if (Shared\StringHelper::countCharacters($codeName) > 28) { + $codeName = Shared\StringHelper::substring($codeName, 0, 28); } } elseif ($i == 100) { - if (Shared\StringHelper::countCharacters($pValue) > 27) { - $pValue = Shared\StringHelper::substring($pValue, 0, 27); + if (Shared\StringHelper::countCharacters($codeName) > 27) { + $codeName = Shared\StringHelper::substring($codeName, 0, 27); } } } - $pValue .= '_' . $i; // ok, we have a valid name + $codeName .= '_' . $i; // ok, we have a valid name } } } - $this->codeName = $pValue; + $this->codeName = $codeName; return $this; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php index f13150d7..7a3fa369 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/BaseWriter.php @@ -6,7 +6,7 @@ abstract class BaseWriter implements IWriter { /** * Write charts that are defined in the workbook? - * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object;. + * Identifies whether the Writer should write definitions for any charts that exist in the PhpSpreadsheet object. * * @var bool */ @@ -35,14 +35,24 @@ abstract class BaseWriter implements IWriter */ private $diskCachingDirectory = './'; + /** + * @var resource + */ + protected $fileHandle; + + /** + * @var bool + */ + private $shouldCloseFile; + public function getIncludeCharts() { return $this->includeCharts; } - public function setIncludeCharts($pValue) + public function setIncludeCharts($includeCharts) { - $this->includeCharts = (bool) $pValue; + $this->includeCharts = (bool) $includeCharts; return $this; } @@ -52,9 +62,9 @@ public function getPreCalculateFormulas() return $this->preCalculateFormulas; } - public function setPreCalculateFormulas($pValue) + public function setPreCalculateFormulas($precalculateFormulas) { - $this->preCalculateFormulas = (bool) $pValue; + $this->preCalculateFormulas = (bool) $precalculateFormulas; return $this; } @@ -64,15 +74,15 @@ public function getUseDiskCaching() return $this->useDiskCaching; } - public function setUseDiskCaching($pValue, $pDirectory = null) + public function setUseDiskCaching($useDiskCache, $cacheDirectory = null) { - $this->useDiskCaching = $pValue; + $this->useDiskCaching = $useDiskCache; - if ($pDirectory !== null) { - if (is_dir($pDirectory)) { - $this->diskCachingDirectory = $pDirectory; + if ($cacheDirectory !== null) { + if (is_dir($cacheDirectory)) { + $this->diskCachingDirectory = $cacheDirectory; } else { - throw new Exception("Directory does not exist: $pDirectory"); + throw new Exception("Directory does not exist: $cacheDirectory"); } } @@ -83,4 +93,51 @@ public function getDiskCachingDirectory() { return $this->diskCachingDirectory; } + + protected function processFlags(int $flags): void + { + if (((bool) ($flags & self::SAVE_WITH_CHARTS)) === true) { + $this->setIncludeCharts(true); + } + } + + /** + * Open file handle. + * + * @param resource|string $filename + */ + public function openFileHandle($filename): void + { + if (is_resource($filename)) { + $this->fileHandle = $filename; + $this->shouldCloseFile = false; + + return; + } + + $mode = 'wb'; + $scheme = parse_url($filename, PHP_URL_SCHEME); + if ($scheme === 's3') { + $mode = 'w'; + } + $fileHandle = $filename ? fopen($filename, $mode) : false; + if ($fileHandle === false) { + throw new Exception('Could not open file "' . $filename . '" for writing.'); + } + + $this->fileHandle = $fileHandle; + $this->shouldCloseFile = true; + } + + /** + * Close file handle only if we opened it ourselves. + */ + protected function maybeCloseFileHandle(): void + { + if ($this->shouldCloseFile) { + if (!fclose($this->fileHandle)) { + throw new Exception('Could not close file after writing.'); + } + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php index 1166bd25..0f385de1 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Csv.php @@ -64,6 +64,13 @@ class Csv extends BaseWriter */ private $excelCompatibility = false; + /** + * Output encoding. + * + * @var string + */ + private $outputEncoding = ''; + /** * Create a new CSV. * @@ -77,12 +84,12 @@ public function __construct(Spreadsheet $spreadsheet) /** * Save PhpSpreadsheet to file. * - * @param string $pFilename - * - * @throws Exception + * @param resource|string $filename */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // Fetch sheet $sheet = $this->spreadsheet->getSheet($this->sheetIndex); @@ -92,10 +99,7 @@ public function save($pFilename) Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Open file - $fileHandle = fopen($pFilename, 'wb+'); - if ($fileHandle === false) { - throw new Exception("Could not open file $pFilename for writing."); - } + $this->openFileHandle($filename); if ($this->excelCompatibility) { $this->setUseBOM(true); // Enforce UTF-8 BOM Header @@ -104,13 +108,15 @@ public function save($pFilename) $this->setDelimiter(';'); // Set delimiter to a semi-colon $this->setLineEnding("\r\n"); } + if ($this->useBOM) { // Write the UTF-8 BOM code if required - fwrite($fileHandle, "\xEF\xBB\xBF"); + fwrite($this->fileHandle, "\xEF\xBB\xBF"); } + if ($this->includeSeparatorLine) { // Write the separator line if required - fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); + fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); } // Identify the range that we need to extract from the worksheet @@ -122,12 +128,10 @@ public function save($pFilename) // Convert the row to an array... $cellsArray = $sheet->rangeToArray('A' . $row . ':' . $maxCol . $row, '', $this->preCalculateFormulas); // ... and write to the file - $this->writeLine($fileHandle, $cellsArray[0]); + $this->writeLine($this->fileHandle, $cellsArray[0]); } - // Close file - fclose($fileHandle); - + $this->maybeCloseFileHandle(); Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); } @@ -145,13 +149,13 @@ public function getDelimiter() /** * Set delimiter. * - * @param string $pValue Delimiter, defaults to ',' + * @param string $delimiter Delimiter, defaults to ',' * * @return $this */ - public function setDelimiter($pValue) + public function setDelimiter($delimiter) { - $this->delimiter = $pValue; + $this->delimiter = $delimiter; return $this; } @@ -169,16 +173,13 @@ public function getEnclosure() /** * Set enclosure. * - * @param string $pValue Enclosure, defaults to " + * @param string $enclosure Enclosure, defaults to " * * @return $this */ - public function setEnclosure($pValue) + public function setEnclosure($enclosure = '"') { - if ($pValue == '') { - $pValue = null; - } - $this->enclosure = $pValue; + $this->enclosure = $enclosure; return $this; } @@ -196,13 +197,13 @@ public function getLineEnding() /** * Set line ending. * - * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL) + * @param string $lineEnding Line ending, defaults to OS line ending (PHP_EOL) * * @return $this */ - public function setLineEnding($pValue) + public function setLineEnding($lineEnding) { - $this->lineEnding = $pValue; + $this->lineEnding = $lineEnding; return $this; } @@ -220,13 +221,13 @@ public function getUseBOM() /** * Set whether BOM should be used. * - * @param bool $pValue Use UTF-8 byte-order mark? Defaults to false + * @param bool $useBOM Use UTF-8 byte-order mark? Defaults to false * * @return $this */ - public function setUseBOM($pValue) + public function setUseBOM($useBOM) { - $this->useBOM = $pValue; + $this->useBOM = $useBOM; return $this; } @@ -244,13 +245,13 @@ public function getIncludeSeparatorLine() /** * Set whether a separator line should be included as the first line of the file. * - * @param bool $pValue Use separator line? Defaults to false + * @param bool $includeSeparatorLine Use separator line? Defaults to false * * @return $this */ - public function setIncludeSeparatorLine($pValue) + public function setIncludeSeparatorLine($includeSeparatorLine) { - $this->includeSeparatorLine = $pValue; + $this->includeSeparatorLine = $includeSeparatorLine; return $this; } @@ -268,14 +269,14 @@ public function getExcelCompatibility() /** * Set whether the file should be saved with full Excel Compatibility. * - * @param bool $pValue Set the file to be written as a fully Excel compatible csv file + * @param bool $excelCompatibility Set the file to be written as a fully Excel compatible csv file * Note that this overrides other settings such as useBOM, enclosure and delimiter * * @return $this */ - public function setExcelCompatibility($pValue) + public function setExcelCompatibility($excelCompatibility) { - $this->excelCompatibility = $pValue; + $this->excelCompatibility = $excelCompatibility; return $this; } @@ -293,50 +294,111 @@ public function getSheetIndex() /** * Set sheet index. * - * @param int $pValue Sheet index + * @param int $sheetIndex Sheet index * * @return $this */ - public function setSheetIndex($pValue) + public function setSheetIndex($sheetIndex) { - $this->sheetIndex = $pValue; + $this->sheetIndex = $sheetIndex; return $this; } + /** + * Get output encoding. + * + * @return string + */ + public function getOutputEncoding() + { + return $this->outputEncoding; + } + + /** + * Set output encoding. + * + * @param string $outputEnconding Output encoding + * + * @return $this + */ + public function setOutputEncoding($outputEnconding) + { + $this->outputEncoding = $outputEnconding; + + return $this; + } + + /** @var bool */ + private $enclosureRequired = true; + + public function setEnclosureRequired(bool $value): self + { + $this->enclosureRequired = $value; + + return $this; + } + + public function getEnclosureRequired(): bool + { + return $this->enclosureRequired; + } + + /** + * Convert boolean to TRUE/FALSE; otherwise return element cast to string. + * + * @param mixed $element + */ + private static function elementToString($element): string + { + if (is_bool($element)) { + return $element ? 'TRUE' : 'FALSE'; + } + + return (string) $element; + } + /** * Write line to CSV file. * - * @param resource $pFileHandle PHP filehandle - * @param array $pValues Array containing values in a row + * @param resource $fileHandle PHP filehandle + * @param array $values Array containing values in a row */ - private function writeLine($pFileHandle, array $pValues) + private function writeLine($fileHandle, array $values): void { // No leading delimiter - $writeDelimiter = false; + $delimiter = ''; // Build the line $line = ''; - foreach ($pValues as $element) { - // Escape enclosures - $element = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $element); - + foreach ($values as $element) { + $element = self::elementToString($element); // Add delimiter - if ($writeDelimiter) { - $line .= $this->delimiter; - } else { - $writeDelimiter = true; + $line .= $delimiter; + $delimiter = $this->delimiter; + // Escape enclosures + $enclosure = $this->enclosure; + if ($enclosure) { + // If enclosure is not required, use enclosure only if + // element contains newline, delimiter, or enclosure. + if (!$this->enclosureRequired && strpbrk($element, "$delimiter$enclosure\n") === false) { + $enclosure = ''; + } else { + $element = str_replace($enclosure, $enclosure . $enclosure, $element); + } } - // Add enclosed string - $line .= $this->enclosure . $element . $this->enclosure; + $line .= $enclosure . $element . $enclosure; } // Add line ending $line .= $this->lineEnding; // Write to file - fwrite($pFileHandle, $line); + if ($this->outputEncoding != '') { + $line = mb_convert_encoding($line, $this->outputEncoding); + } + fwrite($fileHandle, $line); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php index 37d68e91..629e3c0c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Html.php @@ -2,12 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer; +use HTMLPurifier; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Chart\Chart; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont; @@ -23,7 +25,6 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Html extends BaseWriter { @@ -37,7 +38,7 @@ class Html extends BaseWriter /** * Sheet index to write. * - * @var int + * @var null|int */ private $sheetIndex = 0; @@ -133,9 +134,14 @@ class Html extends BaseWriter private $generateSheetNavigationBlock = true; /** - * Create a new HTML. + * Callback for editing generated html. * - * @param Spreadsheet $spreadsheet + * @var null|callable + */ + private $editHtmlCallback; + + /** + * Create a new HTML. */ public function __construct(Spreadsheet $spreadsheet) { @@ -146,11 +152,28 @@ public function __construct(Spreadsheet $spreadsheet) /** * Save Spreadsheet to file. * - * @param string $pFilename + * @param resource|string $filename + */ + public function save($filename, int $flags = 0): void + { + $this->processFlags($flags); + + // Open file + $this->openFileHandle($filename); + + // Write html + fwrite($this->fileHandle, $this->generateHTMLAll()); + + // Close file + $this->maybeCloseFileHandle(); + } + + /** + * Save Spreadsheet as html to variable. * - * @throws WriterException + * @return string */ - public function save($pFilename) + public function generateHtmlAll() { // garbage collect $this->spreadsheet->garbageCollect(); @@ -163,33 +186,50 @@ public function save($pFilename) // Build CSS $this->buildCSS(!$this->useInlineCss); - // Open file - $fileHandle = fopen($pFilename, 'wb+'); - if ($fileHandle === false) { - throw new WriterException("Could not open file $pFilename for writing."); - } + $html = ''; // Write headers - fwrite($fileHandle, $this->generateHTMLHeader(!$this->useInlineCss)); + $html .= $this->generateHTMLHeader(!$this->useInlineCss); // Write navigation (tabs) if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) { - fwrite($fileHandle, $this->generateNavigation()); + $html .= $this->generateNavigation(); } // Write data - fwrite($fileHandle, $this->generateSheetData()); + $html .= $this->generateSheetData(); // Write footer - fwrite($fileHandle, $this->generateHTMLFooter()); - - // Close file - fclose($fileHandle); + $html .= $this->generateHTMLFooter(); + $callback = $this->editHtmlCallback; + if ($callback) { + $html = $callback($html); + } Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); + + return $html; } + /** + * Set a callback to edit the entire HTML. + * + * The callback must accept the HTML as string as first parameter, + * and it must return the edited HTML as string. + */ + public function setEditHtmlCallback(?callable $callback): void + { + $this->editHtmlCallback = $callback; + } + + const VALIGN_ARR = [ + Alignment::VERTICAL_BOTTOM => 'bottom', + Alignment::VERTICAL_TOP => 'top', + Alignment::VERTICAL_CENTER => 'middle', + Alignment::VERTICAL_JUSTIFY => 'middle', + ]; + /** * Map VAlign. * @@ -199,45 +239,44 @@ public function save($pFilename) */ private function mapVAlign($vAlign) { - switch ($vAlign) { - case Alignment::VERTICAL_BOTTOM: - return 'bottom'; - case Alignment::VERTICAL_TOP: - return 'top'; - case Alignment::VERTICAL_CENTER: - case Alignment::VERTICAL_JUSTIFY: - return 'middle'; - default: - return 'baseline'; - } + return array_key_exists($vAlign, self::VALIGN_ARR) ? self::VALIGN_ARR[$vAlign] : 'baseline'; } + const HALIGN_ARR = [ + Alignment::HORIZONTAL_LEFT => 'left', + Alignment::HORIZONTAL_RIGHT => 'right', + Alignment::HORIZONTAL_CENTER => 'center', + Alignment::HORIZONTAL_CENTER_CONTINUOUS => 'center', + Alignment::HORIZONTAL_JUSTIFY => 'justify', + ]; + /** * Map HAlign. * * @param string $hAlign Horizontal alignment * - * @return false|string + * @return string */ private function mapHAlign($hAlign) { - switch ($hAlign) { - case Alignment::HORIZONTAL_GENERAL: - return false; - case Alignment::HORIZONTAL_LEFT: - return 'left'; - case Alignment::HORIZONTAL_RIGHT: - return 'right'; - case Alignment::HORIZONTAL_CENTER: - case Alignment::HORIZONTAL_CENTER_CONTINUOUS: - return 'center'; - case Alignment::HORIZONTAL_JUSTIFY: - return 'justify'; - default: - return false; - } + return array_key_exists($hAlign, self::HALIGN_ARR) ? self::HALIGN_ARR[$hAlign] : ''; } + const BORDER_ARR = [ + Border::BORDER_NONE => 'none', + Border::BORDER_DASHDOT => '1px dashed', + Border::BORDER_DASHDOTDOT => '1px dotted', + Border::BORDER_DASHED => '1px dashed', + Border::BORDER_DOTTED => '1px dotted', + Border::BORDER_DOUBLE => '3px double', + Border::BORDER_HAIR => '1px solid', + Border::BORDER_MEDIUM => '2px solid', + Border::BORDER_MEDIUMDASHDOT => '2px dashed', + Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted', + Border::BORDER_SLANTDASHDOT => '2px dashed', + Border::BORDER_THICK => '3px solid', + ]; + /** * Map border style. * @@ -247,47 +286,13 @@ private function mapHAlign($hAlign) */ private function mapBorderStyle($borderStyle) { - switch ($borderStyle) { - case Border::BORDER_NONE: - return 'none'; - case Border::BORDER_DASHDOT: - return '1px dashed'; - case Border::BORDER_DASHDOTDOT: - return '1px dotted'; - case Border::BORDER_DASHED: - return '1px dashed'; - case Border::BORDER_DOTTED: - return '1px dotted'; - case Border::BORDER_DOUBLE: - return '3px double'; - case Border::BORDER_HAIR: - return '1px solid'; - case Border::BORDER_MEDIUM: - return '2px solid'; - case Border::BORDER_MEDIUMDASHDOT: - return '2px dashed'; - case Border::BORDER_MEDIUMDASHDOTDOT: - return '2px dotted'; - case Border::BORDER_MEDIUMDASHED: - return '2px dashed'; - case Border::BORDER_SLANTDASHDOT: - return '2px dashed'; - case Border::BORDER_THICK: - return '3px solid'; - case Border::BORDER_THIN: - return '1px solid'; - default: - // map others to thin - return '1px solid'; - } + return array_key_exists($borderStyle, self::BORDER_ARR) ? self::BORDER_ARR[$borderStyle] : '1px solid'; } /** * Get sheet index. - * - * @return int */ - public function getSheetIndex() + public function getSheetIndex(): ?int { return $this->sheetIndex; } @@ -295,13 +300,13 @@ public function getSheetIndex() /** * Set sheet index. * - * @param int $pValue Sheet index + * @param int $sheetIndex Sheet index * * @return $this */ - public function setSheetIndex($pValue) + public function setSheetIndex($sheetIndex) { - $this->sheetIndex = $pValue; + $this->sheetIndex = $sheetIndex; return $this; } @@ -319,13 +324,13 @@ public function getGenerateSheetNavigationBlock() /** * Set sheet index. * - * @param bool $pValue Flag indicating whether the sheet navigation block should be generated or not + * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not * * @return $this */ - public function setGenerateSheetNavigationBlock($pValue) + public function setGenerateSheetNavigationBlock($generateSheetNavigationBlock) { - $this->generateSheetNavigationBlock = (bool) $pValue; + $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock; return $this; } @@ -342,84 +347,105 @@ public function writeAllSheets() return $this; } + private static function generateMeta($val, $desc) + { + return $val + ? (' ' . PHP_EOL) + : ''; + } + + public const BODY_LINE = ' ' . PHP_EOL; + /** * Generate HTML header. * - * @param bool $pIncludeStyles Include styles? - * - * @throws WriterException + * @param bool $includeStyles Include styles? * * @return string */ - public function generateHTMLHeader($pIncludeStyles = false) + public function generateHTMLHeader($includeStyles = false) { // Construct HTML $properties = $this->spreadsheet->getProperties(); - $html = '' . PHP_EOL; - $html .= '' . PHP_EOL; + $html = '' . PHP_EOL; + $html .= '' . PHP_EOL; $html .= ' ' . PHP_EOL; - $html .= ' ' . PHP_EOL; - $html .= ' ' . PHP_EOL; - if ($properties->getTitle() > '') { - $html .= ' ' . htmlspecialchars($properties->getTitle()) . '' . PHP_EOL; - } - if ($properties->getCreator() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getTitle() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getDescription() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getSubject() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getKeywords() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getCategory() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getCompany() > '') { - $html .= ' ' . PHP_EOL; - } - if ($properties->getManager() > '') { - $html .= ' ' . PHP_EOL; - } - - if ($pIncludeStyles) { - $html .= $this->generateStyles(true); - } + $html .= ' ' . PHP_EOL; + $html .= ' ' . PHP_EOL; + $html .= ' ' . htmlspecialchars($properties->getTitle(), Settings::htmlEntityFlags()) . '' . PHP_EOL; + $html .= self::generateMeta($properties->getCreator(), 'author'); + $html .= self::generateMeta($properties->getTitle(), 'title'); + $html .= self::generateMeta($properties->getDescription(), 'description'); + $html .= self::generateMeta($properties->getSubject(), 'subject'); + $html .= self::generateMeta($properties->getKeywords(), 'keywords'); + $html .= self::generateMeta($properties->getCategory(), 'category'); + $html .= self::generateMeta($properties->getCompany(), 'company'); + $html .= self::generateMeta($properties->getManager(), 'manager'); + + $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true); $html .= ' ' . PHP_EOL; $html .= '' . PHP_EOL; - $html .= ' ' . PHP_EOL; + $html .= self::BODY_LINE; return $html; } - /** - * Generate sheet data. - * - * @throws WriterException - * - * @return string - */ - public function generateSheetData() + private function generateSheetPrep() { // Ensure that Spans have been calculated? - if ($this->sheetIndex !== null || !$this->spansAreCalculated) { - $this->calculateSpans(); - } + $this->calculateSpans(); // Fetch sheets - $sheets = []; if ($this->sheetIndex === null) { $sheets = $this->spreadsheet->getAllSheets(); } else { - $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); + $sheets = [$this->spreadsheet->getSheet($this->sheetIndex)]; + } + + return $sheets; + } + + private function generateSheetStarts($sheet, $rowMin) + { + // calculate start of , + $tbodyStart = $rowMin; + $theadStart = $theadEnd = 0; // default: no no + if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); + + // we can only support repeating rows that start at top row + if ($rowsToRepeatAtTop[0] == 1) { + $theadStart = $rowsToRepeatAtTop[0]; + $theadEnd = $rowsToRepeatAtTop[1]; + $tbodyStart = $rowsToRepeatAtTop[1] + 1; + } + } + + return [$theadStart, $theadEnd, $tbodyStart]; + } + + private function generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart) + { + // ? + $startTag = ($row == $theadStart) ? (' ' . PHP_EOL) : ''; + if (!$startTag) { + $startTag = ($row == $tbodyStart) ? (' ' . PHP_EOL) : ''; } + $endTag = ($row == $theadEnd) ? (' ' . PHP_EOL) : ''; + $cellType = ($row >= $tbodyStart) ? 'td' : 'th'; + + return [$cellType, $startTag, $endTag]; + } + + /** + * Generate sheet data. + * + * @return string + */ + public function generateSheetData() + { + $sheets = $this->generateSheetPrep(); // Construct HTML $html = ''; @@ -431,52 +457,25 @@ public function generateSheetData() $html .= $this->generateTableHeader($sheet); // Get worksheet dimension - $dimension = explode(':', $sheet->calculateWorksheetDimension()); - $dimension[0] = Coordinate::coordinateFromString($dimension[0]); - $dimension[0][0] = Coordinate::columnIndexFromString($dimension[0][0]); - $dimension[1] = Coordinate::coordinateFromString($dimension[1]); - $dimension[1][0] = Coordinate::columnIndexFromString($dimension[1][0]); - - // row min,max - $rowMin = $dimension[0][1]; - $rowMax = $dimension[1][1]; - - // calculate start of , - $tbodyStart = $rowMin; - $theadStart = $theadEnd = 0; // default: no no - if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); - - // we can only support repeating rows that start at top row - if ($rowsToRepeatAtTop[0] == 1) { - $theadStart = $rowsToRepeatAtTop[0]; - $theadEnd = $rowsToRepeatAtTop[1]; - $tbodyStart = $rowsToRepeatAtTop[1] + 1; - } - } + [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension()); + [$minCol, $minRow] = Coordinate::indexesFromString($min); + [$maxCol, $maxRow] = Coordinate::indexesFromString($max); - // Loop through cells - $row = $rowMin - 1; - while ($row++ < $rowMax) { - // ? - if ($row == $theadStart) { - $html .= ' ' . PHP_EOL; - $cellType = 'th'; - } + [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow); - // ? - if ($row == $tbodyStart) { - $html .= ' ' . PHP_EOL; - $cellType = 'td'; - } + // Loop through cells + $row = $minRow - 1; + while ($row++ < $maxRow) { + [$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart); + $html .= $startTag; // Write row if there are HTML table cells in it if (!isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) { // Start a new rowData $rowData = []; // Loop through columns - $column = $dimension[0][0]; - while ($column <= $dimension[1][0]) { + $column = $minCol; + while ($column <= $maxCol) { // Cell exists? if ($sheet->cellExistsByColumnAndRow($column, $row)) { $rowData[$column] = Coordinate::stringFromColumnIndex($column) . $row; @@ -488,23 +487,16 @@ public function generateSheetData() $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType); } - // ? - if ($row == $theadEnd) { - $html .= ' ' . PHP_EOL; - } + $html .= $endTag; } $html .= $this->extendRowsForChartsAndImages($sheet, $row); - // Close table body. - $html .= ' ' . PHP_EOL; - // Write table footer $html .= $this->generateTableFooter(); - // Writing PDF? - if ($this->isPdf) { + if ($this->isPdf && $this->useInlineCss) { if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) { - $html .= '
      '; + $html .= '
      '; } } @@ -518,8 +510,6 @@ public function generateSheetData() /** * Generate sheet tabs. * - * @throws WriterException - * * @return string */ public function generateNavigation() @@ -553,13 +543,29 @@ public function generateNavigation() return $html; } - private function extendRowsForChartsAndImages(Worksheet $pSheet, $row) + /** + * Extend Row if chart is placed after nominal end of row. + * This code should be exercised by sample: + * Chart/32_Chart_read_write_PDF.php. + * However, that test is suppressed due to out-of-date + * Jpgraph code issuing warnings. So, don't measure + * code coverage for this function till that is fixed. + * + * @param int $row Row to check for charts + * + * @return array + * + * @codeCoverageIgnore + */ + private function extendRowsForCharts(Worksheet $worksheet, int $row) { $rowMax = $row; $colMax = 'A'; + $anyfound = false; if ($this->includeCharts) { - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { + $anyfound = true; $chartCoordinates = $chart->getTopLeftPosition(); $chartTL = Coordinate::coordinateFromString($chartCoordinates['cell']); $chartCol = Coordinate::columnIndexFromString($chartTL[0]); @@ -573,122 +579,138 @@ private function extendRowsForChartsAndImages(Worksheet $pSheet, $row) } } - foreach ($pSheet->getDrawingCollection() as $drawing) { - if ($drawing instanceof Drawing) { - $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); - $imageCol = Coordinate::columnIndexFromString($imageTL[0]); - if ($imageTL[1] > $rowMax) { - $rowMax = $imageTL[1]; - if ($imageCol > Coordinate::columnIndexFromString($colMax)) { - $colMax = $imageTL[0]; - } + return [$rowMax, $colMax, $anyfound]; + } + + private function extendRowsForChartsAndImages(Worksheet $worksheet, int $row): string + { + [$rowMax, $colMax, $anyfound] = $this->extendRowsForCharts($worksheet, $row); + + foreach ($worksheet->getDrawingCollection() as $drawing) { + $anyfound = true; + $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates()); + $imageCol = Coordinate::columnIndexFromString($imageTL[0]); + if ($imageTL[1] > $rowMax) { + $rowMax = $imageTL[1]; + if ($imageCol > Coordinate::columnIndexFromString($colMax)) { + $colMax = $imageTL[0]; } } } // Don't extend rows if not needed - if ($row === $rowMax) { + if ($row === $rowMax || !$anyfound) { return ''; } $html = ''; ++$colMax; - + ++$row; while ($row <= $rowMax) { $html .= ''; for ($col = 'A'; $col != $colMax; ++$col) { - $html .= ''; - $html .= $this->writeImageInCell($pSheet, $col . $row); - if ($this->includeCharts) { - $html .= $this->writeChartInCell($pSheet, $col . $row); + $htmlx = $this->writeImageInCell($worksheet, $col . $row); + $htmlx .= $this->includeCharts ? $this->writeChartInCell($worksheet, $col . $row) : ''; + if ($htmlx) { + $html .= "$htmlx"; + } else { + $html .= ""; } - $html .= ''; } ++$row; - $html .= ''; + $html .= '' . PHP_EOL; } return $html; } + /** + * Convert Windows file name to file protocol URL. + * + * @param string $filename file name on local system + * + * @return string + */ + public static function winFileToUrl($filename) + { + // Windows filename + if (substr($filename, 1, 2) === ':\\') { + $filename = 'file:///' . str_replace('\\', '/', $filename); + } + + return $filename; + } + /** * Generate image tag in cell. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet + * @param Worksheet $worksheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet * @param string $coordinates Cell coordinates * * @return string */ - private function writeImageInCell(Worksheet $pSheet, $coordinates) + private function writeImageInCell(Worksheet $worksheet, $coordinates) { // Construct HTML $html = ''; // Write images - foreach ($pSheet->getDrawingCollection() as $drawing) { + foreach ($worksheet->getDrawingCollection() as $drawing) { + if ($drawing->getCoordinates() != $coordinates) { + continue; + } + $filedesc = $drawing->getDescription(); + $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image'; if ($drawing instanceof Drawing) { - if ($drawing->getCoordinates() == $coordinates) { - $filename = $drawing->getPath(); + $filename = $drawing->getPath(); - // Strip off eventual '.' - if (substr($filename, 0, 1) == '.') { - $filename = substr($filename, 1); - } + // Strip off eventual '.' + $filename = preg_replace('/^[.]/', '', $filename); - // Prepend images root - $filename = $this->getImagesRoot() . $filename; + // Prepend images root + $filename = $this->getImagesRoot() . $filename; - // Strip off eventual '.' - if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') { - $filename = substr($filename, 1); - } + // Strip off eventual '.' if followed by non-/ + $filename = preg_replace('@^[.]([^/])@', '$1', $filename); - // Convert UTF8 data to PCDATA - $filename = htmlspecialchars($filename); + // Convert UTF8 data to PCDATA + $filename = htmlspecialchars($filename, Settings::htmlEntityFlags()); - $html .= PHP_EOL; - if ((!$this->embedImages) || ($this->isPdf)) { - $imageData = $filename; - } else { + $html .= PHP_EOL; + $imageData = self::winFileToUrl($filename); + + if ($this->embedImages && !$this->isPdf) { + $picture = @file_get_contents($filename); + if ($picture !== false) { $imageDetails = getimagesize($filename); - if ($fp = fopen($filename, 'rb', 0)) { - $picture = ''; - while (!feof($fp)) { - $picture .= fread($fp, 1024); - } - fclose($fp); - // base64 encode the binary data, then break it - // into chunks according to RFC 2045 semantics - $base64 = chunk_split(base64_encode($picture)); - $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; - } else { - $imageData = $filename; - } + // base64 encode the binary data + $base64 = base64_encode($picture); + $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; } - - $html .= '
      '; - $html .= ''; - $html .= '
      '; } + + $html .= '' . $filedesc . ''; } elseif ($drawing instanceof MemoryDrawing) { - if ($drawing->getCoordinates() != $coordinates) { - continue; + $imageResource = $drawing->getImageResource(); + if ($imageResource) { + ob_start(); // Let's start output buffering. + // @phpstan-ignore-next-line + imagepng($imageResource); // This will normally output the image, but because of ob_start(), it won't. + $contents = ob_get_contents(); // Instead, output above is saved to $contents + ob_end_clean(); // End the output buffer. + + /** @phpstan-ignore-next-line */ + $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents); + + // Because of the nature of tables, width is more important than height. + // max-width: 100% ensures that image doesnt overflow containing cell + // width: X sets width of supplied image. + // As a result, images bigger than cell will be contained and images smaller will not get stretched + $html .= '' . $filedesc . ''; } - ob_start(); // Let's start output buffering. - imagepng($drawing->getImageResource()); // This will normally output the image, but because of ob_start(), it won't. - $contents = ob_get_contents(); // Instead, output above is saved to $contents - ob_end_clean(); // End the output buffer. - - $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents); - - // Because of the nature of tables, width is more important than height. - // max-width: 100% ensures that image doesnt overflow containing cell - // width: X sets width of supplied image. - // As a result, images bigger than cell will be contained and images smaller will not get stretched - $html .= ''; } } @@ -697,40 +719,42 @@ private function writeImageInCell(Worksheet $pSheet, $coordinates) /** * Generate chart tag in cell. + * This code should be exercised by sample: + * Chart/32_Chart_read_write_PDF.php. + * However, that test is suppressed due to out-of-date + * Jpgraph code issuing warnings. So, don't measure + * code coverage for this function till that is fixed. * - * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet - * @param string $coordinates Cell coordinates - * - * @return string + * @codeCoverageIgnore */ - private function writeChartInCell(Worksheet $pSheet, $coordinates) + private function writeChartInCell(Worksheet $worksheet, string $coordinates): string { // Construct HTML $html = ''; // Write charts - foreach ($pSheet->getChartCollection() as $chart) { + foreach ($worksheet->getChartCollection() as $chart) { if ($chart instanceof Chart) { $chartCoordinates = $chart->getTopLeftPosition(); if ($chartCoordinates['cell'] == $coordinates) { $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png'; if (!$chart->render($chartFileName)) { - return; + return ''; } $html .= PHP_EOL; $imageDetails = getimagesize($chartFileName); + $filedesc = $chart->getTitle(); + $filedesc = $filedesc ? $filedesc->getCaptionText() : ''; + $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart'; if ($fp = fopen($chartFileName, 'rb', 0)) { $picture = fread($fp, filesize($chartFileName)); fclose($fp); - // base64 encode the binary data, then break it - // into chunks according to RFC 2045 semantics - $base64 = chunk_split(base64_encode($picture)); + /** @phpstan-ignore-next-line */ + $base64 = base64_encode($picture); $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64; - $html .= '
      '; - $html .= '' . PHP_EOL; - $html .= '
      '; + $html .= '' . $filedesc . '' . PHP_EOL; unlink($chartFileName); } @@ -747,8 +771,6 @@ private function writeChartInCell(Worksheet $pSheet, $coordinates) * * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) * - * @throws WriterException - * * @return string */ public function generateStyles($generateSurroundingHTML = true) @@ -762,7 +784,7 @@ public function generateStyles($generateSurroundingHTML = true) // Start styles if ($generateSurroundingHTML) { $html .= ' \n"; + // Identify which rows should be omitted in HTML. These are the rows where all the cells + // participate in a merge and the where base cells are somewhere above. + $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn()); + foreach ($candidateSpannedRow as $rowIndex) { + if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) { + if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) { + $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex; + } + } + } + + // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 + if (isset($this->isSpannedRow[$sheetIndex])) { + foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) { + $adjustedBaseCells = []; + $c = -1; + $e = $countColumns - 1; + while ($c++ < $e) { + $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell']; + + if (!in_array($baseCell, $adjustedBaseCells)) { + // subtract rowspan by 1 + --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan']; + $adjustedBaseCells[] = $baseCell; + } + } + } + } } /** @@ -1671,20 +1762,98 @@ private function setMargins(Worksheet $pSheet) * * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092 * - * @param Worksheet $pSheet * @param string $coordinate * * @return string */ - private function writeComment(Worksheet $pSheet, $coordinate) + private function writeComment(Worksheet $worksheet, $coordinate) { $result = ''; - if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) { - $result .= ''; - $result .= '
      ' . nl2br($pSheet->getComment($coordinate)->getText()->getPlainText()) . '
      '; - $result .= PHP_EOL; + if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) { + $sanitizer = new HTMLPurifier(); + $cachePath = File::sysGetTempDir() . '/phpsppur'; + if (is_dir($cachePath) || mkdir($cachePath)) { + $sanitizer->config->set('Cache.SerializerPath', $cachePath); + } + $sanitizedString = $sanitizer->purify($worksheet->getComment($coordinate)->getText()->getPlainText()); + if ($sanitizedString !== '') { + $result .= ''; + $result .= '
      ' . nl2br($sanitizedString) . '
      '; + $result .= PHP_EOL; + } } return $result; } + + public function getOrientation(): ?string + { + return null; + } + + /** + * Generate @page declarations. + * + * @param bool $generateSurroundingHTML + * + * @return string + */ + private function generatePageDeclarations($generateSurroundingHTML) + { + // Ensure that Spans have been calculated? + $this->calculateSpans(); + + // Fetch sheets + $sheets = []; + if ($this->sheetIndex === null) { + $sheets = $this->spreadsheet->getAllSheets(); + } else { + $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex); + } + + // Construct HTML + $htmlPage = $generateSurroundingHTML ? ('' . PHP_EOL) : ''; + + return $htmlPage; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php index 448b532f..b0a62726 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/IWriter.php @@ -6,10 +6,12 @@ interface IWriter { + public const SAVE_WITH_CHARTS = 1; + /** * IWriter constructor. * - * @param Spreadsheet $spreadsheet + * @param Spreadsheet $spreadsheet The spreadsheet that we want to save using this Writer */ public function __construct(Spreadsheet $spreadsheet); @@ -27,11 +29,11 @@ public function getIncludeCharts(); * Set to true, to advise the Writer to include any charts that exist in the PhpSpreadsheet object. * Set to false (the default) to ignore charts. * - * @param bool $pValue + * @param bool $includeCharts * * @return IWriter */ - public function setIncludeCharts($pValue); + public function setIncludeCharts($includeCharts); /** * Get Pre-Calculate Formulas flag @@ -50,20 +52,18 @@ public function getPreCalculateFormulas(); * Set to true (the default) to advise the Writer to calculate all formulae on save * Set to false to prevent precalculation of formulae on save. * - * @param bool $pValue Pre-Calculate Formulas? + * @param bool $precalculateFormulas Pre-Calculate Formulas? * * @return IWriter */ - public function setPreCalculateFormulas($pValue); + public function setPreCalculateFormulas($precalculateFormulas); /** * Save PhpSpreadsheet to file. * - * @param string $pFilename Name of the file to save - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception + * @param resource|string $filename Name of the file to save */ - public function save($pFilename); + public function save($filename, int $flags = 0): void; /** * Get use disk caching where possible? @@ -75,14 +75,12 @@ public function getUseDiskCaching(); /** * Set use disk caching where possible? * - * @param bool $pValue - * @param string $pDirectory Disk caching directory - * - * @throws Exception when directory does not exist + * @param bool $useDiskCache + * @param string $cacheDirectory Disk caching directory * * @return IWriter */ - public function setUseDiskCaching($pValue, $pDirectory = null); + public function setUseDiskCaching($useDiskCache, $cacheDirectory = null); /** * Get disk caching directory. diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php index 43659fa0..827c43b5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods.php @@ -2,7 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Writer; -use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; use PhpOffice\PhpSpreadsheet\Writer\Ods\Content; @@ -12,17 +11,12 @@ use PhpOffice\PhpSpreadsheet\Writer\Ods\Settings; use PhpOffice\PhpSpreadsheet\Writer\Ods\Styles; use PhpOffice\PhpSpreadsheet\Writer\Ods\Thumbnails; -use ZipArchive; +use ZipStream\Exception\OverflowException; +use ZipStream\Option\Archive; +use ZipStream\ZipStream; class Ods extends BaseWriter { - /** - * Private writer parts. - * - * @var Ods\WriterPart[] - */ - private $writerParts = []; - /** * Private PhpSpreadsheet. * @@ -30,127 +24,154 @@ class Ods extends BaseWriter */ private $spreadSheet; + /** + * @var Content + */ + private $writerPartContent; + + /** + * @var Meta + */ + private $writerPartMeta; + + /** + * @var MetaInf + */ + private $writerPartMetaInf; + + /** + * @var Mimetype + */ + private $writerPartMimetype; + + /** + * @var Settings + */ + private $writerPartSettings; + + /** + * @var Styles + */ + private $writerPartStyles; + + /** + * @var Thumbnails + */ + private $writerPartThumbnails; + /** * Create a new Ods. - * - * @param Spreadsheet $spreadsheet */ public function __construct(Spreadsheet $spreadsheet) { $this->setSpreadsheet($spreadsheet); - $writerPartsArray = [ - 'content' => Content::class, - 'meta' => Meta::class, - 'meta_inf' => MetaInf::class, - 'mimetype' => Mimetype::class, - 'settings' => Settings::class, - 'styles' => Styles::class, - 'thumbnails' => Thumbnails::class, - ]; - - foreach ($writerPartsArray as $writer => $class) { - $this->writerParts[$writer] = new $class($this); - } + $this->writerPartContent = new Content($this); + $this->writerPartMeta = new Meta($this); + $this->writerPartMetaInf = new MetaInf($this); + $this->writerPartMimetype = new Mimetype($this); + $this->writerPartSettings = new Settings($this); + $this->writerPartStyles = new Styles($this); + $this->writerPartThumbnails = new Thumbnails($this); } - /** - * Get writer part. - * - * @param string $pPartName Writer part name - * - * @return null|Ods\WriterPart - */ - public function getWriterPart($pPartName) + public function getWriterPartContent(): Content { - if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; - } + return $this->writerPartContent; + } + + public function getWriterPartMeta(): Meta + { + return $this->writerPartMeta; + } - return null; + public function getWriterPartMetaInf(): MetaInf + { + return $this->writerPartMetaInf; + } + + public function getWriterPartMimetype(): Mimetype + { + return $this->writerPartMimetype; + } + + public function getWriterPartSettings(): Settings + { + return $this->writerPartSettings; + } + + public function getWriterPartStyles(): Styles + { + return $this->writerPartStyles; + } + + public function getWriterPartThumbnails(): Thumbnails + { + return $this->writerPartThumbnails; } /** * Save PhpSpreadsheet to file. * - * @param string $pFilename - * - * @throws WriterException + * @param resource|string $filename */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { if (!$this->spreadSheet) { throw new WriterException('PhpSpreadsheet object unassigned.'); } + $this->processFlags($flags); + // garbage collect $this->spreadSheet->garbageCollect(); - // If $pFilename is php://output or php://stdout, make it a temporary file... - $originalFilename = $pFilename; - if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { - $pFilename = @tempnam(File::sysGetTempDir(), 'phpxltmp'); - if ($pFilename == '') { - $pFilename = $originalFilename; - } - } + $this->openFileHandle($filename); - $zip = $this->createZip($pFilename); + $zip = $this->createZip(); - $zip->addFromString('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest()); - $zip->addFromString('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail()); - $zip->addFromString('content.xml', $this->getWriterPart('content')->write()); - $zip->addFromString('meta.xml', $this->getWriterPart('meta')->write()); - $zip->addFromString('mimetype', $this->getWriterPart('mimetype')->write()); - $zip->addFromString('settings.xml', $this->getWriterPart('settings')->write()); - $zip->addFromString('styles.xml', $this->getWriterPart('styles')->write()); + $zip->addFile('META-INF/manifest.xml', $this->getWriterPartMetaInf()->write()); + $zip->addFile('Thumbnails/thumbnail.png', $this->getWriterPartthumbnails()->write()); + // Settings always need to be written before Content; Styles after Content + $zip->addFile('settings.xml', $this->getWriterPartsettings()->write()); + $zip->addFile('content.xml', $this->getWriterPartcontent()->write()); + $zip->addFile('meta.xml', $this->getWriterPartmeta()->write()); + $zip->addFile('mimetype', $this->getWriterPartmimetype()->write()); + $zip->addFile('styles.xml', $this->getWriterPartstyles()->write()); // Close file - if ($zip->close() === false) { - throw new WriterException("Could not close zip file $pFilename."); + try { + $zip->finish(); + } catch (OverflowException $e) { + throw new WriterException('Could not close resource.'); } - // If a temporary file was used, copy it to the correct file stream - if ($originalFilename != $pFilename) { - if (copy($pFilename, $originalFilename) === false) { - throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename."); - } - @unlink($pFilename); - } + $this->maybeCloseFileHandle(); } /** * Create zip object. * - * @param string $pFilename - * - * @throws WriterException - * - * @return ZipArchive + * @return ZipStream */ - private function createZip($pFilename) + private function createZip() { - // Create new ZIP file and open it for writing - $zip = new ZipArchive(); - - if (file_exists($pFilename)) { - unlink($pFilename); - } // Try opening the ZIP file - if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) { - if ($zip->open($pFilename, ZipArchive::CREATE) !== true) { - throw new WriterException("Could not open $pFilename for writing."); - } + if (!is_resource($this->fileHandle)) { + throw new WriterException('Could not open resource for writing.'); } - return $zip; + // Create new ZIP stream + $options = new Archive(); + $options->setEnableZip64(false); + $options->setOutputStream($this->fileHandle); + + return new ZipStream(null, $options); } /** * Get Spreadsheet object. * - * @throws WriterException - * * @return Spreadsheet */ public function getSpreadsheet() diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php new file mode 100644 index 00000000..cf0450f1 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/AutoFilters.php @@ -0,0 +1,63 @@ +objWriter = $objWriter; + $this->spreadsheet = $spreadsheet; + } + + public function write(): void + { + $wrapperWritten = false; + $sheetCount = $this->spreadsheet->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $worksheet = $this->spreadsheet->getSheet($i); + $autofilter = $worksheet->getAutoFilter(); + if ($autofilter !== null && !empty($autofilter->getRange())) { + if ($wrapperWritten === false) { + $this->objWriter->startElement('table:database-ranges'); + $wrapperWritten = true; + } + $this->objWriter->startElement('table:database-range'); + $this->objWriter->writeAttribute('table:orientation', 'column'); + $this->objWriter->writeAttribute('table:display-filter-buttons', 'true'); + $this->objWriter->writeAttribute( + 'table:target-range-address', + $this->formatRange($worksheet, $autofilter) + ); + $this->objWriter->endElement(); + } + } + + if ($wrapperWritten === true) { + $this->objWriter->endElement(); + } + } + + protected function formatRange(Worksheet $worksheet, Autofilter $autofilter): string + { + $title = $worksheet->getTitle(); + $range = $autofilter->getRange(); + + return "'{$title}'.{$range}"; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php index 2f543be5..b0829bf1 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Comment.php @@ -6,14 +6,11 @@ use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; /** - * @category PhpSpreadsheet - * - * @copyright Copyright (c) 2006 - 2015 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) * @author Alexander Pervakov */ class Comment { - public static function write(XMLWriter $objWriter, Cell $cell) + public static function write(XMLWriter $objWriter, Cell $cell): void { $comments = $cell->getWorksheet()->getComments(); if (!isset($comments[$cell->getCoordinate()])) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php new file mode 100644 index 00000000..a3629bd6 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Cell/Style.php @@ -0,0 +1,240 @@ +writer = $writer; + } + + private function mapHorizontalAlignment(string $horizontalAlignment): string + { + switch ($horizontalAlignment) { + case Alignment::HORIZONTAL_CENTER: + case Alignment::HORIZONTAL_CENTER_CONTINUOUS: + case Alignment::HORIZONTAL_DISTRIBUTED: + return 'center'; + case Alignment::HORIZONTAL_RIGHT: + return 'end'; + case Alignment::HORIZONTAL_FILL: + case Alignment::HORIZONTAL_JUSTIFY: + return 'justify'; + } + + return 'start'; + } + + private function mapVerticalAlignment(string $verticalAlignment): string + { + switch ($verticalAlignment) { + case Alignment::VERTICAL_TOP: + return 'top'; + case Alignment::VERTICAL_CENTER: + return 'middle'; + case Alignment::VERTICAL_DISTRIBUTED: + case Alignment::VERTICAL_JUSTIFY: + return 'automatic'; + } + + return 'bottom'; + } + + private function writeFillStyle(Fill $fill): void + { + switch ($fill->getFillType()) { + case Fill::FILL_SOLID: + $this->writer->writeAttribute('fo:background-color', sprintf( + '#%s', + strtolower($fill->getStartColor()->getRGB()) + )); + + break; + case Fill::FILL_GRADIENT_LINEAR: + case Fill::FILL_GRADIENT_PATH: + /// TODO :: To be implemented + break; + case Fill::FILL_NONE: + default: + } + } + + private function writeCellProperties(CellStyle $style): void + { + // Align + $hAlign = $style->getAlignment()->getHorizontal(); + $vAlign = $style->getAlignment()->getVertical(); + $wrap = $style->getAlignment()->getWrapText(); + + $this->writer->startElement('style:table-cell-properties'); + if (!empty($vAlign) || $wrap) { + if (!empty($vAlign)) { + $vAlign = $this->mapVerticalAlignment($vAlign); + $this->writer->writeAttribute('style:vertical-align', $vAlign); + } + if ($wrap) { + $this->writer->writeAttribute('fo:wrap-option', 'wrap'); + } + } + $this->writer->writeAttribute('style:rotation-align', 'none'); + + // Fill + if ($fill = $style->getFill()) { + $this->writeFillStyle($fill); + } + + $this->writer->endElement(); + + if (!empty($hAlign)) { + $hAlign = $this->mapHorizontalAlignment($hAlign); + $this->writer->startElement('style:paragraph-properties'); + $this->writer->writeAttribute('fo:text-align', $hAlign); + $this->writer->endElement(); + } + } + + protected function mapUnderlineStyle(Font $font): string + { + switch ($font->getUnderline()) { + case Font::UNDERLINE_DOUBLE: + case Font::UNDERLINE_DOUBLEACCOUNTING: + return'double'; + case Font::UNDERLINE_SINGLE: + case Font::UNDERLINE_SINGLEACCOUNTING: + return'single'; + } + + return 'none'; + } + + protected function writeTextProperties(CellStyle $style): void + { + // Font + $this->writer->startElement('style:text-properties'); + + $font = $style->getFont(); + + if ($font->getBold()) { + $this->writer->writeAttribute('fo:font-weight', 'bold'); + $this->writer->writeAttribute('style:font-weight-complex', 'bold'); + $this->writer->writeAttribute('style:font-weight-asian', 'bold'); + } + + if ($font->getItalic()) { + $this->writer->writeAttribute('fo:font-style', 'italic'); + } + + if ($color = $font->getColor()) { + $this->writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB())); + } + + if ($family = $font->getName()) { + $this->writer->writeAttribute('fo:font-family', $family); + } + + if ($size = $font->getSize()) { + $this->writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); + } + + if ($font->getUnderline() && $font->getUnderline() !== Font::UNDERLINE_NONE) { + $this->writer->writeAttribute('style:text-underline-style', 'solid'); + $this->writer->writeAttribute('style:text-underline-width', 'auto'); + $this->writer->writeAttribute('style:text-underline-color', 'font-color'); + + $underline = $this->mapUnderlineStyle($font); + $this->writer->writeAttribute('style:text-underline-type', $underline); + } + + $this->writer->endElement(); // Close style:text-properties + } + + protected function writeColumnProperties(ColumnDimension $columnDimension): void + { + $this->writer->startElement('style:table-column-properties'); + $this->writer->writeAttribute( + 'style:column-width', + round($columnDimension->getWidth(Dimension::UOM_CENTIMETERS), 3) . 'cm' + ); + $this->writer->writeAttribute('fo:break-before', 'auto'); + + // End + $this->writer->endElement(); // Close style:table-column-properties + } + + public function writeColumnStyles(ColumnDimension $columnDimension, int $sheetId): void + { + $this->writer->startElement('style:style'); + $this->writer->writeAttribute('style:family', 'table-column'); + $this->writer->writeAttribute( + 'style:name', + sprintf('%s_%d_%d', self::COLUMN_STYLE_PREFIX, $sheetId, $columnDimension->getColumnNumeric()) + ); + + $this->writeColumnProperties($columnDimension); + + // End + $this->writer->endElement(); // Close style:style + } + + protected function writeRowProperties(RowDimension $rowDimension): void + { + $this->writer->startElement('style:table-row-properties'); + $this->writer->writeAttribute( + 'style:row-height', + round($rowDimension->getRowHeight(Dimension::UOM_CENTIMETERS), 3) . 'cm' + ); + $this->writer->writeAttribute('style:use-optimal-row-height', 'true'); + $this->writer->writeAttribute('fo:break-before', 'auto'); + + // End + $this->writer->endElement(); // Close style:table-row-properties + } + + public function writeRowStyles(RowDimension $rowDimension, int $sheetId): void + { + $this->writer->startElement('style:style'); + $this->writer->writeAttribute('style:family', 'table-row'); + $this->writer->writeAttribute( + 'style:name', + sprintf('%s_%d_%d', self::ROW_STYLE_PREFIX, $sheetId, $rowDimension->getRowIndex()) + ); + + $this->writeRowProperties($rowDimension); + + // End + $this->writer->endElement(); // Close style:style + } + + public function write(CellStyle $style): void + { + $this->writer->startElement('style:style'); + $this->writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); + $this->writer->writeAttribute('style:family', 'table-cell'); + $this->writer->writeAttribute('style:parent-style-name', 'Default'); + + // Alignment, fill colour, etc + $this->writeCellProperties($style); + + // style:text-properties + $this->writeTextProperties($style); + + // End + $this->writer->endElement(); // Close style:style + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php index dea5100f..5d227c84 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Content.php @@ -7,36 +7,39 @@ use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Style\Fill; -use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Worksheet\Row; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception; use PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Comment; +use PhpOffice\PhpSpreadsheet\Writer\Ods\Cell\Style; /** - * @category PhpSpreadsheet - * - * @method Ods getParentWriter - * - * @copyright Copyright (c) 2006 - 2015 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) * @author Alexander Pervakov */ class Content extends WriterPart { const NUMBER_COLS_REPEATED_MAX = 1024; const NUMBER_ROWS_REPEATED_MAX = 1048576; - const CELL_STYLE_PREFIX = 'ce'; + + private $formulaConvertor; + + /** + * Set parent Ods writer. + */ + public function __construct(Ods $writer) + { + parent::__construct($writer); + + $this->formulaConvertor = new Formula($this->getParentWriter()->getSpreadsheet()->getDefinedNames()); + } /** * Write content.xml to XML format. * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function write() + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -98,7 +101,10 @@ public function write() $this->writeSheets($objWriter); - $objWriter->writeElement('table:named-expressions'); + (new AutoFilters($objWriter, $this->getParentWriter()->getSpreadsheet()))->write(); + // Defined names (ranges and formulae) + (new NamedExpressions($objWriter, $this->getParentWriter()->getSpreadsheet(), $this->formulaConvertor))->write(); + $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); @@ -108,33 +114,34 @@ public function write() /** * Write sheets. - * - * @param XMLWriter $objWriter */ - private function writeSheets(XMLWriter $objWriter) + private function writeSheets(XMLWriter $objWriter): void { - $spreadsheet = $this->getParentWriter()->getSpreadsheet(); // @var $spreadsheet Spreadsheet - + $spreadsheet = $this->getParentWriter()->getSpreadsheet(); /** @var Spreadsheet $spreadsheet */ $sheetCount = $spreadsheet->getSheetCount(); - for ($i = 0; $i < $sheetCount; ++$i) { + for ($sheetIndex = 0; $sheetIndex < $sheetCount; ++$sheetIndex) { $objWriter->startElement('table:table'); - $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($i)->getTitle()); + $objWriter->writeAttribute('table:name', $spreadsheet->getSheet($sheetIndex)->getTitle()); $objWriter->writeElement('office:forms'); - $objWriter->startElement('table:table-column'); - $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); - $objWriter->endElement(); - $this->writeRows($objWriter, $spreadsheet->getSheet($i)); + foreach ($spreadsheet->getSheet($sheetIndex)->getColumnDimensions() as $columnDimension) { + $objWriter->startElement('table:table-column'); + $objWriter->writeAttribute( + 'table:style-name', + sprintf('%s_%d_%d', Style::COLUMN_STYLE_PREFIX, $sheetIndex, $columnDimension->getColumnNumeric()) + ); + $objWriter->writeAttribute('table:default-cell-style-name', 'ce0'); +// $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->endElement(); + } + $this->writeRows($objWriter, $spreadsheet->getSheet($sheetIndex), $sheetIndex); $objWriter->endElement(); } } /** * Write rows of the specified sheet. - * - * @param XMLWriter $objWriter - * @param Worksheet $sheet */ - private function writeRows(XMLWriter $objWriter, Worksheet $sheet) + private function writeRows(XMLWriter $objWriter, Worksheet $sheet, int $sheetIndex): void { $numberRowsRepeated = self::NUMBER_ROWS_REPEATED_MAX; $span_row = 0; @@ -148,8 +155,14 @@ private function writeRows(XMLWriter $objWriter, Worksheet $sheet) if ($span_row > 1) { $objWriter->writeAttribute('table:number-rows-repeated', $span_row); } + if ($sheet->getRowDimension($row->getRowIndex())->getRowHeight() > 0) { + $objWriter->writeAttribute( + 'table:style_name', + sprintf('%s_%d_%d', Style::ROW_STYLE_PREFIX, $sheetIndex, $row->getRowIndex()) + ); + } $objWriter->startElement('table:table-cell'); - $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->writeAttribute('table:number-columns-repeated', (string) self::NUMBER_COLS_REPEATED_MAX); $objWriter->endElement(); $objWriter->endElement(); $span_row = 0; @@ -166,13 +179,8 @@ private function writeRows(XMLWriter $objWriter, Worksheet $sheet) /** * Write cells of the specified row. - * - * @param XMLWriter $objWriter - * @param Row $row - * - * @throws Exception */ - private function writeCells(XMLWriter $objWriter, Row $row) + private function writeCells(XMLWriter $objWriter, Row $row): void { $numberColsRepeated = self::NUMBER_COLS_REPEATED_MAX; $prevColumn = -1; @@ -189,7 +197,7 @@ private function writeCells(XMLWriter $objWriter, Row $row) // Style XF $style = $cell->getXfIndex(); if ($style !== null) { - $objWriter->writeAttribute('table:style-name', self::CELL_STYLE_PREFIX . $style); + $objWriter->writeAttribute('table:style-name', Style::CELL_STYLE_PREFIX . $style); } switch ($cell->getDataType()) { @@ -200,7 +208,10 @@ private function writeCells(XMLWriter $objWriter, Row $row) break; case DataType::TYPE_ERROR: - throw new Exception('Writing of error not implemented yet.'); + $objWriter->writeAttribute('table:formula', 'of:=#NULL!'); + $objWriter->writeAttribute('office:value-type', 'string'); + $objWriter->writeAttribute('office:string-value', ''); + $objWriter->writeElement('text:p', '#NULL!'); break; case DataType::TYPE_FORMULA: @@ -212,7 +223,7 @@ private function writeCells(XMLWriter $objWriter, Row $row) // don't do anything } } - $objWriter->writeAttribute('table:formula', 'of:' . $cell->getValue()); + $objWriter->writeAttribute('table:formula', $this->formulaConvertor->convertFormula($cell->getValue())); if (is_numeric($formulaValue)) { $objWriter->writeAttribute('office:value-type', 'float'); } else { @@ -221,10 +232,6 @@ private function writeCells(XMLWriter $objWriter, Row $row) $objWriter->writeAttribute('office:value', $formulaValue); $objWriter->writeElement('text:p', $formulaValue); - break; - case DataType::TYPE_INLINE: - throw new Exception('Writing of inline not implemented yet.'); - break; case DataType::TYPE_NUMERIC: $objWriter->writeAttribute('office:value-type', 'float'); @@ -232,6 +239,8 @@ private function writeCells(XMLWriter $objWriter, Row $row) $objWriter->writeElement('text:p', $cell->getValue()); break; + case DataType::TYPE_INLINE: + // break intentionally omitted case DataType::TYPE_STRING: $objWriter->writeAttribute('office:value-type', 'string'); $objWriter->writeElement('text:p', $cell->getValue()); @@ -258,11 +267,10 @@ private function writeCells(XMLWriter $objWriter, Row $row) /** * Write span. * - * @param XMLWriter $objWriter * @param int $curColumn * @param int $prevColumn */ - private function writeCellSpan(XMLWriter $objWriter, $curColumn, $prevColumn) + private function writeCellSpan(XMLWriter $objWriter, $curColumn, $prevColumn): void { $diff = $curColumn - $prevColumn - 1; if (1 === $diff) { @@ -276,107 +284,39 @@ private function writeCellSpan(XMLWriter $objWriter, $curColumn, $prevColumn) /** * Write XF cell styles. - * - * @param XMLWriter $writer - * @param Spreadsheet $spreadsheet */ - private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet) + private function writeXfStyles(XMLWriter $writer, Spreadsheet $spreadsheet): void { - foreach ($spreadsheet->getCellXfCollection() as $style) { - $writer->startElement('style:style'); - $writer->writeAttribute('style:name', self::CELL_STYLE_PREFIX . $style->getIndex()); - $writer->writeAttribute('style:family', 'table-cell'); - $writer->writeAttribute('style:parent-style-name', 'Default'); - - // style:text-properties + $styleWriter = new Style($writer); - // Font - $writer->startElement('style:text-properties'); - - $font = $style->getFont(); - - if ($font->getBold()) { - $writer->writeAttribute('fo:font-weight', 'bold'); - $writer->writeAttribute('style:font-weight-complex', 'bold'); - $writer->writeAttribute('style:font-weight-asian', 'bold'); - } - - if ($font->getItalic()) { - $writer->writeAttribute('fo:font-style', 'italic'); - } - - if ($color = $font->getColor()) { - $writer->writeAttribute('fo:color', sprintf('#%s', $color->getRGB())); - } - - if ($family = $font->getName()) { - $writer->writeAttribute('fo:font-family', $family); - } - - if ($size = $font->getSize()) { - $writer->writeAttribute('fo:font-size', sprintf('%.1Fpt', $size)); - } - - if ($font->getUnderline() && $font->getUnderline() != Font::UNDERLINE_NONE) { - $writer->writeAttribute('style:text-underline-style', 'solid'); - $writer->writeAttribute('style:text-underline-width', 'auto'); - $writer->writeAttribute('style:text-underline-color', 'font-color'); - - switch ($font->getUnderline()) { - case Font::UNDERLINE_DOUBLE: - $writer->writeAttribute('style:text-underline-type', 'double'); - - break; - case Font::UNDERLINE_SINGLE: - $writer->writeAttribute('style:text-underline-type', 'single'); - - break; + $sheetCount = $spreadsheet->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $worksheet = $spreadsheet->getSheet($i); + $worksheet->calculateColumnWidths(); + foreach ($worksheet->getColumnDimensions() as $columnDimension) { + if ($columnDimension->getWidth() !== -1.0) { + $styleWriter->writeColumnStyles($columnDimension, $i); } } - - $writer->endElement(); // Close style:text-properties - - // style:table-cell-properties - - $writer->startElement('style:table-cell-properties'); - $writer->writeAttribute('style:rotation-align', 'none'); - - // Fill - if ($fill = $style->getFill()) { - switch ($fill->getFillType()) { - case Fill::FILL_SOLID: - $writer->writeAttribute('fo:background-color', sprintf( - '#%s', - strtolower($fill->getStartColor()->getRGB()) - )); - - break; - case Fill::FILL_GRADIENT_LINEAR: - case Fill::FILL_GRADIENT_PATH: - /// TODO :: To be implemented - break; - case Fill::FILL_NONE: - default: + } + for ($i = 0; $i < $sheetCount; ++$i) { + $worksheet = $spreadsheet->getSheet($i); + foreach ($worksheet->getRowDimensions() as $rowDimension) { + if ($rowDimension->getRowHeight() > 0.0) { + $styleWriter->writeRowStyles($rowDimension, $i); } } + } - $writer->endElement(); // Close style:table-cell-properties - - // End - - $writer->endElement(); // Close style:style + foreach ($spreadsheet->getCellXfCollection() as $style) { + $styleWriter->write($style); } } /** * Write attributes for merged cell. - * - * @param XMLWriter $objWriter - * @param Cell $cell - * - * @throws \PhpOffice\PhpSpreadsheet\Exception */ - private function writeCellMerge(XMLWriter $objWriter, Cell $cell) + private function writeCellMerge(XMLWriter $objWriter, Cell $cell): void { if (!$cell->isMergeRangeValueCell()) { return; @@ -387,9 +327,9 @@ private function writeCellMerge(XMLWriter $objWriter, Cell $cell) $start = Coordinate::coordinateFromString($startCell); $end = Coordinate::coordinateFromString($endCell); $columnSpan = Coordinate::columnIndexFromString($end[0]) - Coordinate::columnIndexFromString($start[0]) + 1; - $rowSpan = $end[1] - $start[1] + 1; + $rowSpan = ((int) $end[1]) - ((int) $start[1]) + 1; - $objWriter->writeAttribute('table:number-columns-spanned', $columnSpan); - $objWriter->writeAttribute('table:number-rows-spanned', $rowSpan); + $objWriter->writeAttribute('table:number-columns-spanned', (string) $columnSpan); + $objWriter->writeAttribute('table:number-rows-spanned', (string) $rowSpan); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Formula.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Formula.php new file mode 100644 index 00000000..db766fb4 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Formula.php @@ -0,0 +1,119 @@ +definedNames[] = $definedName->getName(); + } + } + + public function convertFormula(string $formula, string $worksheetName = ''): string + { + $formula = $this->convertCellReferences($formula, $worksheetName); + $formula = $this->convertDefinedNames($formula); + + if (substr($formula, 0, 1) !== '=') { + $formula = '=' . $formula; + } + + return 'of:' . $formula; + } + + private function convertDefinedNames(string $formula): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '/mui', + $formula, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $lengths = array_map('strlen', array_column($splitRanges[0], 0)); + $offsets = array_column($splitRanges[0], 1); + $values = array_column($splitRanges[0], 0); + + while ($splitCount > 0) { + --$splitCount; + $length = $lengths[$splitCount]; + $offset = $offsets[$splitCount]; + $value = $values[$splitCount]; + + if (in_array($value, $this->definedNames, true)) { + $formula = substr($formula, 0, $offset) . '$$' . $value . substr($formula, $offset + $length); + } + } + + return $formula; + } + + private function convertCellReferences(string $formula, string $worksheetName): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', + $formula, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $lengths = array_map('strlen', array_column($splitRanges[0], 0)); + $offsets = array_column($splitRanges[0], 1); + + $worksheets = $splitRanges[2]; + $columns = $splitRanges[6]; + $rows = $splitRanges[7]; + + // Replace any commas in the formula with semi-colons for Ods + // If by chance there are commas in worksheet names, then they will be "fixed" again in the loop + // because we've already extracted worksheet names with our preg_match_all() + $formula = str_replace(',', ';', $formula); + while ($splitCount > 0) { + --$splitCount; + $length = $lengths[$splitCount]; + $offset = $offsets[$splitCount]; + $worksheet = $worksheets[$splitCount][0]; + $column = $columns[$splitCount][0]; + $row = $rows[$splitCount][0]; + + $newRange = ''; + if (empty($worksheet)) { + if (($offset === 0) || ($formula[$offset - 1] !== ':')) { + // We need a worksheet + $worksheet = $worksheetName; + } + } else { + $worksheet = str_replace("''", "'", trim($worksheet, "'")); + } + if (!empty($worksheet)) { + $newRange = "['" . str_replace("'", "''", $worksheet) . "'"; + } elseif (substr($formula, $offset - 1, 1) !== ':') { + $newRange = '['; + } + $newRange .= '.'; + + if (!empty($column)) { + $newRange .= $column; + } + if (!empty($row)) { + $newRange .= $row; + } + // close the wrapping [] unless this is the first part of a range + $newRange .= substr($formula, $offset + $length, 1) !== ':' ? ']' : ''; + + $formula = substr($formula, 0, $offset) . $newRange . substr($formula, $offset + $length); + } + + return $formula; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php index ffe5eff7..16f7c8b5 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Meta.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; +use PhpOffice\PhpSpreadsheet\Document\Properties; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -10,17 +12,11 @@ class Meta extends WriterPart /** * Write meta.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function write(Spreadsheet $spreadsheet = null) + public function write(): string { - if (!$spreadsheet) { - $spreadsheet = $this->getParentWriter()->getSpreadsheet(); - } + $spreadsheet = $this->getParentWriter()->getSpreadsheet(); $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { @@ -47,15 +43,24 @@ public function write(Spreadsheet $spreadsheet = null) $objWriter->writeElement('meta:initial-creator', $spreadsheet->getProperties()->getCreator()); $objWriter->writeElement('dc:creator', $spreadsheet->getProperties()->getCreator()); - $objWriter->writeElement('meta:creation-date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); - $objWriter->writeElement('dc:date', date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); + $created = $spreadsheet->getProperties()->getCreated(); + $date = Date::dateTimeFromTimestamp("$created"); + $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); + $objWriter->writeElement('meta:creation-date', $date->format(DATE_W3C)); + $created = $spreadsheet->getProperties()->getModified(); + $date = Date::dateTimeFromTimestamp("$created"); + $date->setTimeZone(Date::getDefaultOrLocalTimeZone()); + $objWriter->writeElement('dc:date', $date->format(DATE_W3C)); $objWriter->writeElement('dc:title', $spreadsheet->getProperties()->getTitle()); $objWriter->writeElement('dc:description', $spreadsheet->getProperties()->getDescription()); $objWriter->writeElement('dc:subject', $spreadsheet->getProperties()->getSubject()); - $keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); - foreach ($keywords as $keyword) { - $objWriter->writeElement('meta:keyword', $keyword); - } + $objWriter->writeElement('meta:keyword', $spreadsheet->getProperties()->getKeywords()); + // Don't know if this changed over time, but the keywords are all + // in a single declaration now. + //$keywords = explode(' ', $spreadsheet->getProperties()->getKeywords()); + //foreach ($keywords as $keyword) { + // $objWriter->writeElement('meta:keyword', $keyword); + //} // $objWriter->startElement('meta:user-defined'); @@ -68,10 +73,50 @@ public function write(Spreadsheet $spreadsheet = null) $objWriter->writeRaw($spreadsheet->getProperties()->getCategory()); $objWriter->endElement(); + self::writeDocPropsCustom($objWriter, $spreadsheet); + $objWriter->endElement(); $objWriter->endElement(); return $objWriter->getData(); } + + private static function writeDocPropsCustom(XMLWriter $objWriter, Spreadsheet $spreadsheet): void + { + $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); + foreach ($customPropertyList as $key => $customProperty) { + $propertyValue = $spreadsheet->getProperties()->getCustomPropertyValue($customProperty); + $propertyType = $spreadsheet->getProperties()->getCustomPropertyType($customProperty); + + $objWriter->startElement('meta:user-defined'); + $objWriter->writeAttribute('meta:name', $customProperty); + + switch ($propertyType) { + case Properties::PROPERTY_TYPE_INTEGER: + case Properties::PROPERTY_TYPE_FLOAT: + $objWriter->writeAttribute('meta:value-type', 'float'); + $objWriter->writeRawData($propertyValue); + + break; + case Properties::PROPERTY_TYPE_BOOLEAN: + $objWriter->writeAttribute('meta:value-type', 'boolean'); + $objWriter->writeRawData($propertyValue ? 'true' : 'false'); + + break; + case Properties::PROPERTY_TYPE_DATE: + $objWriter->writeAttribute('meta:value-type', 'date'); + $dtobj = Date::dateTimeFromTimestamp($propertyValue ?? 0); + $objWriter->writeRawData($dtobj->format(DATE_W3C)); + + break; + default: + $objWriter->writeRawData($propertyValue); + + break; + } + + $objWriter->endElement(); + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php index 1ec9d1eb..f3f0d5fc 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/MetaInf.php @@ -9,11 +9,9 @@ class MetaInf extends WriterPart /** * Write META-INF/manifest.xml to XML format. * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function writeManifest() + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php index d0fed2b3..e109e6e7 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Mimetype.php @@ -2,18 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; -use PhpOffice\PhpSpreadsheet\Spreadsheet; - class Mimetype extends WriterPart { /** * Write mimetype to plain text format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function write(Spreadsheet $spreadsheet = null) + public function write(): string { return 'application/vnd.oasis.opendocument.spreadsheet'; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php new file mode 100644 index 00000000..e309dab1 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/NamedExpressions.php @@ -0,0 +1,140 @@ +objWriter = $objWriter; + $this->spreadsheet = $spreadsheet; + $this->formulaConvertor = $formulaConvertor; + } + + public function write(): string + { + $this->objWriter->startElement('table:named-expressions'); + $this->writeExpressions(); + $this->objWriter->endElement(); + + return ''; + } + + private function writeExpressions(): void + { + $definedNames = $this->spreadsheet->getDefinedNames(); + + foreach ($definedNames as $definedName) { + if ($definedName->isFormula()) { + $this->objWriter->startElement('table:named-expression'); + $this->writeNamedFormula($definedName, $this->spreadsheet->getActiveSheet()); + } else { + $this->objWriter->startElement('table:named-range'); + $this->writeNamedRange($definedName); + } + + $this->objWriter->endElement(); + } + } + + private function writeNamedFormula(DefinedName $definedName, Worksheet $defaultWorksheet): void + { + $title = ($definedName->getWorksheet() !== null) ? $definedName->getWorksheet()->getTitle() : $defaultWorksheet->getTitle(); + $this->objWriter->writeAttribute('table:name', $definedName->getName()); + $this->objWriter->writeAttribute( + 'table:expression', + $this->formulaConvertor->convertFormula($definedName->getValue(), $title) + ); + $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( + $definedName, + "'" . $title . "'!\$A\$1" + )); + } + + private function writeNamedRange(DefinedName $definedName): void + { + $baseCell = '$A$1'; + $ws = $definedName->getWorksheet(); + if ($ws !== null) { + $baseCell = "'" . $ws->getTitle() . "'!$baseCell"; + } + $this->objWriter->writeAttribute('table:name', $definedName->getName()); + $this->objWriter->writeAttribute('table:base-cell-address', $this->convertAddress( + $definedName, + $baseCell + )); + $this->objWriter->writeAttribute('table:cell-range-address', $this->convertAddress($definedName, $definedName->getValue())); + } + + private function convertAddress(DefinedName $definedName, string $address): string + { + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', + $address, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $lengths = array_map('strlen', array_column($splitRanges[0], 0)); + $offsets = array_column($splitRanges[0], 1); + + $worksheets = $splitRanges[2]; + $columns = $splitRanges[6]; + $rows = $splitRanges[7]; + + while ($splitCount > 0) { + --$splitCount; + $length = $lengths[$splitCount]; + $offset = $offsets[$splitCount]; + $worksheet = $worksheets[$splitCount][0]; + $column = $columns[$splitCount][0]; + $row = $rows[$splitCount][0]; + + $newRange = ''; + if (empty($worksheet)) { + if (($offset === 0) || ($address[$offset - 1] !== ':')) { + // We need a worksheet + $ws = $definedName->getWorksheet(); + if ($ws !== null) { + $worksheet = $ws->getTitle(); + } + } + } else { + $worksheet = str_replace("''", "'", trim($worksheet, "'")); + } + if (!empty($worksheet)) { + $newRange = "'" . str_replace("'", "''", $worksheet) . "'."; + } + + if (!empty($column)) { + $newRange .= $column; + } + if (!empty($row)) { + $newRange .= $row; + } + + $address = substr($address, 0, $offset) . $newRange . substr($address, $offset + $length); + } + + if (substr($address, 0, 1) === '=') { + $address = substr($address, 1); + } + + return $address; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php index 18f7ee6d..06445591 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Settings.php @@ -2,23 +2,21 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; +use PhpOffice\PhpSpreadsheet\Cell\CellAddress; +use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Settings extends WriterPart { /** * Write settings.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function write(Spreadsheet $spreadsheet = null) + public function write(): string { - $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); } else { @@ -41,14 +39,114 @@ public function write(Spreadsheet $spreadsheet = null) $objWriter->writeAttribute('config:name', 'ooo:view-settings'); $objWriter->startElement('config:config-item-map-indexed'); $objWriter->writeAttribute('config:name', 'Views'); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->startElement('config:config-item-map-entry'); + $spreadsheet = $this->getParentWriter()->getSpreadsheet(); + + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'ViewId'); + $objWriter->writeAttribute('config:type', 'string'); + $objWriter->text('view1'); + $objWriter->endElement(); // ViewId + $objWriter->startElement('config:config-item-map-named'); + + $this->writeAllWorksheetSettings($objWriter, $spreadsheet); + + $wstitle = $spreadsheet->getActiveSheet()->getTitle(); + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'ActiveTable'); + $objWriter->writeAttribute('config:type', 'string'); + $objWriter->text($wstitle); + $objWriter->endElement(); // config:config-item ActiveTable + + $objWriter->endElement(); // config:config-item-map-entry + $objWriter->endElement(); // config:config-item-map-indexed Views + $objWriter->endElement(); // config:config-item-set ooo:view-settings $objWriter->startElement('config:config-item-set'); $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); - $objWriter->endElement(); - $objWriter->endElement(); - $objWriter->endElement(); + $objWriter->endElement(); // config:config-item-set ooo:configuration-settings + $objWriter->endElement(); // office:settings + $objWriter->endElement(); // office:document-settings return $objWriter->getData(); } + + private function writeAllWorksheetSettings(XMLWriter $objWriter, Spreadsheet $spreadsheet): void + { + $objWriter->writeAttribute('config:name', 'Tables'); + + foreach ($spreadsheet->getWorksheetIterator() as $worksheet) { + $this->writeWorksheetSettings($objWriter, $worksheet); + } + + $objWriter->endElement(); // config:config-item-map-entry Tables + } + + private function writeWorksheetSettings(XMLWriter $objWriter, Worksheet $worksheet): void + { + $objWriter->startElement('config:config-item-map-entry'); + $objWriter->writeAttribute('config:name', $worksheet->getTitle()); + + $this->writeSelectedCells($objWriter, $worksheet); + if ($worksheet->getFreezePane() !== null) { + $this->writeFreezePane($objWriter, $worksheet); + } + + $objWriter->endElement(); // config:config-item-map-entry Worksheet + } + + private function writeSelectedCells(XMLWriter $objWriter, Worksheet $worksheet): void + { + $selected = $worksheet->getSelectedCells(); + if (preg_match('/^([a-z]+)([0-9]+)/i', $selected, $matches) === 1) { + $colSel = Coordinate::columnIndexFromString($matches[1]) - 1; + $rowSel = (int) $matches[2] - 1; + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'CursorPositionX'); + $objWriter->writeAttribute('config:type', 'int'); + $objWriter->text((string) $colSel); + $objWriter->endElement(); + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', 'CursorPositionY'); + $objWriter->writeAttribute('config:type', 'int'); + $objWriter->text((string) $rowSel); + $objWriter->endElement(); + } + } + + private function writeSplitValue(XMLWriter $objWriter, string $splitMode, string $type, string $value): void + { + $objWriter->startElement('config:config-item'); + $objWriter->writeAttribute('config:name', $splitMode); + $objWriter->writeAttribute('config:type', $type); + $objWriter->text($value); + $objWriter->endElement(); + } + + private function writeFreezePane(XMLWriter $objWriter, Worksheet $worksheet): void + { + $freezePane = CellAddress::fromCellAddress($worksheet->getFreezePane()); + if ($freezePane->cellAddress() === 'A1') { + return; + } + + $columnId = $freezePane->columnId(); + $columnName = $freezePane->columnName(); + $row = $freezePane->rowId(); + + $this->writeSplitValue($objWriter, 'HorizontalSplitMode', 'short', '2'); + $this->writeSplitValue($objWriter, 'HorizontalSplitPosition', 'int', (string) ($columnId - 1)); + $this->writeSplitValue($objWriter, 'PositionLeft', 'short', '0'); + $this->writeSplitValue($objWriter, 'PositionRight', 'short', (string) ($columnId - 1)); + + for ($column = 'A'; $column !== $columnName; ++$column) { + $worksheet->getColumnDimension($column)->setAutoSize(true); + } + + $this->writeSplitValue($objWriter, 'VerticalSplitMode', 'short', '2'); + $this->writeSplitValue($objWriter, 'VerticalSplitPosition', 'int', (string) ($row - 1)); + $this->writeSplitValue($objWriter, 'PositionTop', 'short', '0'); + $this->writeSplitValue($objWriter, 'PositionBottom', 'short', (string) ($row - 1)); + + $this->writeSplitValue($objWriter, 'ActiveSplitRange', 'short', '3'); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php index eaf5cad9..448b1eff 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Styles.php @@ -3,20 +3,15 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; -use PhpOffice\PhpSpreadsheet\Spreadsheet; class Styles extends WriterPart { /** * Write styles.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function write(Spreadsheet $spreadsheet = null) + public function write(): string { $objWriter = null; if ($this->getParentWriter()->getUseDiskCaching()) { diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php index a29a14ad..db9579d0 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/Thumbnails.php @@ -2,18 +2,14 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Ods; -use PhpOffice\PhpSpreadsheet\Spreadsheet; - class Thumbnails extends WriterPart { /** * Write Thumbnails/thumbnail.png to PNG format. * - * @param Spreadsheet $spreadsheet - * * @return string XML Output */ - public function writeThumbnail(Spreadsheet $spreadsheet = null) + public function write(): string { return ''; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php index 3e2f9684..17d5d169 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Ods/WriterPart.php @@ -25,11 +25,11 @@ public function getParentWriter() /** * Set parent Ods writer. - * - * @param Ods $writer */ public function __construct(Ods $writer) { $this->parentWriter = $writer; } + + abstract public function write(): string; } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php index d9184560..493bbba3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf.php @@ -2,7 +2,6 @@ namespace PhpOffice\PhpSpreadsheet\Writer; -use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; @@ -27,24 +26,17 @@ abstract class Pdf extends Html /** * Orientation (Over-ride). * - * @var string + * @var ?string */ protected $orientation; /** * Paper size (Over-ride). * - * @var int + * @var ?int */ protected $paperSize; - /** - * Temporary storage for Save Array Return type. - * - * @var string - */ - private $saveArrayReturnType; - /** * Paper Sizes xRef List. * @@ -127,8 +119,9 @@ abstract class Pdf extends Html public function __construct(Spreadsheet $spreadsheet) { parent::__construct($spreadsheet); - $this->setUseInlineCss(true); - $this->tempDir = File::sysGetTempDir(); + //$this->setUseInlineCss(true); + $this->tempDir = File::sysGetTempDir() . '/phpsppdf'; + $this->isPdf = true; } /** @@ -162,7 +155,7 @@ public function setFont($fontName) /** * Get Paper Size. * - * @return int + * @return ?int */ public function getPaperSize() { @@ -172,23 +165,21 @@ public function getPaperSize() /** * Set Paper Size. * - * @param string $pValue Paper size see PageSetup::PAPERSIZE_* + * @param int $paperSize Paper size see PageSetup::PAPERSIZE_* * * @return self */ - public function setPaperSize($pValue) + public function setPaperSize($paperSize) { - $this->paperSize = $pValue; + $this->paperSize = $paperSize; return $this; } /** * Get Orientation. - * - * @return string */ - public function getOrientation() + public function getOrientation(): ?string { return $this->orientation; } @@ -196,13 +187,13 @@ public function getOrientation() /** * Set Orientation. * - * @param string $pValue Page orientation see PageSetup::ORIENTATION_* + * @param string $orientation Page orientation see PageSetup::ORIENTATION_* * * @return self */ - public function setOrientation($pValue) + public function setOrientation($orientation) { - $this->orientation = $pValue; + $this->orientation = $orientation; return $this; } @@ -220,18 +211,16 @@ public function getTempDir() /** * Set temporary storage directory. * - * @param string $pValue Temporary storage directory - * - * @throws WriterException when directory does not exist + * @param string $temporaryDirectory Temporary storage directory * * @return self */ - public function setTempDir($pValue) + public function setTempDir($temporaryDirectory) { - if (is_dir($pValue)) { - $this->tempDir = $pValue; + if (is_dir($temporaryDirectory)) { + $this->tempDir = $temporaryDirectory; } else { - throw new WriterException("Directory does not exist: $pValue"); + throw new WriterException("Directory does not exist: $temporaryDirectory"); } return $this; @@ -240,44 +229,23 @@ public function setTempDir($pValue) /** * Save Spreadsheet to PDF file, pre-save. * - * @param string $pFilename Name of the file to save as - * - * @throws WriterException + * @param string $filename Name of the file to save as * * @return resource */ - protected function prepareForSave($pFilename) + protected function prepareForSave($filename) { - // garbage collect - $this->spreadsheet->garbageCollect(); - - $this->saveArrayReturnType = Calculation::getArrayReturnType(); - Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); - // Open file - $fileHandle = fopen($pFilename, 'w'); - if ($fileHandle === false) { - throw new WriterException("Could not open file $pFilename for writing."); - } + $this->openFileHandle($filename); - // Set PDF - $this->isPdf = true; - // Build CSS - $this->buildCSS(true); - - return $fileHandle; + return $this->fileHandle; } /** * Save PhpSpreadsheet to PDF file, post-save. - * - * @param resource $fileHandle */ - protected function restoreStateAfterSave($fileHandle) + protected function restoreStateAfterSave(): void { - // Close file - fclose($fileHandle); - - Calculation::setArrayReturnType($this->saveArrayReturnType); + $this->maybeCloseFileHandle(); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php index 3c3044d7..fc96f904 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Dompdf.php @@ -20,59 +20,34 @@ protected function createExternalWriterInstance() /** * Save Spreadsheet to file. * - * @param string $pFilename Name of the file to save as - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception + * @param string $filename Name of the file to save as */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { - $fileHandle = parent::prepareForSave($pFilename); + $fileHandle = parent::prepareForSave($filename); // Default PDF paper size $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) // Check for paper size and page orientation - if ($this->getSheetIndex() === null) { - $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize(); - } else { - $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); - } + $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); + $orientation = $this->getOrientation() ?? $setup->getOrientation(); + $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); + $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); $orientation = ($orientation == 'L') ? 'landscape' : 'portrait'; - // Override Page Orientation - if ($this->getOrientation() !== null) { - $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT) - ? PageSetup::ORIENTATION_PORTRAIT - : $this->getOrientation(); - } - // Override Paper Size - if ($this->getPaperSize() !== null) { - $printPaperSize = $this->getPaperSize(); - } - - if (isset(self::$paperSizes[$printPaperSize])) { - $paperSize = self::$paperSizes[$printPaperSize]; - } - // Create PDF $pdf = $this->createExternalWriterInstance(); - $pdf->setPaper(strtolower($paperSize), $orientation); + $pdf->setPaper($paperSize, $orientation); - $pdf->loadHtml( - $this->generateHTMLHeader(false) . - $this->generateSheetData() . - $this->generateHTMLFooter() - ); + $pdf->loadHtml($this->generateHTMLAll()); $pdf->render(); // Write to file - fwrite($fileHandle, $pdf->output()); + fwrite($fileHandle, $pdf->output() ?? ''); - parent::restoreStateAfterSave($fileHandle); + parent::restoreStateAfterSave(); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php index fd2664a8..281e1a4f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Mpdf.php @@ -2,8 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; -use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; +use PhpOffice\PhpSpreadsheet\Writer\Html; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Mpdf extends Pdf @@ -23,52 +23,24 @@ protected function createExternalWriterInstance($config) /** * Save Spreadsheet to file. * - * @param string $pFilename Name of the file to save as - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * @throws PhpSpreadsheetException + * @param string $filename Name of the file to save as */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { - $fileHandle = parent::prepareForSave($pFilename); - - // Default PDF paper size - $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + $fileHandle = parent::prepareForSave($filename); // Check for paper size and page orientation - if (null === $this->getSheetIndex()) { - $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize(); - } else { - $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); - } - $this->setOrientation($orientation); - - // Override Page Orientation - if (null !== $this->getOrientation()) { - $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT) - ? PageSetup::ORIENTATION_PORTRAIT - : $this->getOrientation(); - } - $orientation = strtoupper($orientation); - - // Override Paper Size - if (null !== $this->getPaperSize()) { - $printPaperSize = $this->getPaperSize(); - } - - if (isset(self::$paperSizes[$printPaperSize])) { - $paperSize = self::$paperSizes[$printPaperSize]; - } + $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); + $orientation = $this->getOrientation() ?? $setup->getOrientation(); + $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); + $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); // Create PDF - $config = ['tempDir' => $this->tempDir]; + $config = ['tempDir' => $this->tempDir . '/mpdf']; $pdf = $this->createExternalWriterInstance($config); $ortmp = $orientation; - $pdf->_setPageSize(strtoupper($paperSize), $ortmp); + $pdf->_setPageSize($paperSize, $ortmp); $pdf->DefOrientation = $orientation; $pdf->AddPageByArray([ 'orientation' => $orientation, @@ -85,17 +57,23 @@ public function save($pFilename) $pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords()); $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); - $pdf->WriteHTML($this->generateHTMLHeader(false)); - $html = $this->generateSheetData(); + $html = $this->generateHTMLAll(); + $bodyLocation = strpos($html, Html::BODY_LINE); + // Make sure first data presented to Mpdf includes body tag + // so that Mpdf doesn't parse it as content. Issue 2432. + if ($bodyLocation !== false) { + $bodyLocation += strlen(Html::BODY_LINE); + $pdf->WriteHTML(substr($html, 0, $bodyLocation)); + $html = substr($html, $bodyLocation); + } foreach (\array_chunk(\explode(PHP_EOL, $html), 1000) as $lines) { $pdf->WriteHTML(\implode(PHP_EOL, $lines)); } - $pdf->WriteHTML($this->generateHTMLFooter()); // Write to file fwrite($fileHandle, $pdf->Output('', 'S')); - parent::restoreStateAfterSave($fileHandle); + parent::restoreStateAfterSave(); } /** diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php index 8a97b8fe..d29d4764 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php @@ -2,17 +2,29 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Pdf; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Writer\Pdf; class Tcpdf extends Pdf { + /** + * Create a new PDF Writer instance. + * + * @param Spreadsheet $spreadsheet Spreadsheet object + */ + public function __construct(Spreadsheet $spreadsheet) + { + parent::__construct($spreadsheet); + $this->setUseInlineCss(true); + } + /** * Gets the implementation of external PDF library that should be used. * * @param string $orientation Page orientation * @param string $unit Unit measure - * @param string $paperSize Paper size + * @param array|string $paperSize Paper size * * @return \TCPDF implementation */ @@ -24,44 +36,22 @@ protected function createExternalWriterInstance($orientation, $unit, $paperSize) /** * Save Spreadsheet to file. * - * @param string $pFilename Name of the file to save as - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception + * @param string $filename Name of the file to save as */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { - $fileHandle = parent::prepareForSave($pFilename); + $fileHandle = parent::prepareForSave($filename); // Default PDF paper size $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) // Check for paper size and page orientation - if ($this->getSheetIndex() === null) { - $orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize(); - $printMargins = $this->spreadsheet->getSheet(0)->getPageMargins(); - } else { - $orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() - == PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; - $printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); - $printMargins = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageMargins(); - } - - // Override Page Orientation - if ($this->getOrientation() !== null) { - $orientation = ($this->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) - ? 'L' - : 'P'; - } - // Override Paper Size - if ($this->getPaperSize() !== null) { - $printPaperSize = $this->getPaperSize(); - } - - if (isset(self::$paperSizes[$printPaperSize])) { - $paperSize = self::$paperSizes[$printPaperSize]; - } + $setup = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageSetup(); + $orientation = $this->getOrientation() ?? $setup->getOrientation(); + $orientation = ($orientation === PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->getPaperSize() ?? $setup->getPaperSize(); + $paperSize = self::$paperSizes[$printPaperSize] ?? PageSetup::getPaperSizeDefault(); + $printMargins = $this->spreadsheet->getSheet($this->getSheetIndex() ?? 0)->getPageMargins(); // Create PDF $pdf = $this->createExternalWriterInstance($orientation, 'pt', $paperSize); @@ -77,11 +67,7 @@ public function save($pFilename) // Set the appropriate font $pdf->SetFont($this->getFont()); - $pdf->writeHTML( - $this->generateHTMLHeader(false) . - $this->generateSheetData() . - $this->generateHTMLFooter() - ); + $pdf->writeHTML($this->generateHTMLAll()); // Document info $pdf->SetTitle($this->spreadsheet->getProperties()->getTitle()); @@ -91,8 +77,8 @@ public function save($pFilename) $pdf->SetCreator($this->spreadsheet->getProperties()->getCreator()); // Write to file - fwrite($fileHandle, $pdf->output($pFilename, 'S')); + fwrite($fileHandle, $pdf->output($filename, 'S')); - parent::restoreStateAfterSave($fileHandle); + parent::restoreStateAfterSave(); } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php index 6932eb1a..b91e3859 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls.php @@ -23,7 +23,9 @@ use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; -use RuntimeException; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Parser; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet; class Xls extends BaseWriter { @@ -65,7 +67,7 @@ class Xls extends BaseWriter /** * Formula parser. * - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Parser + * @var Parser */ private $parser; @@ -79,24 +81,24 @@ class Xls extends BaseWriter /** * Basic OLE object summary information. * - * @var array + * @var string */ private $summaryInformation; /** * Extended OLE object document summary information. * - * @var array + * @var string */ private $documentSummaryInformation; /** - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook + * @var Workbook */ private $writerWorkbook; /** - * @var \PhpOffice\PhpSpreadsheet\Writer\Xls\Worksheet[] + * @var Worksheet[] */ private $writerWorksheets; @@ -109,18 +111,18 @@ public function __construct(Spreadsheet $spreadsheet) { $this->spreadsheet = $spreadsheet; - $this->parser = new Xls\Parser(); + $this->parser = new Xls\Parser($spreadsheet); } /** * Save Spreadsheet to file. * - * @param string $pFilename - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception + * @param resource|string $filename */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { + $this->processFlags($flags); + // garbage collect $this->spreadsheet->garbageCollect(); @@ -219,9 +221,12 @@ public function save($pFilename) $arrRootData[] = $OLE_DocumentSummaryInformation; } - $root = new Root(time(), time(), $arrRootData); + $time = $this->spreadsheet->getProperties()->getModified(); + $root = new Root($time, $time, $arrRootData); // save the OLE file - $root->save($pFilename); + $this->openFileHandle($filename); + $root->save($this->fileHandle); + $this->maybeCloseFileHandle(); Functions::setReturnDateType($saveDateReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); @@ -230,7 +235,7 @@ public function save($pFilename) /** * Build the Worksheet Escher objects. */ - private function buildWorksheetEschers() + private function buildWorksheetEschers(): void { // 1-based index to BstoreContainer $blipIndex = 0; @@ -241,8 +246,6 @@ private function buildWorksheetEschers() // sheet index $sheetIndex = $sheet->getParent()->getIndex($sheet); - $escher = null; - // check if there are any shapes for this sheet $filterRange = $sheet->getAutoFilter()->getRange(); if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) { @@ -389,13 +392,97 @@ private function buildWorksheetEschers() } } - /** - * Build the Escher object corresponding to the MSODRAWINGGROUP record. - */ - private function buildWorkbookEscher() + private function processMemoryDrawing(BstoreContainer &$bstoreContainer, MemoryDrawing $drawing, string $renderingFunctionx): void { - $escher = null; + switch ($renderingFunctionx) { + case MemoryDrawing::RENDERING_JPEG: + $blipType = BSE::BLIPTYPE_JPEG; + $renderingFunction = 'imagejpeg'; + + break; + default: + $blipType = BSE::BLIPTYPE_PNG; + $renderingFunction = 'imagepng'; + + break; + } + + ob_start(); + call_user_func($renderingFunction, $drawing->getImageResource()); + $blipData = ob_get_contents(); + ob_end_clean(); + + $blip = new Blip(); + $blip->setData($blipData); + + $BSE = new BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + } + + private function processDrawing(BstoreContainer &$bstoreContainer, Drawing $drawing): void + { + $blipType = null; + $blipData = ''; + $filename = $drawing->getPath(); + + [$imagesx, $imagesy, $imageFormat] = getimagesize($filename); + + switch ($imageFormat) { + case 1: // GIF, not supported by BIFF8, we convert to PNG + $blipType = BSE::BLIPTYPE_PNG; + ob_start(); + // @phpstan-ignore-next-line + imagepng(imagecreatefromgif($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + + break; + case 2: // JPEG + $blipType = BSE::BLIPTYPE_JPEG; + $blipData = file_get_contents($filename); + + break; + case 3: // PNG + $blipType = BSE::BLIPTYPE_PNG; + $blipData = file_get_contents($filename); + + break; + case 6: // Windows DIB (BMP), we convert to PNG + $blipType = BSE::BLIPTYPE_PNG; + ob_start(); + // @phpstan-ignore-next-line + imagepng(SharedDrawing::imagecreatefrombmp($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + + break; + } + if ($blipData) { + $blip = new Blip(); + $blip->setData($blipData); + + $BSE = new BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + } + } + private function processBaseDrawing(BstoreContainer &$bstoreContainer, BaseDrawing $drawing): void + { + if ($drawing instanceof Drawing) { + $this->processDrawing($bstoreContainer, $drawing); + } elseif ($drawing instanceof MemoryDrawing) { + $this->processMemoryDrawing($bstoreContainer, $drawing, $drawing->getRenderingFunction()); + } + } + + private function checkForDrawings(): bool + { // any drawings in this workbook? $found = false; foreach ($this->spreadsheet->getAllSheets() as $sheet) { @@ -406,8 +493,16 @@ private function buildWorkbookEscher() } } + return $found; + } + + /** + * Build the Escher object corresponding to the MSODRAWINGGROUP record. + */ + private function buildWorkbookEscher(): void + { // nothing to do if there are no drawings - if (!$found) { + if (!$this->checkForDrawings()) { return; } @@ -429,17 +524,16 @@ private function buildWorkbookEscher() foreach ($this->spreadsheet->getAllsheets() as $sheet) { $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet - if (count($sheet->getDrawingCollection()) > 0) { - ++$countDrawings; - - foreach ($sheet->getDrawingCollection() as $drawing) { - ++$sheetCountShapes; - ++$totalCountShapes; + $addCount = 0; + foreach ($sheet->getDrawingCollection() as $drawing) { + $addCount = 1; + ++$sheetCountShapes; + ++$totalCountShapes; - $spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10; - $spIdMax = max($spId, $spIdMax); - } + $spId = $sheetCountShapes | ($this->spreadsheet->getIndex($sheet) + 1) << 10; + $spIdMax = max($spId, $spIdMax); } + $countDrawings += $addCount; } $dggContainer->setSpIdMax($spIdMax + 1); @@ -453,83 +547,7 @@ private function buildWorkbookEscher() // the BSE's (all the images) foreach ($this->spreadsheet->getAllsheets() as $sheet) { foreach ($sheet->getDrawingCollection() as $drawing) { - if (!extension_loaded('gd')) { - throw new RuntimeException('Saving images in xls requires gd extension'); - } - if ($drawing instanceof Drawing) { - $filename = $drawing->getPath(); - - [$imagesx, $imagesy, $imageFormat] = getimagesize($filename); - - switch ($imageFormat) { - case 1: // GIF, not supported by BIFF8, we convert to PNG - $blipType = BSE::BLIPTYPE_PNG; - ob_start(); - imagepng(imagecreatefromgif($filename)); - $blipData = ob_get_contents(); - ob_end_clean(); - - break; - case 2: // JPEG - $blipType = BSE::BLIPTYPE_JPEG; - $blipData = file_get_contents($filename); - - break; - case 3: // PNG - $blipType = BSE::BLIPTYPE_PNG; - $blipData = file_get_contents($filename); - - break; - case 6: // Windows DIB (BMP), we convert to PNG - $blipType = BSE::BLIPTYPE_PNG; - ob_start(); - imagepng(SharedDrawing::imagecreatefrombmp($filename)); - $blipData = ob_get_contents(); - ob_end_clean(); - - break; - default: - continue 2; - } - - $blip = new Blip(); - $blip->setData($blipData); - - $BSE = new BSE(); - $BSE->setBlipType($blipType); - $BSE->setBlip($blip); - - $bstoreContainer->addBSE($BSE); - } elseif ($drawing instanceof MemoryDrawing) { - switch ($drawing->getRenderingFunction()) { - case MemoryDrawing::RENDERING_JPEG: - $blipType = BSE::BLIPTYPE_JPEG; - $renderingFunction = 'imagejpeg'; - - break; - case MemoryDrawing::RENDERING_GIF: - case MemoryDrawing::RENDERING_PNG: - case MemoryDrawing::RENDERING_DEFAULT: - $blipType = BSE::BLIPTYPE_PNG; - $renderingFunction = 'imagepng'; - - break; - } - - ob_start(); - call_user_func($renderingFunction, $drawing->getImageResource()); - $blipData = ob_get_contents(); - ob_end_clean(); - - $blip = new Blip(); - $blip->setData($blipData); - - $BSE = new BSE(); - $BSE->setBlipType($blipType); - $BSE->setBlip($blip); - - $bstoreContainer->addBSE($BSE); - } + $this->processBaseDrawing($bstoreContainer, $drawing); } } @@ -578,8 +596,8 @@ private function writeDocumentSummaryInformation() ++$dataSection_NumProps; // GKPIDDSI_CATEGORY : Category - if ($this->spreadsheet->getProperties()->getCategory()) { - $dataProp = $this->spreadsheet->getProperties()->getCategory(); + $dataProp = $this->spreadsheet->getProperties()->getCategory(); + if ($dataProp) { $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x02], 'offset' => ['pack' => 'V'], @@ -707,16 +725,13 @@ private function writeDocumentSummaryInformation() $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x0B) { // Boolean - if ($dataProp['data']['data'] == false) { - $dataSection_Content .= pack('V', 0x0000); - } else { - $dataSection_Content .= pack('V', 0x0001); - } + $dataSection_Content .= pack('V', (int) $dataProp['data']['data']); $dataSection_Content_Offset += 4 + 4; } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); - $dataProp['data']['length'] += 1; + // @phpstan-ignore-next-line + ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); @@ -725,14 +740,15 @@ private function writeDocumentSummaryInformation() $dataSection_Content .= $dataProp['data']['data']; $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); - } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) - $dataSection_Content .= $dataProp['data']['data']; + // Condition below can never be true + //} elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + // $dataSection_Content .= $dataProp['data']['data']; - $dataSection_Content_Offset += 4 + 8; + // $dataSection_Content_Offset += 4 + 8; } else { - // Data Type Not Used at the moment $dataSection_Content .= $dataProp['data']['data']; + // @phpstan-ignore-next-line $dataSection_Content_Offset += 4 + $dataProp['data']['length']; } } @@ -752,6 +768,35 @@ private function writeDocumentSummaryInformation() return $data; } + /** + * @param float|int $dataProp + */ + private function writeSummaryPropOle($dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void + { + if ($dataProp) { + $dataSection[] = [ + 'summary' => ['pack' => 'V', 'data' => $sumdata], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length + 'data' => ['data' => OLE::localDateToOLE($dataProp)], + ]; + ++$dataSection_NumProps; + } + } + + private function writeSummaryProp(string $dataProp, int &$dataSection_NumProps, array &$dataSection, int $sumdata, int $typdata): void + { + if ($dataProp) { + $dataSection[] = [ + 'summary' => ['pack' => 'V', 'data' => $sumdata], + 'offset' => ['pack' => 'V'], + 'type' => ['pack' => 'V', 'data' => $typdata], // null-terminated string prepended by dword string length + 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], + ]; + ++$dataSection_NumProps; + } + } + /** * Build the OLE Part for Summary Information. * @@ -792,94 +837,16 @@ private function writeSummaryInformation() ]; ++$dataSection_NumProps; - // Title - if ($this->spreadsheet->getProperties()->getTitle()) { - $dataProp = $this->spreadsheet->getProperties()->getTitle(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x02], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Subject - if ($this->spreadsheet->getProperties()->getSubject()) { - $dataProp = $this->spreadsheet->getProperties()->getSubject(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x03], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Author (Creator) - if ($this->spreadsheet->getProperties()->getCreator()) { - $dataProp = $this->spreadsheet->getProperties()->getCreator(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x04], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Keywords - if ($this->spreadsheet->getProperties()->getKeywords()) { - $dataProp = $this->spreadsheet->getProperties()->getKeywords(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x05], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Comments (Description) - if ($this->spreadsheet->getProperties()->getDescription()) { - $dataProp = $this->spreadsheet->getProperties()->getDescription(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x06], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Last Saved By (LastModifiedBy) - if ($this->spreadsheet->getProperties()->getLastModifiedBy()) { - $dataProp = $this->spreadsheet->getProperties()->getLastModifiedBy(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x08], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x1E], // null-terminated string prepended by dword string length - 'data' => ['data' => $dataProp, 'length' => strlen($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Created Date/Time - if ($this->spreadsheet->getProperties()->getCreated()) { - $dataProp = $this->spreadsheet->getProperties()->getCreated(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x0C], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x40], // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) - 'data' => ['data' => OLE::localDateToOLE($dataProp)], - ]; - ++$dataSection_NumProps; - } - // Modified Date/Time - if ($this->spreadsheet->getProperties()->getModified()) { - $dataProp = $this->spreadsheet->getProperties()->getModified(); - $dataSection[] = [ - 'summary' => ['pack' => 'V', 'data' => 0x0D], - 'offset' => ['pack' => 'V'], - 'type' => ['pack' => 'V', 'data' => 0x40], // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) - 'data' => ['data' => OLE::localDateToOLE($dataProp)], - ]; - ++$dataSection_NumProps; - } + $props = $this->spreadsheet->getProperties(); + $this->writeSummaryProp($props->getTitle(), $dataSection_NumProps, $dataSection, 0x02, 0x1e); + $this->writeSummaryProp($props->getSubject(), $dataSection_NumProps, $dataSection, 0x03, 0x1e); + $this->writeSummaryProp($props->getCreator(), $dataSection_NumProps, $dataSection, 0x04, 0x1e); + $this->writeSummaryProp($props->getKeywords(), $dataSection_NumProps, $dataSection, 0x05, 0x1e); + $this->writeSummaryProp($props->getDescription(), $dataSection_NumProps, $dataSection, 0x06, 0x1e); + $this->writeSummaryProp($props->getLastModifiedBy(), $dataSection_NumProps, $dataSection, 0x08, 0x1e); + $this->writeSummaryPropOle($props->getCreated(), $dataSection_NumProps, $dataSection, 0x0c, 0x40); + $this->writeSummaryPropOle($props->getModified(), $dataSection_NumProps, $dataSection, 0x0d, 0x40); + // Security $dataSection[] = [ 'summary' => ['pack' => 'V', 'data' => 0x13], @@ -912,7 +879,7 @@ private function writeSummaryInformation() } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length // Null-terminated string $dataProp['data']['data'] .= chr(0); - $dataProp['data']['length'] += 1; + ++$dataProp['data']['length']; // Complete the string with null string for being a %4 $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4) == 4 ? 0 : (4 - $dataProp['data']['length'] % 4)); $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php index 3b2eb9af..4a7e0656 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/BIFFwriter.php @@ -49,7 +49,7 @@ class BIFFwriter /** * The string containing the data of the BIFF stream. * - * @var string + * @var null|string */ public $_data; @@ -109,7 +109,7 @@ public static function getByteOrder() * * @param string $data binary data to append */ - protected function append($data) + protected function append($data): void { if (strlen($data) - 4 > $this->limit) { $data = $this->addContinue($data); @@ -142,7 +142,7 @@ public function writeData($data) * @param int $type type of BIFF file to write: 0x0005 Workbook, * 0x0010 Worksheet */ - protected function storeBof($type) + protected function storeBof($type): void { $record = 0x0809; // Record identifier (BIFF5-BIFF8) $length = 0x0010; @@ -163,7 +163,7 @@ protected function storeBof($type) /** * Writes Excel EOF record to indicate the end of a BIFF stream. */ - protected function storeEof() + protected function storeEof(): void { $record = 0x000A; // Record identifier $length = 0x0000; // Number of bytes to follow diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php new file mode 100644 index 00000000..7e9b3cfa --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/CellDataValidation.php @@ -0,0 +1,78 @@ + + */ + protected static $validationTypeMap = [ + DataValidation::TYPE_NONE => 0x00, + DataValidation::TYPE_WHOLE => 0x01, + DataValidation::TYPE_DECIMAL => 0x02, + DataValidation::TYPE_LIST => 0x03, + DataValidation::TYPE_DATE => 0x04, + DataValidation::TYPE_TIME => 0x05, + DataValidation::TYPE_TEXTLENGTH => 0x06, + DataValidation::TYPE_CUSTOM => 0x07, + ]; + + /** + * @var array + */ + protected static $errorStyleMap = [ + DataValidation::STYLE_STOP => 0x00, + DataValidation::STYLE_WARNING => 0x01, + DataValidation::STYLE_INFORMATION => 0x02, + ]; + + /** + * @var array + */ + protected static $operatorMap = [ + DataValidation::OPERATOR_BETWEEN => 0x00, + DataValidation::OPERATOR_NOTBETWEEN => 0x01, + DataValidation::OPERATOR_EQUAL => 0x02, + DataValidation::OPERATOR_NOTEQUAL => 0x03, + DataValidation::OPERATOR_GREATERTHAN => 0x04, + DataValidation::OPERATOR_LESSTHAN => 0x05, + DataValidation::OPERATOR_GREATERTHANOREQUAL => 0x06, + DataValidation::OPERATOR_LESSTHANOREQUAL => 0x07, + ]; + + public static function type(DataValidation $dataValidation): int + { + $validationType = $dataValidation->getType(); + + if (is_string($validationType) && array_key_exists($validationType, self::$validationTypeMap)) { + return self::$validationTypeMap[$validationType]; + } + + return self::$validationTypeMap[DataValidation::TYPE_NONE]; + } + + public static function errorStyle(DataValidation $dataValidation): int + { + $errorStyle = $dataValidation->getErrorStyle(); + + if (is_string($errorStyle) && array_key_exists($errorStyle, self::$errorStyleMap)) { + return self::$errorStyleMap[$errorStyle]; + } + + return self::$errorStyleMap[DataValidation::STYLE_STOP]; + } + + public static function operator(DataValidation $dataValidation): int + { + $operator = $dataValidation->getOperator(); + + if (is_string($operator) && array_key_exists($operator, self::$operatorMap)) { + return self::$operatorMap[$operator]; + } + + return self::$operatorMap[DataValidation::OPERATOR_BETWEEN]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php new file mode 100644 index 00000000..0f78b8c5 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ConditionalHelper.php @@ -0,0 +1,76 @@ +parser = $parser; + } + + /** + * @param mixed $condition + */ + public function processCondition($condition, string $cellRange): void + { + $this->condition = $condition; + $this->cellRange = $cellRange; + + if (is_int($condition) || is_float($condition)) { + $this->size = ($condition <= 65535 ? 3 : 0x0000); + $this->tokens = pack('Cv', 0x1E, $condition); + } else { + try { + $formula = Wizard\WizardAbstract::reverseAdjustCellRef((string) $condition, $cellRange); + $this->parser->parse($formula); + $this->tokens = $this->parser->toReversePolish(); + $this->size = strlen($this->tokens ?? ''); + } catch (PhpSpreadsheetException $e) { + // In the event of a parser error with a formula value, we set the expression to ptgInt + 0 + $this->tokens = pack('Cv', 0x1E, 0); + $this->size = 3; + } + } + } + + public function tokens(): ?string + { + return $this->tokens; + } + + public function size(): int + { + return $this->size; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php new file mode 100644 index 00000000..7a864f50 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/ErrorCode.php @@ -0,0 +1,28 @@ + + */ + protected static $errorCodeMap = [ + '#NULL!' => 0x00, + '#DIV/0!' => 0x07, + '#VALUE!' => 0x0F, + '#REF!' => 0x17, + '#NAME?' => 0x1D, + '#NUM!' => 0x24, + '#N/A' => 0x2A, + ]; + + public static function error(string $errorCode): int + { + if (array_key_exists($errorCode, self::$errorCodeMap)) { + return self::$errorCodeMap[$errorCode]; + } + + return 0; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php index 1ee2e904..e42139b3 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Escher.php @@ -420,8 +420,8 @@ public function close() $recType = 0xF010; // start coordinates - [$column, $row] = Coordinate::coordinateFromString($this->object->getStartCoordinates()); - $c1 = Coordinate::columnIndexFromString($column) - 1; + [$column, $row] = Coordinate::indexesFromString($this->object->getStartCoordinates()); + $c1 = $column - 1; $r1 = $row - 1; // start offsetX @@ -431,8 +431,8 @@ public function close() $startOffsetY = $this->object->getStartOffsetY(); // end coordinates - [$column, $row] = Coordinate::coordinateFromString($this->object->getEndCoordinates()); - $c2 = Coordinate::columnIndexFromString($column) - 1; + [$column, $row] = Coordinate::indexesFromString($this->object->getEndCoordinates()); + $c2 = $column - 1; $r2 = $row - 1; // end offsetX diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php index df37dcb5..1266cf24 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Font.php @@ -22,8 +22,6 @@ class Font /** * Constructor. - * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font */ public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font) { @@ -36,7 +34,7 @@ public function __construct(\PhpOffice\PhpSpreadsheet\Style\Font $font) * * @param int $colorIndex */ - public function setColorIndex($colorIndex) + public function setColorIndex($colorIndex): void { $this->colorIndex = $colorIndex; } @@ -121,7 +119,7 @@ private static function mapBold($bold) /** * Map of BIFF2-BIFF8 codes for underline styles. * - * @var array of int + * @var int[] */ private static $mapUnderline = [ \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE => 0x00, diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php index 59820628..4033fd53 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Parser.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; +use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; +use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; @@ -78,7 +80,7 @@ class Parser * * @var string */ - private $parseTree; + public $parseTree; /** * Array of external sheets. @@ -467,11 +469,15 @@ class Parser 'BAHTTEXT' => [368, 1, 0, 0], ]; + private $spreadsheet; + /** * The class constructor. */ - public function __construct() + public function __construct(Spreadsheet $spreadsheet) { + $this->spreadsheet = $spreadsheet; + $this->currentCharacter = 0; $this->currentToken = ''; // The token we are working on. $this->formula = ''; // The formula to parse. @@ -516,14 +522,16 @@ private function convert($token) } elseif (isset($this->ptg[$token])) { return pack('C', $this->ptg[$token]); // match error codes - } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) or $token == '#N/A') { + } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') { return $this->convertError($token); + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) { + return $this->convertDefinedName($token); // commented so argument number can be processed correctly. See toReversePolish(). - /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) - { - return($this->convertFunction($token, $this->_func_args)); - }*/ - // if it's an argument, ignore the token (the argument remains) + /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) + { + return($this->convertFunction($token, $this->_func_args)); + }*/ + // if it's an argument, ignore the token (the argument remains) } elseif ($token == 'arg') { return ''; } @@ -542,7 +550,7 @@ private function convert($token) private function convertNumber($num) { // Integer in the range 0..2**16-1 - if ((preg_match('/^\\d+$/', $num)) and ($num <= 65535)) { + if ((preg_match('/^\\d+$/', $num)) && ($num <= 65535)) { return pack('Cv', $this->ptg['ptgInt'], $num); } @@ -589,10 +597,9 @@ private function convertFunction($token, $num_args) if ($args >= 0) { return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]); } + // Variable number of args eg. SUM($i, $j, $k, ..). - if ($args == -1) { - return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); - } + return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); } /** @@ -739,6 +746,27 @@ private function convertError($errorCode) return pack('C', 0xFF); } + private function convertDefinedName(string $name): string + { + if (strlen($name) > 255) { + throw new WriterException('Defined Name is too long'); + } + + $nameReference = 1; + foreach ($this->spreadsheet->getDefinedNames() as $definedName) { + if ($name === $definedName->getName()) { + break; + } + ++$nameReference; + } + + $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference); + + throw new WriterException('Cannot yet write formulae with defined names to Xls'); + + return $ptgRef; + } + /** * Look up the REF index that corresponds to an external sheet name * (or range). If it doesn't exist yet add it to the workbook's references @@ -823,12 +851,12 @@ private function getSheetIndex($sheet_name) * called by the addWorksheet() method of the * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class. * - * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet() - * * @param string $name The name of the worksheet being added * @param int $index The index of the worksheet being added + * + * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet() */ - public function setExtSheet($name, $index) + public function setExtSheet($name, $index): void { $this->externalSheets[$name] = $index; } @@ -885,7 +913,7 @@ private function rangeToPackedRange($range) $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!) // FIXME: this changes for BIFF8 - if (($row1 >= 65536) or ($row2 >= 65536)) { + if (($row1 >= 65536) || ($row2 >= 65536)) { throw new WriterException("Row in: $range greater than 65536 "); } @@ -924,7 +952,7 @@ private function cellToRowcol($cell) $col = 0; $col_ref_length = strlen($col_ref); for ($i = 0; $i < $col_ref_length; ++$i) { - $col += (ord($col_ref[$i]) - 64) * pow(26, $expn); + $col += (ord($col_ref[$i]) - 64) * 26 ** $expn; --$expn; } @@ -940,6 +968,7 @@ private function cellToRowcol($cell) */ private function advance() { + $token = ''; $i = $this->currentCharacter; $formula_length = strlen($this->formula); // eat up white spaces @@ -1018,7 +1047,7 @@ private function match($token) break; case '<': // it's a LE or a NE token - if (($this->lookAhead === '=') or ($this->lookAhead === '>')) { + if (($this->lookAhead === '=') || ($this->lookAhead === '>')) { break; } @@ -1027,35 +1056,37 @@ private function match($token) break; default: // if it's a reference A1 or $A$1 or $A1 or A$1 - if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token) and !preg_match('/\d/', $this->lookAhead) and ($this->lookAhead !== ':') and ($this->lookAhead !== '.') and ($this->lookAhead !== '!')) { + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.') && ($this->lookAhead !== '!')) { return $token; - } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token) and !preg_match('/\d/', $this->lookAhead) and ($this->lookAhead !== ':') and ($this->lookAhead !== '.')) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) return $token; - } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $token) and !preg_match('/\d/', $this->lookAhead) and ($this->lookAhead !== ':') and ($this->lookAhead !== '.')) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) { // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) return $token; } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead)) { // if it's a range A1:A2 or $A$1:$A$2 return $token; - } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $token) and !preg_match('/\d/', $this->lookAhead)) { + } elseif (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead)) { // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 return $token; - } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $token) and !preg_match('/\d/', $this->lookAhead)) { + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead)) { // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 return $token; - } elseif (is_numeric($token) and (!is_numeric($token . $this->lookAhead) or ($this->lookAhead == '')) and ($this->lookAhead !== '!') and ($this->lookAhead !== ':')) { + } elseif (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) { // If it's a number (check that it's not a sheet name or range) return $token; - } elseif (preg_match('/"([^"]|""){0,255}"/', $token) and $this->lookAhead !== '"' and (substr_count($token, '"') % 2 == 0)) { + } elseif (preg_match('/"([^"]|""){0,255}"/', $token) && $this->lookAhead !== '"' && (substr_count($token, '"') % 2 == 0)) { // If it's a string (of maximum 255 characters) return $token; - } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) or $token === '#N/A') { + } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token === '#N/A') { // If it's an error code return $token; - } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token) and ($this->lookAhead === '(')) { + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token) && ($this->lookAhead === '(')) { // if it's a function call return $token; + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token) && $this->spreadsheet->getDefinedName($token) !== null) { + return $token; } elseif (substr($token, -1) === ')') { // It's an argument of some description (e.g. a named range), // precise nature yet to be determined @@ -1118,10 +1149,6 @@ private function condition() $this->advance(); $result2 = $this->expression(); $result = $this->createTree('ptgNE', $result, $result2); - } elseif ($this->currentToken == '&') { - $this->advance(); - $result2 = $this->expression(); - $result = $this->createTree('ptgConcat', $result, $result2); } return $result; @@ -1151,7 +1178,7 @@ private function expression() return $result; // If it's an error code - } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken) or $this->currentToken == '#N/A') { + } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken) || $this->currentToken == '#N/A') { $result = $this->createTree($this->currentToken, 'ptgErr', ''); $this->advance(); @@ -1172,9 +1199,16 @@ private function expression() return $this->createTree('ptgUplus', $result2, ''); } $result = $this->term(); - while (($this->currentToken == '+') or - ($this->currentToken == '-') or - ($this->currentToken == '^')) { + while ($this->currentToken === '&') { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgConcat', $result, $result2); + } + while ( + ($this->currentToken == '+') || + ($this->currentToken == '-') || + ($this->currentToken == '^') + ) { if ($this->currentToken == '+') { $this->advance(); $result2 = $this->term(); @@ -1197,9 +1231,9 @@ private function expression() * This function just introduces a ptgParen element in the tree, so that Excel * doesn't get confused when working with a parenthesized formula afterwards. * - * @see fact() - * * @return array The parsed ptg'd tree + * + * @see fact() */ private function parenthesizedExpression() { @@ -1215,8 +1249,10 @@ private function parenthesizedExpression() private function term() { $result = $this->fact(); - while (($this->currentToken == '*') or - ($this->currentToken == '/')) { + while ( + ($this->currentToken == '*') || + ($this->currentToken == '/') + ) { if ($this->currentToken == '*') { $this->advance(); $result2 = $this->fact(); @@ -1250,6 +1286,7 @@ private function fact() throw new WriterException("')' token expected."); } $this->advance(); // eat the ")" + return $result; } // if it's a reference @@ -1270,8 +1307,10 @@ private function fact() $this->advance(); return $result; - } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) or - preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken)) { + } elseif ( + preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) || + preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) + ) { // if it's a range A1:B2 or $A$1:$B$2 // must be an error? $result = $this->createTree($this->currentToken, '', ''); @@ -1303,9 +1342,14 @@ private function fact() $this->advance(); return $result; - } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken)) { + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken) && ($this->lookAhead === '(')) { // if it's a function call return $this->func(); + } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $this->currentToken) && $this->spreadsheet->getDefinedName($this->currentToken) !== null) { + $result = $this->createTree('ptgName', $this->currentToken, ''); + $this->advance(); + + return $result; } throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter); @@ -1344,12 +1388,13 @@ private function func() } $args = $this->functions[$function][1]; // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid. - if (($args >= 0) and ($args != $num_args)) { + if (($args >= 0) && ($args != $num_args)) { throw new WriterException("Incorrect number of arguments in function $function() "); } $result = $this->createTree($function, $result, $num_args); $this->advance(); // eat the ")" + return $result; } @@ -1417,17 +1462,20 @@ public function toReversePolish($tree = []) $polish .= $converted_tree; } // if it's a function convert it here (so we can set it's arguments) - if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value']) and - !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) and - !preg_match('/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/', $tree['value']) and - !is_numeric($tree['value']) and - !isset($this->ptg[$tree['value']])) { + if ( + preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value']) && + !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) && + !preg_match('/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/', $tree['value']) && + !is_numeric($tree['value']) && + !isset($this->ptg[$tree['value']]) + ) { // left subtree for a function is always an array. if ($tree['left'] != '') { $left_tree = $this->toReversePolish($tree['left']); } else { $left_tree = ''; } + // add it's left subtree and return. return $left_tree . $this->convertFunction($tree['value'], $tree['right']); } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php new file mode 100644 index 00000000..711d88d2 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellAlignment.php @@ -0,0 +1,59 @@ + + */ + private static $horizontalMap = [ + Alignment::HORIZONTAL_GENERAL => 0, + Alignment::HORIZONTAL_LEFT => 1, + Alignment::HORIZONTAL_RIGHT => 3, + Alignment::HORIZONTAL_CENTER => 2, + Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, + Alignment::HORIZONTAL_JUSTIFY => 5, + ]; + + /** + * @var array + */ + private static $verticalMap = [ + Alignment::VERTICAL_BOTTOM => 2, + Alignment::VERTICAL_TOP => 0, + Alignment::VERTICAL_CENTER => 1, + Alignment::VERTICAL_JUSTIFY => 3, + ]; + + public static function horizontal(Alignment $alignment): int + { + $horizontalAlignment = $alignment->getHorizontal(); + + if (is_string($horizontalAlignment) && array_key_exists($horizontalAlignment, self::$horizontalMap)) { + return self::$horizontalMap[$horizontalAlignment]; + } + + return self::$horizontalMap[Alignment::HORIZONTAL_GENERAL]; + } + + public static function wrap(Alignment $alignment): int + { + $wrap = $alignment->getWrapText(); + + return ($wrap === true) ? 1 : 0; + } + + public static function vertical(Alignment $alignment): int + { + $verticalAlignment = $alignment->getVertical(); + + if (is_string($verticalAlignment) && array_key_exists($verticalAlignment, self::$verticalMap)) { + return self::$verticalMap[$verticalAlignment]; + } + + return self::$verticalMap[Alignment::VERTICAL_BOTTOM]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php new file mode 100644 index 00000000..8d47d6aa --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellBorder.php @@ -0,0 +1,39 @@ + + */ + protected static $styleMap = [ + Border::BORDER_NONE => 0x00, + Border::BORDER_THIN => 0x01, + Border::BORDER_MEDIUM => 0x02, + Border::BORDER_DASHED => 0x03, + Border::BORDER_DOTTED => 0x04, + Border::BORDER_THICK => 0x05, + Border::BORDER_DOUBLE => 0x06, + Border::BORDER_HAIR => 0x07, + Border::BORDER_MEDIUMDASHED => 0x08, + Border::BORDER_DASHDOT => 0x09, + Border::BORDER_MEDIUMDASHDOT => 0x0A, + Border::BORDER_DASHDOTDOT => 0x0B, + Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, + Border::BORDER_SLANTDASHDOT => 0x0D, + ]; + + public static function style(Border $border): int + { + $borderStyle = $border->getBorderStyle(); + + if (is_string($borderStyle) && array_key_exists($borderStyle, self::$styleMap)) { + return self::$styleMap[$borderStyle]; + } + + return self::$styleMap[Border::BORDER_NONE]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php new file mode 100644 index 00000000..f5a8c470 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/CellFill.php @@ -0,0 +1,46 @@ + + */ + protected static $fillStyleMap = [ + Fill::FILL_NONE => 0x00, + Fill::FILL_SOLID => 0x01, + Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, + Fill::FILL_PATTERN_DARKGRAY => 0x03, + Fill::FILL_PATTERN_LIGHTGRAY => 0x04, + Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, + Fill::FILL_PATTERN_DARKVERTICAL => 0x06, + Fill::FILL_PATTERN_DARKDOWN => 0x07, + Fill::FILL_PATTERN_DARKUP => 0x08, + Fill::FILL_PATTERN_DARKGRID => 0x09, + Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, + Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, + Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, + Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, + Fill::FILL_PATTERN_LIGHTUP => 0x0E, + Fill::FILL_PATTERN_LIGHTGRID => 0x0F, + Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, + Fill::FILL_PATTERN_GRAY125 => 0x11, + Fill::FILL_PATTERN_GRAY0625 => 0x12, + Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 + Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 + ]; + + public static function style(Fill $fill): int + { + $fillStyle = $fill->getFillType(); + + if (is_string($fillStyle) && array_key_exists($fillStyle, self::$fillStyleMap)) { + return self::$fillStyleMap[$fillStyle]; + } + + return self::$fillStyleMap[Fill::FILL_NONE]; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php new file mode 100644 index 00000000..caf85c04 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Style/ColorMap.php @@ -0,0 +1,90 @@ + + */ + private static $colorMap = [ + '#000000' => 0x08, + '#FFFFFF' => 0x09, + '#FF0000' => 0x0A, + '#00FF00' => 0x0B, + '#0000FF' => 0x0C, + '#FFFF00' => 0x0D, + '#FF00FF' => 0x0E, + '#00FFFF' => 0x0F, + '#800000' => 0x10, + '#008000' => 0x11, + '#000080' => 0x12, + '#808000' => 0x13, + '#800080' => 0x14, + '#008080' => 0x15, + '#C0C0C0' => 0x16, + '#808080' => 0x17, + '#9999FF' => 0x18, + '#993366' => 0x19, + '#FFFFCC' => 0x1A, + '#CCFFFF' => 0x1B, + '#660066' => 0x1C, + '#FF8080' => 0x1D, + '#0066CC' => 0x1E, + '#CCCCFF' => 0x1F, + // '#000080' => 0x20, + // '#FF00FF' => 0x21, + // '#FFFF00' => 0x22, + // '#00FFFF' => 0x23, + // '#800080' => 0x24, + // '#800000' => 0x25, + // '#008080' => 0x26, + // '#0000FF' => 0x27, + '#00CCFF' => 0x28, + // '#CCFFFF' => 0x29, + '#CCFFCC' => 0x2A, + '#FFFF99' => 0x2B, + '#99CCFF' => 0x2C, + '#FF99CC' => 0x2D, + '#CC99FF' => 0x2E, + '#FFCC99' => 0x2F, + '#3366FF' => 0x30, + '#33CCCC' => 0x31, + '#99CC00' => 0x32, + '#FFCC00' => 0x33, + '#FF9900' => 0x34, + '#FF6600' => 0x35, + '#666699' => 0x36, + '#969696' => 0x37, + '#003366' => 0x38, + '#339966' => 0x39, + '#003300' => 0x3A, + '#333300' => 0x3B, + '#993300' => 0x3C, + // '#993366' => 0x3D, + '#333399' => 0x3E, + '#333333' => 0x3F, + ]; + + public static function lookup(Color $color, int $defaultIndex = 0x00): int + { + $colorRgb = $color->getRGB(); + if (is_string($colorRgb) && array_key_exists("#{$colorRgb}", self::$colorMap)) { + return self::$colorMap["#{$colorRgb}"]; + } + +// TODO Try and map RGB value to nearest colour within the define pallette +// $red = Color::getRed($colorRgb, false); +// $green = Color::getGreen($colorRgb, false); +// $blue = Color::getBlue($colorRgb, false); + +// $paletteSpace = 3; +// $newColor = ($red * $paletteSpace / 256) * ($paletteSpace * $paletteSpace) + +// ($green * $paletteSpace / 256) * $paletteSpace + +// ($blue * $paletteSpace / 256); + + return $defaultIndex; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php index 41c8e64e..ccffa181 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Workbook.php @@ -2,7 +2,9 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; +use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; @@ -167,7 +169,7 @@ class Workbook extends BIFFwriter /** * Escher object corresponding to MSODRAWINGGROUP. * - * @var \PhpOffice\PhpSpreadsheet\Shared\Escher + * @var null|\PhpOffice\PhpSpreadsheet\Shared\Escher */ private $escher; @@ -222,7 +224,6 @@ public function __construct(Spreadsheet $spreadsheet, &$str_total, &$str_unique, /** * Add a new XF writer. * - * @param Style $style * @param bool $isStyleXf Is it a style XF? * * @return int Index to XF record @@ -273,8 +274,6 @@ public function addXfWriter(Style $style, $isStyleXf = false) /** * Add a font to added fonts. * - * @param \PhpOffice\PhpSpreadsheet\Style\Font $font - * * @return int Index to FONT record */ public function addFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) @@ -343,7 +342,7 @@ private function addColor($rgb) /** * Sets the colour palette to the Excel 97+ default. */ - private function setPaletteXl97() + private function setPaletteXl97(): void { $this->palette = [ 0x08 => [0x00, 0x00, 0x00, 0x00], @@ -409,13 +408,13 @@ private function setPaletteXl97() * Assemble worksheets into a workbook and send the BIFF data to an OLE * storage. * - * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams + * @param array $worksheetSizes The sizes in bytes of the binary worksheet streams * * @return string Binary data for workbook stream */ - public function writeWorkbook(array $pWorksheetSizes) + public function writeWorkbook(array $worksheetSizes) { - $this->worksheetSizes = $pWorksheetSizes; + $this->worksheetSizes = $worksheetSizes; // Calculate the number of selected worksheet tabs and call the finalization // methods for each worksheet @@ -465,7 +464,7 @@ public function writeWorkbook(array $pWorksheetSizes) /** * Calculate offsets for Worksheet BOF records. */ - private function calcSheetOffsets() + private function calcSheetOffsets(): void { $boundsheet_length = 10; // fixed length for a BOUNDSHEET record @@ -489,7 +488,7 @@ private function calcSheetOffsets() /** * Store the Excel FONT records. */ - private function writeAllFonts() + private function writeAllFonts(): void { foreach ($this->fontWriters as $fontWriter) { $this->append($fontWriter->writeFont()); @@ -499,7 +498,7 @@ private function writeAllFonts() /** * Store user defined numerical formats i.e. FORMAT records. */ - private function writeAllNumberFormats() + private function writeAllNumberFormats(): void { foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) { $this->writeNumberFormat($numberFormat->getFormatCode(), $numberFormatIndex); @@ -509,7 +508,7 @@ private function writeAllNumberFormats() /** * Write all XF records. */ - private function writeAllXfs() + private function writeAllXfs(): void { foreach ($this->xfWriters as $xfWriter) { $this->append($xfWriter->writeXf()); @@ -519,11 +518,62 @@ private function writeAllXfs() /** * Write all STYLE records. */ - private function writeAllStyles() + private function writeAllStyles(): void { $this->writeStyle(); } + private function parseDefinedNameValue(DefinedName $definedName): string + { + $definedRange = $definedName->getValue(); + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_CELLREF . '/mui', + $definedRange, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $lengths = array_map('strlen', array_column($splitRanges[0], 0)); + $offsets = array_column($splitRanges[0], 1); + + $worksheets = $splitRanges[2]; + $columns = $splitRanges[6]; + $rows = $splitRanges[7]; + + while ($splitCount > 0) { + --$splitCount; + $length = $lengths[$splitCount]; + $offset = $offsets[$splitCount]; + $worksheet = $worksheets[$splitCount][0]; + $column = $columns[$splitCount][0]; + $row = $rows[$splitCount][0]; + + $newRange = ''; + if (empty($worksheet)) { + if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { + // We should have a worksheet + $worksheet = $definedName->getWorksheet() ? $definedName->getWorksheet()->getTitle() : null; + } + } else { + $worksheet = str_replace("''", "'", trim($worksheet, "'")); + } + if (!empty($worksheet)) { + $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; + } + + if (!empty($column)) { + $newRange .= "\${$column}"; + } + if (!empty($row)) { + $newRange .= "\${$row}"; + } + + $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); + } + + return $definedRange; + } + /** * Writes all the DEFINEDNAME records (BIFF8). * So far this is only used for repeating rows/columns (print titles) and print areas. @@ -533,20 +583,11 @@ private function writeAllDefinedNamesBiff8() $chunk = ''; // Named ranges - if (count($this->spreadsheet->getNamedRanges()) > 0) { + $definedNames = $this->spreadsheet->getDefinedNames(); + if (count($definedNames) > 0) { // Loop named ranges - $namedRanges = $this->spreadsheet->getNamedRanges(); - foreach ($namedRanges as $namedRange) { - // Create absolute coordinate - $range = Coordinate::splitRange($namedRange->getRange()); - $iMax = count($range); - for ($i = 0; $i < $iMax; ++$i) { - $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . Coordinate::absoluteCoordinate($range[$i][0]); - if (isset($range[$i][1])) { - $range[$i][1] = Coordinate::absoluteCoordinate($range[$i][1]); - } - } - $range = Coordinate::buildRange($range); // e.g. Sheet1!$A$1:$B$2 + foreach ($definedNames as $definedName) { + $range = $this->parseDefinedNameValue($definedName); // parse formula try { @@ -554,18 +595,22 @@ private function writeAllDefinedNamesBiff8() $formulaData = $this->parser->toReversePolish(); // make sure tRef3d is of type tRef3dR (0x3A) - if (isset($formulaData[0]) and ($formulaData[0] == "\x7A" or $formulaData[0] == "\x5A")) { + if (isset($formulaData[0]) && ($formulaData[0] == "\x7A" || $formulaData[0] == "\x5A")) { $formulaData = "\x3A" . substr($formulaData, 1); } - if ($namedRange->getLocalOnly()) { - // local scope - $scope = $this->spreadsheet->getIndex($namedRange->getScope()) + 1; + if ($definedName->getLocalOnly()) { + /** + * local scope. + * + * @phpstan-ignore-next-line + */ + $scope = $this->spreadsheet->getIndex($definedName->getScope()) + 1; } else { // global scope $scope = 0; } - $chunk .= $this->writeData($this->writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false)); + $chunk .= $this->writeData($this->writeDefinedNameBiff8($definedName->getName(), $formulaData, $scope, false)); } catch (PhpSpreadsheetException $e) { // do nothing } @@ -637,13 +682,13 @@ private function writeAllDefinedNamesBiff8() $formulaData = ''; for ($j = 0; $j < $countPrintArea; ++$j) { $printAreaRect = $printArea[$j]; // e.g. A3:J6 - $printAreaRect[0] = Coordinate::coordinateFromString($printAreaRect[0]); - $printAreaRect[1] = Coordinate::coordinateFromString($printAreaRect[1]); + $printAreaRect[0] = Coordinate::indexesFromString($printAreaRect[0]); + $printAreaRect[1] = Coordinate::indexesFromString($printAreaRect[1]); $print_rowmin = $printAreaRect[0][1] - 1; $print_rowmax = $printAreaRect[1][1] - 1; - $print_colmin = Coordinate::columnIndexFromString($printAreaRect[0][0]) - 1; - $print_colmax = Coordinate::columnIndexFromString($printAreaRect[1][0]) - 1; + $print_colmin = $printAreaRect[0][0] - 1; + $print_colmax = $printAreaRect[1][0] - 1; // construct formula data manually because parser does not recognize absolute 3d cell references $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); @@ -715,8 +760,8 @@ private function writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $is * Write a short NAME record. * * @param string $name - * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global - * @param integer[][] $rangeBounds range boundaries + * @param int $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param int[][] $rangeBounds range boundaries * @param bool $isHidden * * @return string Complete binary record data @@ -754,7 +799,7 @@ private function writeShortNameBiff8($name, $sheetIndex, $rangeBounds, $isHidden /** * Stores the CODEPAGE biff record. */ - private function writeCodepage() + private function writeCodepage(): void { $record = 0x0042; // Record identifier $length = 0x0002; // Number of bytes to follow @@ -769,7 +814,7 @@ private function writeCodepage() /** * Write Excel BIFF WINDOW1 record. */ - private function writeWindow1() + private function writeWindow1(): void { $record = 0x003D; // Record identifier $length = 0x0012; // Number of bytes to follow @@ -798,10 +843,9 @@ private function writeWindow1() /** * Writes Excel BIFF BOUNDSHEET record. * - * @param Worksheet $sheet Worksheet name * @param int $offset Location of worksheet BOF */ - private function writeBoundSheet($sheet, $offset) + private function writeBoundSheet(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $sheet, $offset): void { $sheetname = $sheet->getTitle(); $record = 0x0085; // Record identifier @@ -876,7 +920,7 @@ private function writeExternalsheetBiff8() /** * Write Excel BIFF STYLE records. */ - private function writeStyle() + private function writeStyle(): void { $record = 0x0293; // Record identifier $length = 0x0004; // Bytes to follow @@ -896,7 +940,7 @@ private function writeStyle() * @param string $format Custom format string * @param int $ifmt Format index code */ - private function writeNumberFormat($format, $ifmt) + private function writeNumberFormat($format, $ifmt): void { $record = 0x041E; // Record identifier @@ -911,7 +955,7 @@ private function writeNumberFormat($format, $ifmt) /** * Write DATEMODE record to indicate the date system in use (1904 or 1900). */ - private function writeDateMode() + private function writeDateMode(): void { $record = 0x0022; // Record identifier $length = 0x0002; // Bytes to follow @@ -963,7 +1007,7 @@ private function writeRecalcId() /** * Stores the PALETTE biff record. */ - private function writePalette() + private function writePalette(): void { $aref = $this->palette; @@ -1130,21 +1174,17 @@ private function writeMsoDrawingGroup() /** * Get Escher object. - * - * @return \PhpOffice\PhpSpreadsheet\Shared\Escher */ - public function getEscher() + public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. - * - * @param \PhpOffice\PhpSpreadsheet\Shared\Escher $pValue */ - public function setEscher(\PhpOffice\PhpSpreadsheet\Shared\Escher $pValue = null) + public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { - $this->escher = $pValue; + $this->escher = $escher; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php index 5a6fa61a..796c2142 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Worksheet.php @@ -2,19 +2,17 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; +use GdImage; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; -use PhpOffice\PhpSpreadsheet\Cell\DataValidation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\Run; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\Xls; -use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\Conditional; -use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; @@ -56,6 +54,12 @@ // */ class Worksheet extends BIFFwriter { + /** @var int */ + private static $always0 = 0; + + /** @var int */ + private static $always1 = 1; + /** * Formula parser. * @@ -94,7 +98,7 @@ class Worksheet extends BIFFwriter /** * Whether to use outline. * - * @var int + * @var bool */ private $outlineOn; @@ -190,7 +194,7 @@ class Worksheet extends BIFFwriter /** * Escher object corresponding to MSODRAWING. * - * @var \PhpOffice\PhpSpreadsheet\Shared\Escher + * @var null|\PhpOffice\PhpSpreadsheet\Shared\Escher */ private $escher; @@ -216,8 +220,8 @@ class Worksheet extends BIFFwriter * * @param int $str_total Total number of strings * @param int $str_unique Total number of unique strings - * @param array &$str_table String Table - * @param array &$colors Colour Table + * @param array $str_table String Table + * @param array $colors Colour Table * @param Parser $parser The formula parser created for the Workbook * @param bool $preCalculateFormulas Flag indicating whether formulas should be calculated or just written * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet The worksheet to write @@ -243,10 +247,10 @@ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Pa $this->printHeaders = 0; - $this->outlineStyle = 0; - $this->outlineBelow = 1; - $this->outlineRight = 1; - $this->outlineOn = 1; + $this->outlineStyle = false; + $this->outlineBelow = true; + $this->outlineRight = true; + $this->outlineOn = true; $this->fontHashIndex = []; @@ -258,12 +262,12 @@ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Pa $maxC = $this->phpSheet->getHighestColumn(); // Determine lowest and highest column and row + $this->firstRowIndex = $minR; $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR; $this->firstColumnIndex = Coordinate::columnIndexFromString($minC); $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC); -// if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255; if ($this->lastColumnIndex > 255) { $this->lastColumnIndex = 255; } @@ -277,7 +281,7 @@ public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Pa * * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::storeWorkbook() */ - public function close() + public function close(): void { $phpSheet = $this->phpSheet; @@ -392,7 +396,13 @@ public function close() // Row dimensions foreach ($phpSheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs - $this->writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel()); + $this->writeRow( + $rowDimension->getRowIndex() - 1, + (int) $rowDimension->getRowHeight(), + $xfIndex, + !$rowDimension->getVisible(), + $rowDimension->getOutlineLevel() + ); } // Write Cells @@ -412,7 +422,6 @@ public function close() $cVal = $cell->getValue(); if ($cVal instanceof RichText) { $arrcRun = []; - $str_len = StringHelper::countCharacters($cVal->getPlainText(), 'UTF-8'); $str_pos = 0; $elements = $cVal->getRichTextElements(); foreach ($elements as $element) { @@ -430,6 +439,7 @@ public function close() } else { switch ($cell->getDatatype()) { case DataType::TYPE_STRING: + case DataType::TYPE_INLINE: case DataType::TYPE_NULL: if ($cVal === '' || $cVal === null) { $this->writeBlank($row, $column, $xfIndex); @@ -475,7 +485,7 @@ public function close() break; case DataType::TYPE_ERROR: - $this->writeBoolErr($row, $column, self::mapErrorCode($cVal), 1, $xfIndex); + $this->writeBoolErr($row, $column, ErrorCode::error($cVal), 1, $xfIndex); break; } @@ -511,7 +521,7 @@ public function close() // Hyperlinks foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { - [$column, $row] = Coordinate::coordinateFromString($coordinate); + [$column, $row] = Coordinate::indexesFromString($coordinate); $url = $hyperlink->getUrl(); @@ -525,7 +535,7 @@ public function close() $url = 'external:' . $url; } - $this->writeUrl($row - 1, Coordinate::columnIndexFromString($column) - 1, $url); + $this->writeUrl($row - 1, $column - 1, $url); } $this->writeDataValidity(); @@ -535,30 +545,44 @@ public function close() $this->writeSheetProtection(); $this->writeRangeProtection(); - $arrConditionalStyles = $phpSheet->getConditionalStylesCollection(); + // Write Conditional Formatting Rules and Styles + $this->writeConditionalFormatting(); + + $this->storeEof(); + } + + private function writeConditionalFormatting(): void + { + $conditionalFormulaHelper = new ConditionalHelper($this->parser); + + $arrConditionalStyles = $this->phpSheet->getConditionalStylesCollection(); if (!empty($arrConditionalStyles)) { $arrConditional = []; - // @todo CFRule & CFHeader - // Write CFHEADER record - $this->writeCFHeader(); + // Write ConditionalFormattingTable records foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { + $cfHeaderWritten = false; foreach ($conditionalStyles as $conditional) { - if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION - || $conditional->getConditionType() == Conditional::CONDITION_CELLIS) { - if (!isset($arrConditional[$conditional->getHashCode()])) { + /** @var Conditional $conditional */ + if ( + $conditional->getConditionType() === Conditional::CONDITION_EXPRESSION || + $conditional->getConditionType() === Conditional::CONDITION_CELLIS + ) { + // Write CFHEADER record (only if there are Conditional Styles that we are able to write) + if ($cfHeaderWritten === false) { + $cfHeaderWritten = $this->writeCFHeader($cellCoordinate, $conditionalStyles); + } + if ($cfHeaderWritten === true && !isset($arrConditional[$conditional->getHashCode()])) { // This hash code has been handled $arrConditional[$conditional->getHashCode()] = true; // Write CFRULE record - $this->writeCFRule($conditional); + $this->writeCFRule($conditionalFormulaHelper, $conditional, $cellCoordinate); } } } } } - - $this->storeEof(); } /** @@ -584,31 +608,30 @@ private function writeBIFF8CellRangeAddressFixed($range) $lastCell = $explodes[1]; } - $firstCellCoordinates = Coordinate::coordinateFromString($firstCell); // e.g. [0, 1] - $lastCellCoordinates = Coordinate::coordinateFromString($lastCell); // e.g. [1, 6] + $firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1] + $lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6] - return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, Coordinate::columnIndexFromString($firstCellCoordinates[0]) - 1, Coordinate::columnIndexFromString($lastCellCoordinates[0]) - 1); + return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1); } /** - * Retrieves data from memory in one chunk, or from disk in $buffer + * Retrieves data from memory in one chunk, or from disk * sized chunks. * * @return string The data */ public function getData() { - $buffer = 4096; - // Return data stored in memory if (isset($this->_data)) { $tmp = $this->_data; - unset($this->_data); + $this->_data = null; return $tmp; } + // No data to return - return false; + return ''; } /** @@ -616,7 +639,7 @@ public function getData() * * @param int $print Whether to print the headers or not. Defaults to 1 (print). */ - public function printRowColHeaders($print = 1) + public function printRowColHeaders($print = 1): void { $this->printHeaders = $print; } @@ -630,17 +653,12 @@ public function printRowColHeaders($print = 1) * @param bool $symbols_right * @param bool $auto_style */ - public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false) + public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false): void { $this->outlineOn = $visible; $this->outlineBelow = $symbols_below; $this->outlineRight = $symbols_right; $this->outlineStyle = $auto_style; - - // Ensure this is a boolean vale for Window2 - if ($this->outlineOn) { - $this->outlineOn = 1; - } } /** @@ -683,7 +701,7 @@ private function writeNumber($row, $col, $num, $xfIndex) * @param string $str The string * @param int $xfIndex Index to XF record */ - private function writeString($row, $col, $str, $xfIndex) + private function writeString($row, $col, $str, $xfIndex): void { $this->writeLabelSst($row, $col, $str, $xfIndex); } @@ -698,7 +716,7 @@ private function writeString($row, $col, $str, $xfIndex) * @param int $xfIndex The XF format index for the cell * @param array $arrcRun Index to Font record and characters beginning */ - private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun) + private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow @@ -725,7 +743,7 @@ private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun) * @param string $str The string to write * @param mixed $xfIndex The XF format index for the cell */ - private function writeLabelSst($row, $col, $str, $xfIndex) + private function writeLabelSst($row, $col, $str, $xfIndex): void { $record = 0x00FD; // Record identifier $length = 0x000A; // Bytes to follow @@ -822,7 +840,6 @@ private function writeBoolErr($row, $col, $value, $isError, $xfIndex) private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) { $record = 0x0006; // Record identifier - // Initialize possible additional value for STRING record that should be written after the FORMULA record? $stringValue = null; @@ -840,7 +857,7 @@ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) $errorCodes = DataType::getErrorCodes(); if (isset($errorCodes[$calculatedValue])) { // Error value - $num = pack('CCCvCv', 0x02, 0x00, self::mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF); + $num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF); } elseif ($calculatedValue === '') { // Empty string (and BIFF8) $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); @@ -872,7 +889,7 @@ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) // Parse the formula using the parser in Parser.php try { - $error = $this->parser->parse($formula); + $this->parser->parse($formula); $formula = $this->parser->toReversePolish(); $formlen = strlen($formula); // Length of the binary string @@ -881,8 +898,8 @@ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) $header = pack('vv', $record, $length); $data = pack('vvv', $row, $col, $xfIndex) - . $num - . pack('vVv', $grbit, $unknown, $formlen); + . $num + . pack('vVv', $grbit, $unknown, $formlen); $this->append($header . $data . $formula); // Append also a STRING record if necessary @@ -901,7 +918,7 @@ private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) * * @param string $stringValue */ - private function writeStringRecord($stringValue) + private function writeStringRecord($stringValue): void { $record = 0x0207; // Record identifier $data = StringHelper::UTF8toBIFF8UnicodeLong($stringValue); @@ -923,20 +940,14 @@ private function writeStringRecord($stringValue) * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external * directory url. * - * Returns 0 : normal termination - * -2 : row or column out of range - * -3 : long string truncated to 255 chars - * * @param int $row Row * @param int $col Column * @param string $url URL string - * - * @return int */ - private function writeUrl($row, $col, $url) + private function writeUrl($row, $col, $url): void { // Add start row and col to arg list - return $this->writeUrlRange($row, $col, $row, $col, $url); + $this->writeUrlRange($row, $col, $row, $col, $url); } /** @@ -945,27 +956,25 @@ private function writeUrl($row, $col, $url) * to be written. These are either, Web (http, ftp, mailto), Internal * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). * - * @see writeUrl() - * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * - * @return int + * @see writeUrl() */ - public function writeUrlRange($row1, $col1, $row2, $col2, $url) + private function writeUrlRange($row1, $col1, $row2, $col2, $url): void { // Check for internal/external sheet links or default to web link if (preg_match('[^internal:]', $url)) { - return $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); + $this->writeUrlInternal($row1, $col1, $row2, $col2, $url); } if (preg_match('[^external:]', $url)) { - return $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); + $this->writeUrlExternal($row1, $col1, $row2, $col2, $url); } - return $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); + $this->writeUrlWeb($row1, $col1, $row2, $col2, $url); } /** @@ -973,20 +982,17 @@ public function writeUrlRange($row1, $col1, $row2, $col2, $url) * The link type ($options) is 0x03 is the same as absolute dir ref without * sheet. However it is differentiated by the $unknown2 data stream. * - * @see writeUrl() - * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * - * @return int + * @see writeUrl() */ - public function writeUrlWeb($row1, $col1, $row2, $col2, $url) + public function writeUrlWeb($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow // Pack the undocumented parts of the hyperlink stream $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); @@ -996,6 +1002,8 @@ public function writeUrlWeb($row1, $col1, $row2, $col2, $url) $options = pack('V', 0x03); // Convert URL to a null terminated wchar string + + /** @phpstan-ignore-next-line */ $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); $url = $url . "\0\0\0"; @@ -1011,27 +1019,22 @@ public function writeUrlWeb($row1, $col1, $row2, $col2, $url) // Write the packed data $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url); - - return 0; } /** * Used to write internal reference hyperlinks such as "Sheet1!A1". * - * @see writeUrl() - * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * - * @return int + * @see writeUrl() */ - public function writeUrlInternal($row1, $col1, $row2, $col2, $url) + private function writeUrlInternal($row1, $col1, $row2, $col2, $url): void { $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow // Strip URL type $url = preg_replace('/^internal:/', '', $url); @@ -1060,8 +1063,6 @@ public function writeUrlInternal($row1, $col1, $row2, $col2, $url) // Write the packed data $this->append($header . $data . $unknown1 . $options . $url_len . $url); - - return 0; } /** @@ -1071,22 +1072,20 @@ public function writeUrlInternal($row1, $col1, $row2, $col2, $url) * Note: Excel writes some relative links with the $dir_long string. We ignore * these cases for the sake of simpler code. * - * @see writeUrl() - * * @param int $row1 Start row * @param int $col1 Start column * @param int $row2 End row * @param int $col2 End column * @param string $url URL string * - * @return int + * @see writeUrl() */ - public function writeUrlExternal($row1, $col1, $row2, $col2, $url) + private function writeUrlExternal($row1, $col1, $row2, $col2, $url): void { // Network drives are different. We will handle them separately // MS/Novell network drives and shares start with \\ if (preg_match('[^external:\\\\]', $url)) { - return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); + return; } $record = 0x01B8; // Record identifier @@ -1142,14 +1141,14 @@ public function writeUrlExternal($row1, $col1, $row2, $col2, $url) // Pack the main data stream $data = pack('vvvv', $row1, $row2, $col1, $col2) . - $unknown1 . - $link_type . - $unknown2 . - $up_count . - $dir_short_len . - $dir_short . - $unknown3 . - $stream_len; /*. + $unknown1 . + $link_type . + $unknown2 . + $up_count . + $dir_short_len . + $dir_short . + $unknown3 . + $stream_len; /*. $dir_long_len . $unknown4 . $dir_long . @@ -1162,8 +1161,6 @@ public function writeUrlExternal($row1, $col1, $row2, $col2, $url) // Write the packed data $this->append($header . $data); - - return 0; } /** @@ -1176,7 +1173,7 @@ public function writeUrlExternal($row1, $col1, $row2, $col2, $url) * @param bool $hidden The optional hidden attribute * @param int $level The optional outline level for row, in range [0,7] */ - private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) + private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0): void { $record = 0x0208; // Record identifier $length = 0x0010; // Number of bytes to follow @@ -1193,7 +1190,7 @@ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) } // Use writeRow($row, null, $XF) to set XF format without setting height - if ($height != null) { + if ($height !== null) { $miyRw = $height * 20; // row height } else { $miyRw = 0xff; // default row height is 256 @@ -1206,7 +1203,7 @@ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) // collapsed. The zero height flag, 0x20, is used to collapse a row. $grbit |= $level; - if ($hidden) { + if ($hidden === true) { $grbit |= 0x0030; } if ($height !== null) { @@ -1225,7 +1222,7 @@ private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) /** * Writes Excel DIMENSIONS to define the area in which there is data. */ - private function writeDimensions() + private function writeDimensions(): void { $record = 0x0200; // Record identifier @@ -1239,7 +1236,7 @@ private function writeDimensions() /** * Write BIFF record Window2. */ - private function writeWindow2() + private function writeWindow2(): void { $record = 0x023E; // Record identifier $length = 0x0012; @@ -1291,7 +1288,7 @@ private function writeWindow2() /** * Write BIFF record DEFAULTROWHEIGHT. */ - private function writeDefaultRowHeight() + private function writeDefaultRowHeight(): void { $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight(); @@ -1313,7 +1310,7 @@ private function writeDefaultRowHeight() /** * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. */ - private function writeDefcol() + private function writeDefcol(): void { $defaultColWidth = 8; @@ -1339,34 +1336,15 @@ private function writeDefcol() * 4 => Option flags. * 5 => Optional outline level */ - private function writeColinfo($col_array) + private function writeColinfo($col_array): void { - if (isset($col_array[0])) { - $colFirst = $col_array[0]; - } - if (isset($col_array[1])) { - $colLast = $col_array[1]; - } - if (isset($col_array[2])) { - $coldx = $col_array[2]; - } else { - $coldx = 8.43; - } - if (isset($col_array[3])) { - $xfIndex = $col_array[3]; - } else { - $xfIndex = 15; - } - if (isset($col_array[4])) { - $grbit = $col_array[4]; - } else { - $grbit = 0; - } - if (isset($col_array[5])) { - $level = $col_array[5]; - } else { - $level = 0; - } + $colFirst = $col_array[0] ?? null; + $colLast = $col_array[1] ?? null; + $coldx = $col_array[2] ?? 8.43; + $xfIndex = $col_array[3] ?? 15; + $grbit = $col_array[4] ?? 0; + $level = $col_array[5] ?? 0; + $record = 0x007D; // Record identifier $length = 0x000C; // Number of bytes to follow @@ -1386,7 +1364,7 @@ private function writeColinfo($col_array) /** * Write BIFF record SELECTION. */ - private function writeSelection() + private function writeSelection(): void { // look up the selected cell range $selectedCells = Coordinate::splitRange($this->phpSheet->getSelectedCells()); @@ -1422,13 +1400,6 @@ private function writeSelection() $irefAct = 0; // Active cell ref $cref = 1; // Number of refs - if (!isset($rwLast)) { - $rwLast = $rwFirst; // Last row in reference - } - if (!isset($colLast)) { - $colLast = $colFirst; // Last col in reference - } - // Swap last row/col for first row/col as necessary if ($rwFirst > $rwLast) { [$rwFirst, $rwLast] = [$rwLast, $rwFirst]; @@ -1446,7 +1417,7 @@ private function writeSelection() /** * Store the MERGEDCELLS records for all ranges of merged cells. */ - private function writeMergedCells() + private function writeMergedCells(): void { $mergeCells = $this->phpSheet->getMergeCells(); $countMergeCells = count($mergeCells); @@ -1478,13 +1449,13 @@ private function writeMergedCells() // extract the row and column indexes $range = Coordinate::splitRange($mergeCell); [$first, $last] = $range[0]; - [$firstColumn, $firstRow] = Coordinate::coordinateFromString($first); - [$lastColumn, $lastRow] = Coordinate::coordinateFromString($last); + [$firstColumn, $firstRow] = Coordinate::indexesFromString($first); + [$lastColumn, $lastRow] = Coordinate::indexesFromString($last); - $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, Coordinate::columnIndexFromString($firstColumn) - 1, Coordinate::columnIndexFromString($lastColumn) - 1); + $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, $firstColumn - 1, $lastColumn - 1); // flush record if we have reached limit for number of merged cells, or reached final merged cell - if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) { + if ($j == $maxCountMergeCellsPerRecord || $i == $countMergeCells) { $recordData = pack('v', $j) . $recordData; $length = strlen($recordData); $header = pack('vv', $record, $length); @@ -1500,7 +1471,7 @@ private function writeMergedCells() /** * Write SHEETLAYOUT record. */ - private function writeSheetLayout() + private function writeSheetLayout(): void { if (!$this->phpSheet->isTabColorSet()) { return; @@ -1527,27 +1498,27 @@ private function writeSheetLayout() /** * Write SHEETPROTECTION. */ - private function writeSheetProtection() + private function writeSheetProtection(): void { // record identifier $record = 0x0867; // prepare options $options = (int) !$this->phpSheet->getProtection()->getObjects() - | (int) !$this->phpSheet->getProtection()->getScenarios() << 1 - | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2 - | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3 - | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4 - | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5 - | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6 - | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7 - | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8 - | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9 - | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10 - | (int) !$this->phpSheet->getProtection()->getSort() << 11 - | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12 - | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13 - | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14; + | (int) !$this->phpSheet->getProtection()->getScenarios() << 1 + | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2 + | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3 + | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4 + | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5 + | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6 + | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7 + | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8 + | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9 + | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10 + | (int) !$this->phpSheet->getProtection()->getSort() << 11 + | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12 + | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13 + | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14; // record data $recordData = pack( @@ -1571,10 +1542,10 @@ private function writeSheetProtection() /** * Write BIFF record RANGEPROTECTION. * - * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records + * Openoffice.org's Documentation of the Microsoft Excel File Format uses term RANGEPROTECTION for these records * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records */ - private function writeRangeProtection() + private function writeRangeProtection(): void { foreach ($this->phpSheet->getProtectedCells() as $range => $password) { // number of ranges, e.g. 'A1:B3 C20:D25' @@ -1622,78 +1593,39 @@ private function writeRangeProtection() * Frozen panes are specified in terms of an integer number of rows and columns. * Thawed panes are specified in terms of Excel's units for rows and columns. */ - private function writePanes() + private function writePanes(): void { - $panes = []; - if ($this->phpSheet->getFreezePane()) { - [$column, $row] = Coordinate::coordinateFromString($this->phpSheet->getFreezePane()); - $panes[0] = Coordinate::columnIndexFromString($column) - 1; - $panes[1] = $row - 1; - - [$leftMostColumn, $topRow] = Coordinate::coordinateFromString($this->phpSheet->getTopLeftCell()); - //Coordinates are zero-based in xls files - $panes[2] = $topRow - 1; - $panes[3] = Coordinate::columnIndexFromString($leftMostColumn) - 1; - } else { + if (!$this->phpSheet->getFreezePane()) { // thaw panes return; } - $x = $panes[0] ?? null; - $y = $panes[1] ?? null; - $rwTop = $panes[2] ?? null; - $colLeft = $panes[3] ?? null; - if (count($panes) > 4) { // if Active pane was received - $pnnAct = $panes[4]; - } else { - $pnnAct = null; - } - $record = 0x0041; // Record identifier - $length = 0x000A; // Number of bytes to follow + [$column, $row] = Coordinate::indexesFromString($this->phpSheet->getFreezePane() ?? ''); + $x = $column - 1; + $y = $row - 1; - // Code specific to frozen or thawed panes. - if ($this->phpSheet->getFreezePane()) { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = $y; - } - if (!isset($colLeft)) { - $colLeft = $x; - } - } else { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = 0; - } - if (!isset($colLeft)) { - $colLeft = 0; - } + [$leftMostColumn, $topRow] = Coordinate::indexesFromString($this->phpSheet->getTopLeftCell()); + //Coordinates are zero-based in xls files + $rwTop = $topRow - 1; + $colLeft = $leftMostColumn - 1; - // Convert Excel's row and column units to the internal units. - // The default row height is 12.75 - // The default column width is 8.43 - // The following slope and intersection values were interpolated. - // - $y = 20 * $y + 255; - $x = 113.879 * $x + 390; - } + $record = 0x0041; // Record identifier + $length = 0x000A; // Number of bytes to follow // Determine which pane should be active. There is also the undocumented // option to override this should it be necessary: may be removed later. - // - if (!isset($pnnAct)) { - if ($x != 0 && $y != 0) { - $pnnAct = 0; // Bottom right - } - if ($x != 0 && $y == 0) { - $pnnAct = 1; // Top right - } - if ($x == 0 && $y != 0) { - $pnnAct = 2; // Bottom left - } - if ($x == 0 && $y == 0) { - $pnnAct = 3; // Top left - } + $pnnAct = null; + if ($x != 0 && $y != 0) { + $pnnAct = 0; // Bottom right + } + if ($x != 0 && $y == 0) { + $pnnAct = 1; // Top right + } + if ($x == 0 && $y != 0) { + $pnnAct = 2; // Bottom left + } + if ($x == 0 && $y == 0) { + $pnnAct = 3; // Top left } $this->activePane = $pnnAct; // Used in writeSelection @@ -1706,15 +1638,13 @@ private function writePanes() /** * Store the page setup SETUP BIFF record. */ - private function writeSetup() + private function writeSetup(): void { $record = 0x00A1; // Record identifier $length = 0x0022; // Number of bytes to follow $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size - - $iScale = $this->phpSheet->getPageSetup()->getScale() ? - $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor + $iScale = $this->phpSheet->getPageSetup()->getScale() ?: 100; // Print scaling factor $iPageStart = 0x01; // Starting page number $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide @@ -1728,11 +1658,12 @@ private function writeSetup() $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin $iCopies = 0x01; // Number of copies - $fLeftToRight = 0x0; // Print over then down - + // Order of printing pages + $fLeftToRight = $this->phpSheet->getPageSetup()->getPageOrder() === PageSetup::PAGEORDER_DOWN_THEN_OVER + ? 0x1 : 0x0; // Page orientation - $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) ? - 0x0 : 0x1; + $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE) + ? 0x0 : 0x1; $fNoPls = 0x0; // Setup not read from printer $fNoColor = 0x0; // Print black and white @@ -1767,7 +1698,7 @@ private function writeSetup() /** * Store the header caption BIFF record. */ - private function writeHeader() + private function writeHeader(): void { $record = 0x0014; // Record identifier @@ -1791,7 +1722,7 @@ private function writeHeader() /** * Store the footer caption BIFF record. */ - private function writeFooter() + private function writeFooter(): void { $record = 0x0015; // Record identifier @@ -1815,7 +1746,7 @@ private function writeFooter() /** * Store the horizontal centering HCENTER BIFF record. */ - private function writeHcenter() + private function writeHcenter(): void { $record = 0x0083; // Record identifier $length = 0x0002; // Bytes to follow @@ -1831,7 +1762,7 @@ private function writeHcenter() /** * Store the vertical centering VCENTER BIFF record. */ - private function writeVcenter() + private function writeVcenter(): void { $record = 0x0084; // Record identifier $length = 0x0002; // Bytes to follow @@ -1846,7 +1777,7 @@ private function writeVcenter() /** * Store the LEFTMARGIN BIFF record. */ - private function writeMarginLeft() + private function writeMarginLeft(): void { $record = 0x0026; // Record identifier $length = 0x0008; // Bytes to follow @@ -1865,7 +1796,7 @@ private function writeMarginLeft() /** * Store the RIGHTMARGIN BIFF record. */ - private function writeMarginRight() + private function writeMarginRight(): void { $record = 0x0027; // Record identifier $length = 0x0008; // Bytes to follow @@ -1884,7 +1815,7 @@ private function writeMarginRight() /** * Store the TOPMARGIN BIFF record. */ - private function writeMarginTop() + private function writeMarginTop(): void { $record = 0x0028; // Record identifier $length = 0x0008; // Bytes to follow @@ -1903,7 +1834,7 @@ private function writeMarginTop() /** * Store the BOTTOMMARGIN BIFF record. */ - private function writeMarginBottom() + private function writeMarginBottom(): void { $record = 0x0029; // Record identifier $length = 0x0008; // Bytes to follow @@ -1922,7 +1853,7 @@ private function writeMarginBottom() /** * Write the PRINTHEADERS BIFF record. */ - private function writePrintHeaders() + private function writePrintHeaders(): void { $record = 0x002a; // Record identifier $length = 0x0002; // Bytes to follow @@ -1938,7 +1869,7 @@ private function writePrintHeaders() * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the * GRIDSET record. */ - private function writePrintGridlines() + private function writePrintGridlines(): void { $record = 0x002b; // Record identifier $length = 0x0002; // Bytes to follow @@ -1954,7 +1885,7 @@ private function writePrintGridlines() * Write the GRIDSET BIFF record. Must be used in conjunction with the * PRINTGRIDLINES record. */ - private function writeGridset() + private function writeGridset(): void { $record = 0x0082; // Record identifier $length = 0x0002; // Bytes to follow @@ -1969,7 +1900,7 @@ private function writeGridset() /** * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet. */ - private function writeAutoFilterInfo() + private function writeAutoFilterInfo(): void { $record = 0x009D; // Record identifier $length = 0x0002; // Bytes to follow @@ -1989,7 +1920,7 @@ private function writeAutoFilterInfo() * * @see writeWsbool() */ - private function writeGuts() + private function writeGuts(): void { $record = 0x0080; // Record identifier $length = 0x0008; // Bytes to follow @@ -2033,7 +1964,7 @@ private function writeGuts() * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction * with the SETUP record. */ - private function writeWsbool() + private function writeWsbool(): void { $record = 0x0081; // Record identifier $length = 0x0002; // Bytes to follow @@ -2068,7 +1999,7 @@ private function writeWsbool() /** * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records. */ - private function writeBreaks() + private function writeBreaks(): void { // initialize $vbreaks = []; @@ -2151,7 +2082,7 @@ private function writeBreaks() /** * Set the Biff PROTECT record to indicate that the worksheet is protected. */ - private function writeProtect() + private function writeProtect(): void { // Exit unless sheet protection has been specified if (!$this->phpSheet->getProtection()->getSheet()) { @@ -2172,7 +2103,7 @@ private function writeProtect() /** * Write SCENPROTECT. */ - private function writeScenProtect() + private function writeScenProtect(): void { // Exit if sheet protection is not active if (!$this->phpSheet->getProtection()->getSheet()) { @@ -2196,7 +2127,7 @@ private function writeScenProtect() /** * Write OBJECTPROTECT. */ - private function writeObjectProtect() + private function writeObjectProtect(): void { // Exit if sheet protection is not active if (!$this->phpSheet->getProtection()->getSheet()) { @@ -2220,10 +2151,10 @@ private function writeObjectProtect() /** * Write the worksheet PASSWORD record. */ - private function writePassword() + private function writePassword(): void { // Exit unless sheet protection and password have been specified - if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) { + if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword() || $this->phpSheet->getProtection()->getAlgorithm() !== '') { return; } @@ -2249,9 +2180,11 @@ private function writePassword() * @param float $scale_x The horizontal scale * @param float $scale_y The vertical scale */ - public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1) + public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1): void { - $bitmap_array = (is_resource($bitmap) ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap)); + $bitmap_array = (is_resource($bitmap) || $bitmap instanceof GdImage + ? $this->processBitmapGd($bitmap) + : $this->processBitmap($bitmap)); [$width, $height, $size, $data] = $bitmap_array; // Scale the frame of the image. @@ -2322,7 +2255,7 @@ public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, * @param int $width Width of image frame * @param int $height Height of image frame */ - public function positionImage($col_start, $row_start, $x1, $y1, $width, $height) + public function positionImage($col_start, $row_start, $x1, $y1, $width, $height): void { // Initialise end cell to the same as the start cell $col_end = $col_start; // Col containing lower right corner of object @@ -2389,7 +2322,7 @@ public function positionImage($col_start, $row_start, $x1, $y1, $width, $height) * @param int $rwB Row containing bottom right corner of object * @param int $dyB Distance from bottom of cell */ - private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB) + private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB): void { $record = 0x005d; // Record identifier $length = 0x003c; // Bytes to follow @@ -2457,7 +2390,7 @@ private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dy /** * Convert a GD-image into the internal format. * - * @param resource $image The image to process + * @param GdImage|resource $image The image to process * * @return array Array with data and properties of the bitmap */ @@ -2469,9 +2402,10 @@ public function processBitmapGd($image) $data = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18); for ($j = $height; --$j;) { for ($i = 0; $i < $width; ++$i) { + /** @phpstan-ignore-next-line */ $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); foreach (['red', 'green', 'blue'] as $key) { - $color[$key] = $color[$key] + round((255 - $color[$key]) * $color['alpha'] / 127); + $color[$key] = $color[$key] + (int) round((255 - $color[$key]) * $color['alpha'] / 127); } $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']); } @@ -2509,6 +2443,8 @@ public function processBitmap($bitmap) } // The first 2 bytes are used to identify the bitmap. + + /** @phpstan-ignore-next-line */ $identity = unpack('A2ident', $data); if ($identity['ident'] != 'BM') { throw new WriterException("$bitmap doesn't appear to be a valid bitmap image.\n"); @@ -2573,7 +2509,7 @@ public function processBitmap($bitmap) * Store the window zoom factor. This should be a reduced fraction but for * simplicity we will store all fractions with a numerator of 100. */ - private function writeZoom() + private function writeZoom(): void { // If scale is 100 we don't need to write a record if ($this->phpSheet->getSheetView()->getZoomScale() == 100) { @@ -2590,28 +2526,24 @@ private function writeZoom() /** * Get Escher object. - * - * @return \PhpOffice\PhpSpreadsheet\Shared\Escher */ - public function getEscher() + public function getEscher(): ?\PhpOffice\PhpSpreadsheet\Shared\Escher { return $this->escher; } /** * Set Escher object. - * - * @param \PhpOffice\PhpSpreadsheet\Shared\Escher $pValue */ - public function setEscher(\PhpOffice\PhpSpreadsheet\Shared\Escher $pValue = null) + public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $escher): void { - $this->escher = $pValue; + $this->escher = $escher; } /** * Write MSODRAWING record. */ - private function writeMsoDrawing() + private function writeMsoDrawing(): void { // write the Escher stream if necessary if (isset($this->escher)) { @@ -2696,7 +2628,7 @@ private function writeMsoDrawing() /** * Store the DATAVALIDATIONS and DATAVALIDATION records. */ - private function writeDataValidity() + private function writeDataValidity(): void { // Datavalidation collection $dataValidationCollection = $this->phpSheet->getDataValidationCollection(); @@ -2720,67 +2652,16 @@ private function writeDataValidity() $record = 0x01BE; // Record identifier foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { - // initialize record data - $data = ''; - // options $options = 0x00000000; // data type - $type = 0x00; - switch ($dataValidation->getType()) { - case DataValidation::TYPE_NONE: - $type = 0x00; - - break; - case DataValidation::TYPE_WHOLE: - $type = 0x01; - - break; - case DataValidation::TYPE_DECIMAL: - $type = 0x02; - - break; - case DataValidation::TYPE_LIST: - $type = 0x03; - - break; - case DataValidation::TYPE_DATE: - $type = 0x04; - - break; - case DataValidation::TYPE_TIME: - $type = 0x05; - - break; - case DataValidation::TYPE_TEXTLENGTH: - $type = 0x06; - - break; - case DataValidation::TYPE_CUSTOM: - $type = 0x07; - - break; - } + $type = CellDataValidation::type($dataValidation); $options |= $type << 0; // error style - $errorStyle = 0x00; - switch ($dataValidation->getErrorStyle()) { - case DataValidation::STYLE_STOP: - $errorStyle = 0x00; - - break; - case DataValidation::STYLE_WARNING: - $errorStyle = 0x01; - - break; - case DataValidation::STYLE_INFORMATION: - $errorStyle = 0x02; - - break; - } + $errorStyle = CellDataValidation::errorStyle($dataValidation); $options |= $errorStyle << 4; @@ -2802,41 +2683,7 @@ private function writeDataValidity() $options |= $dataValidation->getShowErrorMessage() << 19; // condition operator - $operator = 0x00; - switch ($dataValidation->getOperator()) { - case DataValidation::OPERATOR_BETWEEN: - $operator = 0x00; - - break; - case DataValidation::OPERATOR_NOTBETWEEN: - $operator = 0x01; - - break; - case DataValidation::OPERATOR_EQUAL: - $operator = 0x02; - - break; - case DataValidation::OPERATOR_NOTEQUAL: - $operator = 0x03; - - break; - case DataValidation::OPERATOR_GREATERTHAN: - $operator = 0x04; - - break; - case DataValidation::OPERATOR_LESSTHAN: - $operator = 0x05; - - break; - case DataValidation::OPERATOR_GREATERTHANOREQUAL: - $operator = 0x06; - - break; - case DataValidation::OPERATOR_LESSTHANOREQUAL: - $operator = 0x07; - - break; - } + $operator = CellDataValidation::operator($dataValidation); $options |= $operator << 20; @@ -2906,39 +2753,10 @@ private function writeDataValidity() } } - /** - * Map Error code. - * - * @param string $errorCode - * - * @return int - */ - private static function mapErrorCode($errorCode) - { - switch ($errorCode) { - case '#NULL!': - return 0x00; - case '#DIV/0!': - return 0x07; - case '#VALUE!': - return 0x0F; - case '#REF!': - return 0x17; - case '#NAME?': - return 0x1D; - case '#NUM!': - return 0x24; - case '#N/A': - return 0x2A; - } - - return 0; - } - /** * Write PLV Record. */ - private function writePageLayoutView() + private function writePageLayoutView(): void { $record = 0x088B; // Record identifier $length = 0x0010; // Bytes to follow @@ -2968,15 +2786,16 @@ private function writePageLayoutView() /** * Write CFRule Record. - * - * @param Conditional $conditional */ - private function writeCFRule(Conditional $conditional) - { + private function writeCFRule( + ConditionalHelper $conditionalFormulaHelper, + Conditional $conditional, + string $cellRange + ): void { $record = 0x01B1; // Record identifier + $type = null; // Type of the CF + $operatorType = null; // Comparison operator - // $type : Type of the CF - // $operatorType : Comparison operator if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) { $type = 0x02; $operatorType = 0x00; @@ -3016,7 +2835,7 @@ private function writeCFRule(Conditional $conditional) $operatorType = 0x01; break; - // not OPERATOR_NOTBETWEEN 0x02 + // not OPERATOR_NOTBETWEEN 0x02 } } @@ -3024,31 +2843,33 @@ private function writeCFRule(Conditional $conditional) // $szValue2 : size of the formula data for second value or formula $arrConditions = $conditional->getConditions(); $numConditions = count($arrConditions); - if ($numConditions == 1) { - $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); - $szValue2 = 0x0000; - $operand1 = pack('Cv', 0x1E, $arrConditions[0]); - $operand2 = null; - } elseif ($numConditions == 2 && ($conditional->getOperatorType() == Conditional::OPERATOR_BETWEEN)) { - $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); - $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000); - $operand1 = pack('Cv', 0x1E, $arrConditions[0]); - $operand2 = pack('Cv', 0x1E, $arrConditions[1]); - } else { - $szValue1 = 0x0000; - $szValue2 = 0x0000; - $operand1 = null; - $operand2 = null; + + $szValue1 = 0x0000; + $szValue2 = 0x0000; + $operand1 = null; + $operand2 = null; + + if ($numConditions === 1) { + $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); + $szValue1 = $conditionalFormulaHelper->size(); + $operand1 = $conditionalFormulaHelper->tokens(); + } elseif ($numConditions === 2 && ($conditional->getOperatorType() === Conditional::OPERATOR_BETWEEN)) { + $conditionalFormulaHelper->processCondition($arrConditions[0], $cellRange); + $szValue1 = $conditionalFormulaHelper->size(); + $operand1 = $conditionalFormulaHelper->tokens(); + $conditionalFormulaHelper->processCondition($arrConditions[1], $cellRange); + $szValue2 = $conditionalFormulaHelper->size(); + $operand2 = $conditionalFormulaHelper->tokens(); } // $flags : Option flags // Alignment - $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0); - $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0); - $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0); - $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0); - $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0); - $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0); + $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() === null ? 1 : 0); + $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() === null ? 1 : 0); + $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() === false ? 1 : 0); + $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() === null ? 1 : 0); + $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() === 0 ? 1 : 0); + $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() === false ? 1 : 0); if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) { $bFormatAlign = 1; } else { @@ -3064,20 +2885,20 @@ private function writeCFRule(Conditional $conditional) } // Border $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == Color::COLOR_BLACK - && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); + && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == Color::COLOR_BLACK - && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); + && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == Color::COLOR_BLACK - && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); + && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == Color::COLOR_BLACK - && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); + && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0); if ($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0) { $bFormatBorder = 1; } else { $bFormatBorder = 0; } // Pattern - $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1); + $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() === null ? 0 : 1); $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1); $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1); if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) { @@ -3086,15 +2907,17 @@ private function writeCFRule(Conditional $conditional) $bFormatFill = 0; } // Font - if ($conditional->getStyle()->getFont()->getName() != null - || $conditional->getStyle()->getFont()->getSize() != null - || $conditional->getStyle()->getFont()->getBold() != null - || $conditional->getStyle()->getFont()->getItalic() != null - || $conditional->getStyle()->getFont()->getSuperscript() != null - || $conditional->getStyle()->getFont()->getSubscript() != null - || $conditional->getStyle()->getFont()->getUnderline() != null - || $conditional->getStyle()->getFont()->getStrikethrough() != null - || $conditional->getStyle()->getFont()->getColor()->getARGB() != null) { + if ( + $conditional->getStyle()->getFont()->getName() !== null + || $conditional->getStyle()->getFont()->getSize() !== null + || $conditional->getStyle()->getFont()->getBold() !== null + || $conditional->getStyle()->getFont()->getItalic() !== null + || $conditional->getStyle()->getFont()->getSuperscript() !== null + || $conditional->getStyle()->getFont()->getSubscript() !== null + || $conditional->getStyle()->getFont()->getUnderline() !== null + || $conditional->getStyle()->getFont()->getStrikethrough() !== null + || $conditional->getStyle()->getFont()->getColor()->getARGB() != null + ) { $bFormatFont = 1; } else { $bFormatFont = 0; @@ -3106,11 +2929,11 @@ private function writeCFRule(Conditional $conditional) $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0); $flags |= (1 == $bTxRotation ? 0x00000008 : 0); // Justify last line flag - $flags |= (1 == 1 ? 0x00000010 : 0); + $flags |= (1 == self::$always1 ? 0x00000010 : 0); $flags |= (1 == $bIndent ? 0x00000020 : 0); $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0); // Default - $flags |= (1 == 1 ? 0x00000080 : 0); + $flags |= (1 == self::$always1 ? 0x00000080 : 0); // Protection $flags |= (1 == $bProtLocked ? 0x00000100 : 0); $flags |= (1 == $bProtHidden ? 0x00000200 : 0); @@ -3119,13 +2942,13 @@ private function writeCFRule(Conditional $conditional) $flags |= (1 == $bBorderRight ? 0x00000800 : 0); $flags |= (1 == $bBorderTop ? 0x00001000 : 0); $flags |= (1 == $bBorderBottom ? 0x00002000 : 0); - $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border - $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border + $flags |= (1 == self::$always1 ? 0x00004000 : 0); // Top left to Bottom right border + $flags |= (1 == self::$always1 ? 0x00008000 : 0); // Bottom left to Top right border // Pattern $flags |= (1 == $bFillStyle ? 0x00010000 : 0); $flags |= (1 == $bFillColor ? 0x00020000 : 0); $flags |= (1 == $bFillColorBg ? 0x00040000 : 0); - $flags |= (1 == 1 ? 0x00380000 : 0); + $flags |= (1 == self::$always1 ? 0x00380000 : 0); // Font $flags |= (1 == $bFormatFont ? 0x04000000 : 0); // Alignment: @@ -3137,19 +2960,24 @@ private function writeCFRule(Conditional $conditional) // Protection $flags |= (1 == $bFormatProt ? 0x40000000 : 0); // Text direction - $flags |= (1 == 0 ? 0x80000000 : 0); + $flags |= (1 == self::$always0 ? 0x80000000 : 0); + + $dataBlockFont = null; + $dataBlockAlign = null; + $dataBlockBorder = null; + $dataBlockFill = null; // Data Blocks if ($bFormatFont == 1) { // Font Name - if ($conditional->getStyle()->getFont()->getName() == null) { + if ($conditional->getStyle()->getFont()->getName() === null) { $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); } else { $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); } // Font Size - if ($conditional->getStyle()->getFont()->getSize() == null) { + if ($conditional->getStyle()->getFont()->getSize() === null) { $dataBlockFont .= pack('V', 20 * 11); } else { $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); @@ -3157,16 +2985,16 @@ private function writeCFRule(Conditional $conditional) // Font Options $dataBlockFont .= pack('V', 0); // Font weight - if ($conditional->getStyle()->getFont()->getBold() == true) { + if ($conditional->getStyle()->getFont()->getBold() === true) { $dataBlockFont .= pack('v', 0x02BC); } else { $dataBlockFont .= pack('v', 0x0190); } // Escapement type - if ($conditional->getStyle()->getFont()->getSubscript() == true) { + if ($conditional->getStyle()->getFont()->getSubscript() === true) { $dataBlockFont .= pack('v', 0x02); $fontEscapement = 0; - } elseif ($conditional->getStyle()->getFont()->getSuperscript() == true) { + } elseif ($conditional->getStyle()->getFont()->getSuperscript() === true) { $dataBlockFont .= pack('v', 0x01); $fontEscapement = 0; } else { @@ -3209,1276 +3037,175 @@ private function writeCFRule(Conditional $conditional) // Not used (3) $dataBlockFont .= pack('vC', 0x0000, 0x00); // Font color index - switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) { - case '000000': - $colorIdx = 0x08; + $colorIdx = Style\ColorMap::lookup($conditional->getStyle()->getFont()->getColor(), 0x00); - break; - case 'FFFFFF': - $colorIdx = 0x09; + $dataBlockFont .= pack('V', $colorIdx); + // Not used (4) + $dataBlockFont .= pack('V', 0x00000000); + // Options flags for modified font attributes + $optionsFlags = 0; + $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() === null ? 1 : 0); + $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); + $optionsFlags |= (1 == self::$always1 ? 0x00000008 : 0); + $optionsFlags |= (1 == self::$always1 ? 0x00000010 : 0); + $optionsFlags |= (1 == self::$always0 ? 0x00000020 : 0); + $optionsFlags |= (1 == self::$always1 ? 0x00000080 : 0); + $dataBlockFont .= pack('V', $optionsFlags); + // Escapement type + $dataBlockFont .= pack('V', $fontEscapement); + // Underline type + $dataBlockFont .= pack('V', $fontUnderline); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Not used (8) + $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); + // Always + $dataBlockFont .= pack('v', 0x0001); + } + if ($bFormatAlign === 1) { + // Alignment and text break + $blockAlign = Style\CellAlignment::horizontal($conditional->getStyle()->getAlignment()); + $blockAlign |= Style\CellAlignment::wrap($conditional->getStyle()->getAlignment()) << 3; + $blockAlign |= Style\CellAlignment::vertical($conditional->getStyle()->getAlignment()) << 4; + $blockAlign |= 0 << 7; - break; - case 'FF0000': - $colorIdx = 0x0A; + // Text rotation angle + $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); - break; - case '00FF00': - $colorIdx = 0x0B; + // Indentation + $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); + if ($conditional->getStyle()->getAlignment()->getShrinkToFit() === true) { + $blockIndent |= 1 << 4; + } else { + $blockIndent |= 0 << 4; + } + $blockIndent |= 0 << 6; - break; - case '0000FF': - $colorIdx = 0x0C; + // Relative indentation + $blockIndentRelative = 255; - break; - case 'FFFF00': - $colorIdx = 0x0D; + $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); + } + if ($bFormatBorder === 1) { + $blockLineStyle = Style\CellBorder::style($conditional->getStyle()->getBorders()->getLeft()); + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getRight()) << 4; + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getTop()) << 8; + $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getBottom()) << 12; - break; - case 'FF00FF': - $colorIdx = 0x0E; + // TODO writeCFRule() => $blockLineStyle => Index Color for left line + // TODO writeCFRule() => $blockLineStyle => Index Color for right line + // TODO writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off + // TODO writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off + $blockColor = 0; + // TODO writeCFRule() => $blockColor => Index Color for top line + // TODO writeCFRule() => $blockColor => Index Color for bottom line + // TODO writeCFRule() => $blockColor => Index Color for diagonal line + $blockColor |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getDiagonal()) << 21; + $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); + } + if ($bFormatFill === 1) { + // Fill Pattern Style + $blockFillPatternStyle = Style\CellFill::style($conditional->getStyle()->getFill()); + // Background Color + $colorIdxBg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getStartColor(), 0x41); + // Foreground Color + $colorIdxFg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getEndColor(), 0x40); - break; - case '00FFFF': - $colorIdx = 0x0F; + $dataBlockFill = pack('v', $blockFillPatternStyle); + $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); + } - break; - case '800000': - $colorIdx = 0x10; + $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); + if ($bFormatFont === 1) { // Block Formatting : OK + $data .= $dataBlockFont; + } + if ($bFormatAlign === 1) { + $data .= $dataBlockAlign; + } + if ($bFormatBorder === 1) { + $data .= $dataBlockBorder; + } + if ($bFormatFill === 1) { // Block Formatting : OK + $data .= $dataBlockFill; + } + if ($bFormatProt == 1) { + $data .= $this->getDataBlockProtection($conditional); + } + if ($operand1 !== null) { + $data .= $operand1; + } + if ($operand2 !== null) { + $data .= $operand2; + } + $header = pack('vv', $record, strlen($data)); + $this->append($header . $data); + } - break; - case '008000': - $colorIdx = 0x11; + /** + * Write CFHeader record. + * + * @param Conditional[] $conditionalStyles + */ + private function writeCFHeader(string $cellCoordinate, array $conditionalStyles): bool + { + $record = 0x01B0; // Record identifier + $length = 0x0016; // Bytes to follow - break; - case '000080': - $colorIdx = 0x12; + $numColumnMin = null; + $numColumnMax = null; + $numRowMin = null; + $numRowMax = null; - break; - case '808000': - $colorIdx = 0x13; + $arrConditional = []; + foreach ($conditionalStyles as $conditional) { + if (!in_array($conditional->getHashCode(), $arrConditional)) { + $arrConditional[] = $conditional->getHashCode(); + } + // Cells + $rangeCoordinates = Coordinate::rangeBoundaries($cellCoordinate); + if ($numColumnMin === null || ($numColumnMin > $rangeCoordinates[0][0])) { + $numColumnMin = $rangeCoordinates[0][0]; + } + if ($numColumnMax === null || ($numColumnMax < $rangeCoordinates[1][0])) { + $numColumnMax = $rangeCoordinates[1][0]; + } + if ($numRowMin === null || ($numRowMin > $rangeCoordinates[0][1])) { + $numRowMin = (int) $rangeCoordinates[0][1]; + } + if ($numRowMax === null || ($numRowMax < $rangeCoordinates[1][1])) { + $numRowMax = (int) $rangeCoordinates[1][1]; + } + } - break; - case '800080': - $colorIdx = 0x14; + if (count($arrConditional) === 0) { + return false; + } - break; - case '008080': - $colorIdx = 0x15; + $needRedraw = 1; + $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1); - break; - case 'C0C0C0': - $colorIdx = 0x16; + $header = pack('vv', $record, $length); + $data = pack('vv', count($arrConditional), $needRedraw); + $data .= $cellRange; + $data .= pack('v', 0x0001); + $data .= $cellRange; + $this->append($header . $data); - break; - case '808080': - $colorIdx = 0x17; - - break; - case '9999FF': - $colorIdx = 0x18; - - break; - case '993366': - $colorIdx = 0x19; - - break; - case 'FFFFCC': - $colorIdx = 0x1A; - - break; - case 'CCFFFF': - $colorIdx = 0x1B; - - break; - case '660066': - $colorIdx = 0x1C; - - break; - case 'FF8080': - $colorIdx = 0x1D; - - break; - case '0066CC': - $colorIdx = 0x1E; - - break; - case 'CCCCFF': - $colorIdx = 0x1F; - - break; - case '000080': - $colorIdx = 0x20; - - break; - case 'FF00FF': - $colorIdx = 0x21; - - break; - case 'FFFF00': - $colorIdx = 0x22; - - break; - case '00FFFF': - $colorIdx = 0x23; - - break; - case '800080': - $colorIdx = 0x24; - - break; - case '800000': - $colorIdx = 0x25; - - break; - case '008080': - $colorIdx = 0x26; - - break; - case '0000FF': - $colorIdx = 0x27; - - break; - case '00CCFF': - $colorIdx = 0x28; - - break; - case 'CCFFFF': - $colorIdx = 0x29; - - break; - case 'CCFFCC': - $colorIdx = 0x2A; - - break; - case 'FFFF99': - $colorIdx = 0x2B; - - break; - case '99CCFF': - $colorIdx = 0x2C; - - break; - case 'FF99CC': - $colorIdx = 0x2D; - - break; - case 'CC99FF': - $colorIdx = 0x2E; - - break; - case 'FFCC99': - $colorIdx = 0x2F; - - break; - case '3366FF': - $colorIdx = 0x30; - - break; - case '33CCCC': - $colorIdx = 0x31; - - break; - case '99CC00': - $colorIdx = 0x32; - - break; - case 'FFCC00': - $colorIdx = 0x33; - - break; - case 'FF9900': - $colorIdx = 0x34; - - break; - case 'FF6600': - $colorIdx = 0x35; - - break; - case '666699': - $colorIdx = 0x36; - - break; - case '969696': - $colorIdx = 0x37; - - break; - case '003366': - $colorIdx = 0x38; - - break; - case '339966': - $colorIdx = 0x39; - - break; - case '003300': - $colorIdx = 0x3A; - - break; - case '333300': - $colorIdx = 0x3B; - - break; - case '993300': - $colorIdx = 0x3C; - - break; - case '993366': - $colorIdx = 0x3D; - - break; - case '333399': - $colorIdx = 0x3E; - - break; - case '333333': - $colorIdx = 0x3F; - - break; - default: - $colorIdx = 0x00; - - break; - } - $dataBlockFont .= pack('V', $colorIdx); - // Not used (4) - $dataBlockFont .= pack('V', 0x00000000); - // Options flags for modified font attributes - $optionsFlags = 0; - $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0); - $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); - $optionsFlags |= (1 == 1 ? 0x00000008 : 0); - $optionsFlags |= (1 == 1 ? 0x00000010 : 0); - $optionsFlags |= (1 == 0 ? 0x00000020 : 0); - $optionsFlags |= (1 == 1 ? 0x00000080 : 0); - $dataBlockFont .= pack('V', $optionsFlags); - // Escapement type - $dataBlockFont .= pack('V', $fontEscapement); - // Underline type - $dataBlockFont .= pack('V', $fontUnderline); - // Always - $dataBlockFont .= pack('V', 0x00000000); - // Always - $dataBlockFont .= pack('V', 0x00000000); - // Not used (8) - $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); - // Always - $dataBlockFont .= pack('v', 0x0001); - } - if ($bFormatAlign == 1) { - $blockAlign = 0; - // Alignment and text break - switch ($conditional->getStyle()->getAlignment()->getHorizontal()) { - case Alignment::HORIZONTAL_GENERAL: - $blockAlign = 0; - - break; - case Alignment::HORIZONTAL_LEFT: - $blockAlign = 1; - - break; - case Alignment::HORIZONTAL_RIGHT: - $blockAlign = 3; - - break; - case Alignment::HORIZONTAL_CENTER: - $blockAlign = 2; - - break; - case Alignment::HORIZONTAL_CENTER_CONTINUOUS: - $blockAlign = 6; - - break; - case Alignment::HORIZONTAL_JUSTIFY: - $blockAlign = 5; - - break; - } - if ($conditional->getStyle()->getAlignment()->getWrapText() == true) { - $blockAlign |= 1 << 3; - } else { - $blockAlign |= 0 << 3; - } - switch ($conditional->getStyle()->getAlignment()->getVertical()) { - case Alignment::VERTICAL_BOTTOM: - $blockAlign = 2 << 4; - - break; - case Alignment::VERTICAL_TOP: - $blockAlign = 0 << 4; - - break; - case Alignment::VERTICAL_CENTER: - $blockAlign = 1 << 4; - - break; - case Alignment::VERTICAL_JUSTIFY: - $blockAlign = 3 << 4; - - break; - } - $blockAlign |= 0 << 7; - - // Text rotation angle - $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); - - // Indentation - $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); - if ($conditional->getStyle()->getAlignment()->getShrinkToFit() == true) { - $blockIndent |= 1 << 4; - } else { - $blockIndent |= 0 << 4; - } - $blockIndent |= 0 << 6; - - // Relative indentation - $blockIndentRelative = 255; - - $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); - } - if ($bFormatBorder == 1) { - $blockLineStyle = 0; - switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D; - - break; - } - switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 4; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 4; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 4; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 4; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 4; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 4; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 4; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 4; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 4; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 4; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 4; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 4; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 4; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 4; - - break; - } - switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 8; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 8; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 8; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 8; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 8; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 8; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 8; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 8; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 8; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 8; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 8; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 8; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 8; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 8; - - break; - } - switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockLineStyle |= 0x00 << 12; - - break; - case Border::BORDER_THIN: - $blockLineStyle |= 0x01 << 12; - - break; - case Border::BORDER_MEDIUM: - $blockLineStyle |= 0x02 << 12; - - break; - case Border::BORDER_DASHED: - $blockLineStyle |= 0x03 << 12; - - break; - case Border::BORDER_DOTTED: - $blockLineStyle |= 0x04 << 12; - - break; - case Border::BORDER_THICK: - $blockLineStyle |= 0x05 << 12; - - break; - case Border::BORDER_DOUBLE: - $blockLineStyle |= 0x06 << 12; - - break; - case Border::BORDER_HAIR: - $blockLineStyle |= 0x07 << 12; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockLineStyle |= 0x08 << 12; - - break; - case Border::BORDER_DASHDOT: - $blockLineStyle |= 0x09 << 12; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockLineStyle |= 0x0A << 12; - - break; - case Border::BORDER_DASHDOTDOT: - $blockLineStyle |= 0x0B << 12; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockLineStyle |= 0x0C << 12; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockLineStyle |= 0x0D << 12; - - break; - } - //@todo writeCFRule() => $blockLineStyle => Index Color for left line - //@todo writeCFRule() => $blockLineStyle => Index Color for right line - //@todo writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off - //@todo writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off - $blockColor = 0; - //@todo writeCFRule() => $blockColor => Index Color for top line - //@todo writeCFRule() => $blockColor => Index Color for bottom line - //@todo writeCFRule() => $blockColor => Index Color for diagonal line - switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()) { - case Border::BORDER_NONE: - $blockColor |= 0x00 << 21; - - break; - case Border::BORDER_THIN: - $blockColor |= 0x01 << 21; - - break; - case Border::BORDER_MEDIUM: - $blockColor |= 0x02 << 21; - - break; - case Border::BORDER_DASHED: - $blockColor |= 0x03 << 21; - - break; - case Border::BORDER_DOTTED: - $blockColor |= 0x04 << 21; - - break; - case Border::BORDER_THICK: - $blockColor |= 0x05 << 21; - - break; - case Border::BORDER_DOUBLE: - $blockColor |= 0x06 << 21; - - break; - case Border::BORDER_HAIR: - $blockColor |= 0x07 << 21; - - break; - case Border::BORDER_MEDIUMDASHED: - $blockColor |= 0x08 << 21; - - break; - case Border::BORDER_DASHDOT: - $blockColor |= 0x09 << 21; - - break; - case Border::BORDER_MEDIUMDASHDOT: - $blockColor |= 0x0A << 21; - - break; - case Border::BORDER_DASHDOTDOT: - $blockColor |= 0x0B << 21; - - break; - case Border::BORDER_MEDIUMDASHDOTDOT: - $blockColor |= 0x0C << 21; - - break; - case Border::BORDER_SLANTDASHDOT: - $blockColor |= 0x0D << 21; - - break; - } - $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); - } - if ($bFormatFill == 1) { - // Fill Patern Style - $blockFillPatternStyle = 0; - switch ($conditional->getStyle()->getFill()->getFillType()) { - case Fill::FILL_NONE: - $blockFillPatternStyle = 0x00; - - break; - case Fill::FILL_SOLID: - $blockFillPatternStyle = 0x01; - - break; - case Fill::FILL_PATTERN_MEDIUMGRAY: - $blockFillPatternStyle = 0x02; - - break; - case Fill::FILL_PATTERN_DARKGRAY: - $blockFillPatternStyle = 0x03; - - break; - case Fill::FILL_PATTERN_LIGHTGRAY: - $blockFillPatternStyle = 0x04; - - break; - case Fill::FILL_PATTERN_DARKHORIZONTAL: - $blockFillPatternStyle = 0x05; - - break; - case Fill::FILL_PATTERN_DARKVERTICAL: - $blockFillPatternStyle = 0x06; - - break; - case Fill::FILL_PATTERN_DARKDOWN: - $blockFillPatternStyle = 0x07; - - break; - case Fill::FILL_PATTERN_DARKUP: - $blockFillPatternStyle = 0x08; - - break; - case Fill::FILL_PATTERN_DARKGRID: - $blockFillPatternStyle = 0x09; - - break; - case Fill::FILL_PATTERN_DARKTRELLIS: - $blockFillPatternStyle = 0x0A; - - break; - case Fill::FILL_PATTERN_LIGHTHORIZONTAL: - $blockFillPatternStyle = 0x0B; - - break; - case Fill::FILL_PATTERN_LIGHTVERTICAL: - $blockFillPatternStyle = 0x0C; - - break; - case Fill::FILL_PATTERN_LIGHTDOWN: - $blockFillPatternStyle = 0x0D; - - break; - case Fill::FILL_PATTERN_LIGHTUP: - $blockFillPatternStyle = 0x0E; - - break; - case Fill::FILL_PATTERN_LIGHTGRID: - $blockFillPatternStyle = 0x0F; - - break; - case Fill::FILL_PATTERN_LIGHTTRELLIS: - $blockFillPatternStyle = 0x10; - - break; - case Fill::FILL_PATTERN_GRAY125: - $blockFillPatternStyle = 0x11; - - break; - case Fill::FILL_PATTERN_GRAY0625: - $blockFillPatternStyle = 0x12; - - break; - case Fill::FILL_GRADIENT_LINEAR: - $blockFillPatternStyle = 0x00; - - break; // does not exist in BIFF8 - case Fill::FILL_GRADIENT_PATH: - $blockFillPatternStyle = 0x00; - - break; // does not exist in BIFF8 - default: - $blockFillPatternStyle = 0x00; - - break; - } - // Color - switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) { - case '000000': - $colorIdxBg = 0x08; - - break; - case 'FFFFFF': - $colorIdxBg = 0x09; - - break; - case 'FF0000': - $colorIdxBg = 0x0A; - - break; - case '00FF00': - $colorIdxBg = 0x0B; - - break; - case '0000FF': - $colorIdxBg = 0x0C; - - break; - case 'FFFF00': - $colorIdxBg = 0x0D; - - break; - case 'FF00FF': - $colorIdxBg = 0x0E; - - break; - case '00FFFF': - $colorIdxBg = 0x0F; - - break; - case '800000': - $colorIdxBg = 0x10; - - break; - case '008000': - $colorIdxBg = 0x11; - - break; - case '000080': - $colorIdxBg = 0x12; - - break; - case '808000': - $colorIdxBg = 0x13; - - break; - case '800080': - $colorIdxBg = 0x14; - - break; - case '008080': - $colorIdxBg = 0x15; - - break; - case 'C0C0C0': - $colorIdxBg = 0x16; - - break; - case '808080': - $colorIdxBg = 0x17; - - break; - case '9999FF': - $colorIdxBg = 0x18; - - break; - case '993366': - $colorIdxBg = 0x19; - - break; - case 'FFFFCC': - $colorIdxBg = 0x1A; - - break; - case 'CCFFFF': - $colorIdxBg = 0x1B; - - break; - case '660066': - $colorIdxBg = 0x1C; - - break; - case 'FF8080': - $colorIdxBg = 0x1D; - - break; - case '0066CC': - $colorIdxBg = 0x1E; - - break; - case 'CCCCFF': - $colorIdxBg = 0x1F; - - break; - case '000080': - $colorIdxBg = 0x20; - - break; - case 'FF00FF': - $colorIdxBg = 0x21; - - break; - case 'FFFF00': - $colorIdxBg = 0x22; - - break; - case '00FFFF': - $colorIdxBg = 0x23; - - break; - case '800080': - $colorIdxBg = 0x24; - - break; - case '800000': - $colorIdxBg = 0x25; - - break; - case '008080': - $colorIdxBg = 0x26; - - break; - case '0000FF': - $colorIdxBg = 0x27; - - break; - case '00CCFF': - $colorIdxBg = 0x28; - - break; - case 'CCFFFF': - $colorIdxBg = 0x29; - - break; - case 'CCFFCC': - $colorIdxBg = 0x2A; - - break; - case 'FFFF99': - $colorIdxBg = 0x2B; - - break; - case '99CCFF': - $colorIdxBg = 0x2C; - - break; - case 'FF99CC': - $colorIdxBg = 0x2D; - - break; - case 'CC99FF': - $colorIdxBg = 0x2E; - - break; - case 'FFCC99': - $colorIdxBg = 0x2F; - - break; - case '3366FF': - $colorIdxBg = 0x30; - - break; - case '33CCCC': - $colorIdxBg = 0x31; - - break; - case '99CC00': - $colorIdxBg = 0x32; - - break; - case 'FFCC00': - $colorIdxBg = 0x33; - - break; - case 'FF9900': - $colorIdxBg = 0x34; - - break; - case 'FF6600': - $colorIdxBg = 0x35; - - break; - case '666699': - $colorIdxBg = 0x36; - - break; - case '969696': - $colorIdxBg = 0x37; - - break; - case '003366': - $colorIdxBg = 0x38; - - break; - case '339966': - $colorIdxBg = 0x39; - - break; - case '003300': - $colorIdxBg = 0x3A; - - break; - case '333300': - $colorIdxBg = 0x3B; - - break; - case '993300': - $colorIdxBg = 0x3C; - - break; - case '993366': - $colorIdxBg = 0x3D; - - break; - case '333399': - $colorIdxBg = 0x3E; - - break; - case '333333': - $colorIdxBg = 0x3F; - - break; - default: - $colorIdxBg = 0x41; - - break; - } - // Fg Color - switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) { - case '000000': - $colorIdxFg = 0x08; - - break; - case 'FFFFFF': - $colorIdxFg = 0x09; - - break; - case 'FF0000': - $colorIdxFg = 0x0A; - - break; - case '00FF00': - $colorIdxFg = 0x0B; - - break; - case '0000FF': - $colorIdxFg = 0x0C; - - break; - case 'FFFF00': - $colorIdxFg = 0x0D; - - break; - case 'FF00FF': - $colorIdxFg = 0x0E; - - break; - case '00FFFF': - $colorIdxFg = 0x0F; - - break; - case '800000': - $colorIdxFg = 0x10; - - break; - case '008000': - $colorIdxFg = 0x11; - - break; - case '000080': - $colorIdxFg = 0x12; - - break; - case '808000': - $colorIdxFg = 0x13; - - break; - case '800080': - $colorIdxFg = 0x14; - - break; - case '008080': - $colorIdxFg = 0x15; - - break; - case 'C0C0C0': - $colorIdxFg = 0x16; - - break; - case '808080': - $colorIdxFg = 0x17; - - break; - case '9999FF': - $colorIdxFg = 0x18; - - break; - case '993366': - $colorIdxFg = 0x19; - - break; - case 'FFFFCC': - $colorIdxFg = 0x1A; - - break; - case 'CCFFFF': - $colorIdxFg = 0x1B; - - break; - case '660066': - $colorIdxFg = 0x1C; - - break; - case 'FF8080': - $colorIdxFg = 0x1D; - - break; - case '0066CC': - $colorIdxFg = 0x1E; - - break; - case 'CCCCFF': - $colorIdxFg = 0x1F; - - break; - case '000080': - $colorIdxFg = 0x20; - - break; - case 'FF00FF': - $colorIdxFg = 0x21; - - break; - case 'FFFF00': - $colorIdxFg = 0x22; - - break; - case '00FFFF': - $colorIdxFg = 0x23; - - break; - case '800080': - $colorIdxFg = 0x24; - - break; - case '800000': - $colorIdxFg = 0x25; - - break; - case '008080': - $colorIdxFg = 0x26; - - break; - case '0000FF': - $colorIdxFg = 0x27; - - break; - case '00CCFF': - $colorIdxFg = 0x28; - - break; - case 'CCFFFF': - $colorIdxFg = 0x29; - - break; - case 'CCFFCC': - $colorIdxFg = 0x2A; - - break; - case 'FFFF99': - $colorIdxFg = 0x2B; - - break; - case '99CCFF': - $colorIdxFg = 0x2C; - - break; - case 'FF99CC': - $colorIdxFg = 0x2D; - - break; - case 'CC99FF': - $colorIdxFg = 0x2E; - - break; - case 'FFCC99': - $colorIdxFg = 0x2F; - - break; - case '3366FF': - $colorIdxFg = 0x30; - - break; - case '33CCCC': - $colorIdxFg = 0x31; - - break; - case '99CC00': - $colorIdxFg = 0x32; - - break; - case 'FFCC00': - $colorIdxFg = 0x33; - - break; - case 'FF9900': - $colorIdxFg = 0x34; - - break; - case 'FF6600': - $colorIdxFg = 0x35; - - break; - case '666699': - $colorIdxFg = 0x36; - - break; - case '969696': - $colorIdxFg = 0x37; - - break; - case '003366': - $colorIdxFg = 0x38; - - break; - case '339966': - $colorIdxFg = 0x39; - - break; - case '003300': - $colorIdxFg = 0x3A; - - break; - case '333300': - $colorIdxFg = 0x3B; - - break; - case '993300': - $colorIdxFg = 0x3C; - - break; - case '993366': - $colorIdxFg = 0x3D; - - break; - case '333399': - $colorIdxFg = 0x3E; - - break; - case '333333': - $colorIdxFg = 0x3F; - - break; - default: - $colorIdxFg = 0x40; - - break; - } - $dataBlockFill = pack('v', $blockFillPatternStyle); - $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); - } - if ($bFormatProt == 1) { - $dataBlockProtection = 0; - if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { - $dataBlockProtection = 1; - } - if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { - $dataBlockProtection = 1 << 1; - } - } - - $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); - if ($bFormatFont == 1) { // Block Formatting : OK - $data .= $dataBlockFont; - } - if ($bFormatAlign == 1) { - $data .= $dataBlockAlign; - } - if ($bFormatBorder == 1) { - $data .= $dataBlockBorder; - } - if ($bFormatFill == 1) { // Block Formatting : OK - $data .= $dataBlockFill; - } - if ($bFormatProt == 1) { - $data .= $dataBlockProtection; - } - if ($operand1 !== null) { - $data .= $operand1; - } - if ($operand2 !== null) { - $data .= $operand2; - } - $header = pack('vv', $record, strlen($data)); - $this->append($header . $data); + return true; } - /** - * Write CFHeader record. - */ - private function writeCFHeader() + private function getDataBlockProtection(Conditional $conditional): int { - $record = 0x01B0; // Record identifier - $length = 0x0016; // Bytes to follow - - $numColumnMin = null; - $numColumnMax = null; - $numRowMin = null; - $numRowMax = null; - $arrConditional = []; - foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { - foreach ($conditionalStyles as $conditional) { - if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION - || $conditional->getConditionType() == Conditional::CONDITION_CELLIS) { - if (!in_array($conditional->getHashCode(), $arrConditional)) { - $arrConditional[] = $conditional->getHashCode(); - } - // Cells - $arrCoord = Coordinate::coordinateFromString($cellCoordinate); - if (!is_numeric($arrCoord[0])) { - $arrCoord[0] = Coordinate::columnIndexFromString($arrCoord[0]); - } - if ($numColumnMin === null || ($numColumnMin > $arrCoord[0])) { - $numColumnMin = $arrCoord[0]; - } - if ($numColumnMax === null || ($numColumnMax < $arrCoord[0])) { - $numColumnMax = $arrCoord[0]; - } - if ($numRowMin === null || ($numRowMin > $arrCoord[1])) { - $numRowMin = $arrCoord[1]; - } - if ($numRowMax === null || ($numRowMax < $arrCoord[1])) { - $numRowMax = $arrCoord[1]; - } - } - } + $dataBlockProtection = 0; + if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1; + } + if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1 << 1; } - $needRedraw = 1; - $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1); - $header = pack('vv', $record, $length); - $data = pack('vv', count($arrConditional), $needRedraw); - $data .= $cellRange; - $data .= pack('v', 0x0001); - $data .= $cellRange; - $this->append($header . $data); + return $dataBlockProtection; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php index 238fb34c..b2dbc67a 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xls/Xf.php @@ -3,11 +3,12 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xls; use PhpOffice\PhpSpreadsheet\Style\Alignment; -use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; -use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Protection; use PhpOffice\PhpSpreadsheet\Style\Style; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellAlignment; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellBorder; +use PhpOffice\PhpSpreadsheet\Writer\Xls\Style\CellFill; // Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): // ----------------------------------------------------------------------------------------- @@ -115,6 +116,21 @@ class Xf */ private $rightBorderColor; + /** + * @var int + */ + private $diag; + + /** + * @var int + */ + private $diagColor; + + /** + * @var Style + */ + private $style; + /** * Constructor. * @@ -132,14 +148,14 @@ public function __construct(Style $style) $this->foregroundColor = 0x40; $this->backgroundColor = 0x41; - $this->_diag = 0; + $this->diag = 0; $this->bottomBorderColor = 0x40; $this->topBorderColor = 0x40; $this->leftBorderColor = 0x40; $this->rightBorderColor = 0x40; - $this->_diag_color = 0x40; - $this->_style = $style; + $this->diagColor = 0x40; + $this->style = $style; } /** @@ -153,39 +169,39 @@ public function writeXf() if ($this->isStyleXf) { $style = 0xFFF5; } else { - $style = self::mapLocked($this->_style->getProtection()->getLocked()); - $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1; + $style = self::mapLocked($this->style->getProtection()->getLocked()); + $style |= self::mapHidden($this->style->getProtection()->getHidden()) << 1; } // Flags to indicate if attributes have been set. $atr_num = ($this->numberFormatIndex != 0) ? 1 : 0; $atr_fnt = ($this->fontIndex != 0) ? 1 : 0; - $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; - $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || - self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle())) ? 1 : 0; - $atr_pat = (($this->foregroundColor != 0x40) || - ($this->backgroundColor != 0x41) || - self::mapFillType($this->_style->getFill()->getFillType())) ? 1 : 0; - $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked()) - | self::mapHidden($this->_style->getProtection()->getHidden()); + $atr_alc = ((int) $this->style->getAlignment()->getWrapText()) ? 1 : 0; + $atr_bdr = (CellBorder::style($this->style->getBorders()->getBottom()) || + CellBorder::style($this->style->getBorders()->getTop()) || + CellBorder::style($this->style->getBorders()->getLeft()) || + CellBorder::style($this->style->getBorders()->getRight())) ? 1 : 0; + $atr_pat = ($this->foregroundColor != 0x40) ? 1 : 0; + $atr_pat = ($this->backgroundColor != 0x41) ? 1 : $atr_pat; + $atr_pat = CellFill::style($this->style->getFill()) ? 1 : $atr_pat; + $atr_prot = self::mapLocked($this->style->getProtection()->getLocked()) + | self::mapHidden($this->style->getProtection()->getHidden()); // Zero the default border colour if the border has not been set. - if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getBottom()) == 0) { $this->bottomBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getTop()) == 0) { $this->topBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getRight()) == 0) { $this->rightBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) { + if (CellBorder::style($this->style->getBorders()->getLeft()) == 0) { $this->leftBorderColor = 0; } - if (self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) { - $this->_diag_color = 0; + if (CellBorder::style($this->style->getBorders()->getDiagonal()) == 0) { + $this->diagColor = 0; } $record = 0x00E0; // Record identifier @@ -194,9 +210,10 @@ public function writeXf() $ifnt = $this->fontIndex; // Index to FONT record $ifmt = $this->numberFormatIndex; // Index to FORMAT record - $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment - $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; - $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4; + // Alignment + $align = CellAlignment::horizontal($this->style->getAlignment()); + $align |= CellAlignment::wrap($this->style->getAlignment()) << 3; + $align |= CellAlignment::vertical($this->style->getAlignment()) << 4; $align |= $this->textJustLast << 7; $used_attrib = $atr_num << 2; @@ -209,35 +226,35 @@ public function writeXf() $icv = $this->foregroundColor; // fg and bg pattern colors $icv |= $this->backgroundColor << 7; - $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; - $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; + $border1 = CellBorder::style($this->style->getBorders()->getLeft()); // Border line style and color + $border1 |= CellBorder::style($this->style->getBorders()->getRight()) << 4; + $border1 |= CellBorder::style($this->style->getBorders()->getTop()) << 8; + $border1 |= CellBorder::style($this->style->getBorders()->getBottom()) << 12; $border1 |= $this->leftBorderColor << 16; $border1 |= $this->rightBorderColor << 23; - $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection(); + $diagonalDirection = $this->style->getBorders()->getDiagonalDirection(); $diag_tl_to_rb = $diagonalDirection == Borders::DIAGONAL_BOTH - || $diagonalDirection == Borders::DIAGONAL_DOWN; + || $diagonalDirection == Borders::DIAGONAL_DOWN; $diag_tr_to_lb = $diagonalDirection == Borders::DIAGONAL_BOTH - || $diagonalDirection == Borders::DIAGONAL_UP; + || $diagonalDirection == Borders::DIAGONAL_UP; $border1 |= $diag_tl_to_rb << 30; $border1 |= $diag_tr_to_lb << 31; $border2 = $this->topBorderColor; // Border color $border2 |= $this->bottomBorderColor << 7; - $border2 |= $this->_diag_color << 14; - $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; - $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26; + $border2 |= $this->diagColor << 14; + $border2 |= CellBorder::style($this->style->getBorders()->getDiagonal()) << 21; + $border2 |= CellFill::style($this->style->getFill()) << 26; $header = pack('vv', $record, $length); //BIFF8 options: identation, shrinkToFit and text direction - $biff8_options = $this->_style->getAlignment()->getIndent(); - $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4; + $biff8_options = $this->style->getAlignment()->getIndent(); + $biff8_options |= (int) $this->style->getAlignment()->getShrinkToFit() << 4; $data = pack('vvvC', $ifnt, $ifmt, $style, $align); - $data .= pack('CCC', self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); + $data .= pack('CCC', self::mapTextRotation($this->style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); $data .= pack('VVv', $border1, $border2, $icv); return $header . $data; @@ -248,7 +265,7 @@ public function writeXf() * * @param bool $value */ - public function setIsStyleXf($value) + public function setIsStyleXf($value): void { $this->isStyleXf = $value; } @@ -258,7 +275,7 @@ public function setIsStyleXf($value) * * @param int $colorIndex Color index */ - public function setBottomColor($colorIndex) + public function setBottomColor($colorIndex): void { $this->bottomBorderColor = $colorIndex; } @@ -268,7 +285,7 @@ public function setBottomColor($colorIndex) * * @param int $colorIndex Color index */ - public function setTopColor($colorIndex) + public function setTopColor($colorIndex): void { $this->topBorderColor = $colorIndex; } @@ -278,7 +295,7 @@ public function setTopColor($colorIndex) * * @param int $colorIndex Color index */ - public function setLeftColor($colorIndex) + public function setLeftColor($colorIndex): void { $this->leftBorderColor = $colorIndex; } @@ -288,7 +305,7 @@ public function setLeftColor($colorIndex) * * @param int $colorIndex Color index */ - public function setRightColor($colorIndex) + public function setRightColor($colorIndex): void { $this->rightBorderColor = $colorIndex; } @@ -298,9 +315,9 @@ public function setRightColor($colorIndex) * * @param int $colorIndex Color index */ - public function setDiagColor($colorIndex) + public function setDiagColor($colorIndex): void { - $this->_diag_color = $colorIndex; + $this->diagColor = $colorIndex; } /** @@ -308,7 +325,7 @@ public function setDiagColor($colorIndex) * * @param int $colorIndex Color index */ - public function setFgColor($colorIndex) + public function setFgColor($colorIndex): void { $this->foregroundColor = $colorIndex; } @@ -318,7 +335,7 @@ public function setFgColor($colorIndex) * * @param int $colorIndex Color index */ - public function setBgColor($colorIndex) + public function setBgColor($colorIndex): void { $this->backgroundColor = $colorIndex; } @@ -329,7 +346,7 @@ public function setBgColor($colorIndex) * * @param int $numberFormatIndex Index to format record */ - public function setNumberFormatIndex($numberFormatIndex) + public function setNumberFormatIndex($numberFormatIndex): void { $this->numberFormatIndex = $numberFormatIndex; } @@ -339,153 +356,11 @@ public function setNumberFormatIndex($numberFormatIndex) * * @param int $value Font index, note that value 4 does not exist */ - public function setFontIndex($value) + public function setFontIndex($value): void { $this->fontIndex = $value; } - /** - * Map of BIFF2-BIFF8 codes for border styles. - * - * @var array of int - */ - private static $mapBorderStyles = [ - Border::BORDER_NONE => 0x00, - Border::BORDER_THIN => 0x01, - Border::BORDER_MEDIUM => 0x02, - Border::BORDER_DASHED => 0x03, - Border::BORDER_DOTTED => 0x04, - Border::BORDER_THICK => 0x05, - Border::BORDER_DOUBLE => 0x06, - Border::BORDER_HAIR => 0x07, - Border::BORDER_MEDIUMDASHED => 0x08, - Border::BORDER_DASHDOT => 0x09, - Border::BORDER_MEDIUMDASHDOT => 0x0A, - Border::BORDER_DASHDOTDOT => 0x0B, - Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, - Border::BORDER_SLANTDASHDOT => 0x0D, - ]; - - /** - * Map border style. - * - * @param string $borderStyle - * - * @return int - */ - private static function mapBorderStyle($borderStyle) - { - if (isset(self::$mapBorderStyles[$borderStyle])) { - return self::$mapBorderStyles[$borderStyle]; - } - - return 0x00; - } - - /** - * Map of BIFF2-BIFF8 codes for fill types. - * - * @var array of int - */ - private static $mapFillTypes = [ - Fill::FILL_NONE => 0x00, - Fill::FILL_SOLID => 0x01, - Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, - Fill::FILL_PATTERN_DARKGRAY => 0x03, - Fill::FILL_PATTERN_LIGHTGRAY => 0x04, - Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, - Fill::FILL_PATTERN_DARKVERTICAL => 0x06, - Fill::FILL_PATTERN_DARKDOWN => 0x07, - Fill::FILL_PATTERN_DARKUP => 0x08, - Fill::FILL_PATTERN_DARKGRID => 0x09, - Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, - Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, - Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, - Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, - Fill::FILL_PATTERN_LIGHTUP => 0x0E, - Fill::FILL_PATTERN_LIGHTGRID => 0x0F, - Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, - Fill::FILL_PATTERN_GRAY125 => 0x11, - Fill::FILL_PATTERN_GRAY0625 => 0x12, - Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 - Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 - ]; - - /** - * Map fill type. - * - * @param string $fillType - * - * @return int - */ - private static function mapFillType($fillType) - { - if (isset(self::$mapFillTypes[$fillType])) { - return self::$mapFillTypes[$fillType]; - } - - return 0x00; - } - - /** - * Map of BIFF2-BIFF8 codes for horizontal alignment. - * - * @var array of int - */ - private static $mapHAlignments = [ - Alignment::HORIZONTAL_GENERAL => 0, - Alignment::HORIZONTAL_LEFT => 1, - Alignment::HORIZONTAL_CENTER => 2, - Alignment::HORIZONTAL_RIGHT => 3, - Alignment::HORIZONTAL_FILL => 4, - Alignment::HORIZONTAL_JUSTIFY => 5, - Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, - ]; - - /** - * Map to BIFF2-BIFF8 codes for horizontal alignment. - * - * @param string $hAlign - * - * @return int - */ - private function mapHAlign($hAlign) - { - if (isset(self::$mapHAlignments[$hAlign])) { - return self::$mapHAlignments[$hAlign]; - } - - return 0; - } - - /** - * Map of BIFF2-BIFF8 codes for vertical alignment. - * - * @var array of int - */ - private static $mapVAlignments = [ - Alignment::VERTICAL_TOP => 0, - Alignment::VERTICAL_CENTER => 1, - Alignment::VERTICAL_BOTTOM => 2, - Alignment::VERTICAL_JUSTIFY => 3, - ]; - - /** - * Map to BIFF2-BIFF8 codes for vertical alignment. - * - * @param string $vAlign - * - * @return int - */ - private static function mapVAlign($vAlign) - { - if (isset(self::$mapVAlignments[$vAlign])) { - return self::$mapVAlignments[$vAlign]; - } - - return 2; - } - /** * Map to BIFF8 codes for text rotation angle. * @@ -497,15 +372,22 @@ private static function mapTextRotation($textRotation) { if ($textRotation >= 0) { return $textRotation; - } elseif ($textRotation == -165) { - return 255; - } elseif ($textRotation < 0) { - return 90 - $textRotation; } + if ($textRotation == Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) { + return Alignment::TEXTROTATION_STACK_EXCEL; + } + + return 90 - $textRotation; } + private const LOCK_ARRAY = [ + Protection::PROTECTION_INHERIT => 1, + Protection::PROTECTION_PROTECTED => 1, + Protection::PROTECTION_UNPROTECTED => 0, + ]; + /** - * Map locked. + * Map locked values. * * @param string $locked * @@ -513,18 +395,15 @@ private static function mapTextRotation($textRotation) */ private static function mapLocked($locked) { - switch ($locked) { - case Protection::PROTECTION_INHERIT: - return 1; - case Protection::PROTECTION_PROTECTED: - return 1; - case Protection::PROTECTION_UNPROTECTED: - return 0; - default: - return 1; - } + return array_key_exists($locked, self::LOCK_ARRAY) ? self::LOCK_ARRAY[$locked] : 1; } + private const HIDDEN_ARRAY = [ + Protection::PROTECTION_INHERIT => 0, + Protection::PROTECTION_PROTECTED => 1, + Protection::PROTECTION_UNPROTECTED => 0, + ]; + /** * Map hidden. * @@ -534,15 +413,6 @@ private static function mapLocked($locked) */ private static function mapHidden($hidden) { - switch ($hidden) { - case Protection::PROTECTION_INHERIT: - return 0; - case Protection::PROTECTION_PROTECTED: - return 1; - case Protection::PROTECTION_UNPROTECTED: - return 0; - default: - return 0; - } + return array_key_exists($hidden, self::HIDDEN_ARRAY) ? self::HIDDEN_ARRAY[$hidden] : 0; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php index 1fa59e51..5aca5117 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx.php @@ -5,8 +5,13 @@ use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\HashTable; -use PhpOffice\PhpSpreadsheet\Shared\File; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Style\Borders; +use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\Fill; +use PhpOffice\PhpSpreadsheet\Style\Font; +use PhpOffice\PhpSpreadsheet\Style\NumberFormat; +use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; @@ -20,10 +25,14 @@ use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style; +use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Table; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook; use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet; use ZipArchive; +use ZipStream\Exception\OverflowException; +use ZipStream\Option\Archive; +use ZipStream\ZipStream; class Xlsx extends BaseWriter { @@ -34,13 +43,6 @@ class Xlsx extends BaseWriter */ private $office2003compatibility = false; - /** - * Private writer parts. - * - * @var Xlsx\WriterPart[] - */ - private $writerParts = []; - /** * Private Spreadsheet. * @@ -58,384 +60,510 @@ class Xlsx extends BaseWriter /** * Private unique Conditional HashTable. * - * @var HashTable + * @var HashTable */ private $stylesConditionalHashTable; /** * Private unique Style HashTable. * - * @var HashTable + * @var HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ private $styleHashTable; /** * Private unique Fill HashTable. * - * @var HashTable + * @var HashTable */ private $fillHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * - * @var HashTable + * @var HashTable */ private $fontHashTable; /** * Private unique Borders HashTable. * - * @var HashTable + * @var HashTable */ private $bordersHashTable; /** * Private unique NumberFormat HashTable. * - * @var HashTable + * @var HashTable */ private $numFmtHashTable; /** * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * - * @var HashTable + * @var HashTable */ private $drawingHashTable; /** - * Create a new Xlsx Writer. + * Private handle for zip stream. * - * @param Spreadsheet $spreadsheet + * @var ZipStream + */ + private $zip; + + /** + * @var Chart + */ + private $writerPartChart; + + /** + * @var Comments + */ + private $writerPartComments; + + /** + * @var ContentTypes + */ + private $writerPartContentTypes; + + /** + * @var DocProps + */ + private $writerPartDocProps; + + /** + * @var Drawing + */ + private $writerPartDrawing; + + /** + * @var Rels + */ + private $writerPartRels; + + /** + * @var RelsRibbon + */ + private $writerPartRelsRibbon; + + /** + * @var RelsVBA + */ + private $writerPartRelsVBA; + + /** + * @var StringTable + */ + private $writerPartStringTable; + + /** + * @var Style + */ + private $writerPartStyle; + + /** + * @var Theme + */ + private $writerPartTheme; + + /** + * @var Table + */ + private $writerPartTable; + + /** + * @var Workbook + */ + private $writerPartWorkbook; + + /** + * @var Worksheet + */ + private $writerPartWorksheet; + + /** + * Create a new Xlsx Writer. */ public function __construct(Spreadsheet $spreadsheet) { // Assign PhpSpreadsheet $this->setSpreadsheet($spreadsheet); - $writerPartsArray = [ - 'stringtable' => StringTable::class, - 'contenttypes' => ContentTypes::class, - 'docprops' => DocProps::class, - 'rels' => Rels::class, - 'theme' => Theme::class, - 'style' => Style::class, - 'workbook' => Workbook::class, - 'worksheet' => Worksheet::class, - 'drawing' => Drawing::class, - 'comments' => Comments::class, - 'chart' => Chart::class, - 'relsvba' => RelsVBA::class, - 'relsribbonobjects' => RelsRibbon::class, - ]; - - // Initialise writer parts - // and Assign their parent IWriters - foreach ($writerPartsArray as $writer => $class) { - $this->writerParts[$writer] = new $class($this); - } - - $hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable', - 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable', - 'styleHashTable', - ]; + $this->writerPartChart = new Chart($this); + $this->writerPartComments = new Comments($this); + $this->writerPartContentTypes = new ContentTypes($this); + $this->writerPartDocProps = new DocProps($this); + $this->writerPartDrawing = new Drawing($this); + $this->writerPartRels = new Rels($this); + $this->writerPartRelsRibbon = new RelsRibbon($this); + $this->writerPartRelsVBA = new RelsVBA($this); + $this->writerPartStringTable = new StringTable($this); + $this->writerPartStyle = new Style($this); + $this->writerPartTheme = new Theme($this); + $this->writerPartTable = new Table($this); + $this->writerPartWorkbook = new Workbook($this); + $this->writerPartWorksheet = new Worksheet($this); // Set HashTable variables - foreach ($hashTablesArray as $tableName) { - $this->$tableName = new HashTable(); - } + // @phpstan-ignore-next-line + $this->bordersHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->drawingHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->fillHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->fontHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->numFmtHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->styleHashTable = new HashTable(); + // @phpstan-ignore-next-line + $this->stylesConditionalHashTable = new HashTable(); } - /** - * Get writer part. - * - * @param string $pPartName Writer part name - * - * @return \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart - */ - public function getWriterPart($pPartName) + public function getWriterPartChart(): Chart { - if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; - } + return $this->writerPartChart; + } + + public function getWriterPartComments(): Comments + { + return $this->writerPartComments; + } + + public function getWriterPartContentTypes(): ContentTypes + { + return $this->writerPartContentTypes; + } + + public function getWriterPartDocProps(): DocProps + { + return $this->writerPartDocProps; + } + + public function getWriterPartDrawing(): Drawing + { + return $this->writerPartDrawing; + } + + public function getWriterPartRels(): Rels + { + return $this->writerPartRels; + } + + public function getWriterPartRelsRibbon(): RelsRibbon + { + return $this->writerPartRelsRibbon; + } + + public function getWriterPartRelsVBA(): RelsVBA + { + return $this->writerPartRelsVBA; + } + + public function getWriterPartStringTable(): StringTable + { + return $this->writerPartStringTable; + } + + public function getWriterPartStyle(): Style + { + return $this->writerPartStyle; + } + + public function getWriterPartTheme(): Theme + { + return $this->writerPartTheme; + } - return null; + public function getWriterPartTable(): Table + { + return $this->writerPartTable; + } + + public function getWriterPartWorkbook(): Workbook + { + return $this->writerPartWorkbook; + } + + public function getWriterPartWorksheet(): Worksheet + { + return $this->writerPartWorksheet; } /** * Save PhpSpreadsheet to file. * - * @param string $pFilename - * - * @throws WriterException + * @param resource|string $filename */ - public function save($pFilename) + public function save($filename, int $flags = 0): void { - if ($this->spreadSheet !== null) { - // garbage collect - $this->spreadSheet->garbageCollect(); - - // If $pFilename is php://output or php://stdout, make it a temporary file... - $originalFilename = $pFilename; - if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { - $pFilename = @tempnam(File::sysGetTempDir(), 'phpxltmp'); - if ($pFilename == '') { - $pFilename = $originalFilename; + $this->processFlags($flags); + + // garbage collect + $this->pathNames = []; + $this->spreadSheet->garbageCollect(); + + $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); + Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); + $saveDateReturnType = Functions::getReturnDateType(); + Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); + + // Create string lookup table + $this->stringTable = []; + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + $this->stringTable = $this->getWriterPartStringTable()->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); + } + + // Create styles dictionaries + $this->styleHashTable->addFromSource($this->getWriterPartStyle()->allStyles($this->spreadSheet)); + $this->stylesConditionalHashTable->addFromSource($this->getWriterPartStyle()->allConditionalStyles($this->spreadSheet)); + $this->fillHashTable->addFromSource($this->getWriterPartStyle()->allFills($this->spreadSheet)); + $this->fontHashTable->addFromSource($this->getWriterPartStyle()->allFonts($this->spreadSheet)); + $this->bordersHashTable->addFromSource($this->getWriterPartStyle()->allBorders($this->spreadSheet)); + $this->numFmtHashTable->addFromSource($this->getWriterPartStyle()->allNumberFormats($this->spreadSheet)); + + // Create drawing dictionary + $this->drawingHashTable->addFromSource($this->getWriterPartDrawing()->allDrawings($this->spreadSheet)); + + $zipContent = []; + // Add [Content_Types].xml to ZIP file + $zipContent['[Content_Types].xml'] = $this->getWriterPartContentTypes()->writeContentTypes($this->spreadSheet, $this->includeCharts); + + //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) + if ($this->spreadSheet->hasMacros()) { + $macrosCode = $this->spreadSheet->getMacrosCode(); + if ($macrosCode !== null) { + // we have the code ? + $zipContent['xl/vbaProject.bin'] = $macrosCode; //allways in 'xl', allways named vbaProject.bin + if ($this->spreadSheet->hasMacrosCertificate()) { + //signed macros ? + // Yes : add the certificate file and the related rels file + $zipContent['xl/vbaProjectSignature.bin'] = $this->spreadSheet->getMacrosCertificate(); + $zipContent['xl/_rels/vbaProject.bin.rels'] = $this->getWriterPartRelsVBA()->writeVBARelationships($this->spreadSheet); } } + } + //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) + if ($this->spreadSheet->hasRibbon()) { + $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); + $zipContent[$tmpRibbonTarget] = $this->spreadSheet->getRibbonXMLData('data'); + if ($this->spreadSheet->hasRibbonBinObjects()) { + $tmpRootPath = dirname($tmpRibbonTarget) . '/'; + $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write + foreach ($ribbonBinObjects as $aPath => $aContent) { + $zipContent[$tmpRootPath . $aPath] = $aContent; + } + //the rels for files + $zipContent[$tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels'] = $this->getWriterPartRelsRibbon()->writeRibbonRelationships($this->spreadSheet); + } + } - $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); - Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); - $saveDateReturnType = Functions::getReturnDateType(); - Functions::setReturnDateType(Functions::RETURNDATE_EXCEL); + // Add relationships to ZIP file + $zipContent['_rels/.rels'] = $this->getWriterPartRels()->writeRelationships($this->spreadSheet); + $zipContent['xl/_rels/workbook.xml.rels'] = $this->getWriterPartRels()->writeWorkbookRelationships($this->spreadSheet); - // Create string lookup table - $this->stringTable = []; - for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); - } + // Add document properties to ZIP file + $zipContent['docProps/app.xml'] = $this->getWriterPartDocProps()->writeDocPropsApp($this->spreadSheet); + $zipContent['docProps/core.xml'] = $this->getWriterPartDocProps()->writeDocPropsCore($this->spreadSheet); + $customPropertiesPart = $this->getWriterPartDocProps()->writeDocPropsCustom($this->spreadSheet); + if ($customPropertiesPart !== null) { + $zipContent['docProps/custom.xml'] = $customPropertiesPart; + } - // Create styles dictionaries - $this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet)); - $this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet)); - $this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet)); - $this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet)); - $this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet)); - $this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet)); + // Add theme to ZIP file + $zipContent['xl/theme/theme1.xml'] = $this->getWriterPartTheme()->writeTheme($this->spreadSheet); - // Create drawing dictionary - $this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet)); + // Add string table to ZIP file + $zipContent['xl/sharedStrings.xml'] = $this->getWriterPartStringTable()->writeStringTable($this->stringTable); - $zip = new ZipArchive(); + // Add styles to ZIP file + $zipContent['xl/styles.xml'] = $this->getWriterPartStyle()->writeStyles($this->spreadSheet); - if (file_exists($pFilename)) { - unlink($pFilename); - } - // Try opening the ZIP file - if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) { - if ($zip->open($pFilename, ZipArchive::CREATE) !== true) { - throw new WriterException('Could not open ' . $pFilename . ' for writing.'); + // Add workbook to ZIP file + $zipContent['xl/workbook.xml'] = $this->getWriterPartWorkbook()->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas); + + $chartCount = 0; + // Add worksheets + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + $zipContent['xl/worksheets/sheet' . ($i + 1) . '.xml'] = $this->getWriterPartWorksheet()->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts); + if ($this->includeCharts) { + $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); + if (count($charts) > 0) { + foreach ($charts as $chart) { + $zipContent['xl/charts/chart' . ($chartCount + 1) . '.xml'] = $this->getWriterPartChart()->writeChart($chart, $this->preCalculateFormulas); + ++$chartCount; + } } } + } - // Add [Content_Types].xml to ZIP file - $zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts)); - - //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) - if ($this->spreadSheet->hasMacros()) { - $macrosCode = $this->spreadSheet->getMacrosCode(); - if ($macrosCode !== null) { - // we have the code ? - $zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin - if ($this->spreadSheet->hasMacrosCertificate()) { - //signed macros ? - // Yes : add the certificate file and the related rels file - $zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); - $zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); - } + $chartRef1 = 0; + $tableRef1 = 1; + // Add worksheet relationships (drawings, ...) + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + // Add relationships + $zipContent['xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts, $tableRef1); + + // Add unparsedLoadedData + $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); + $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); + if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { + foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { + $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } - //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) - if ($this->spreadSheet->hasRibbon()) { - $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target'); - $zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); - if ($this->spreadSheet->hasRibbonBinObjects()) { - $tmpRootPath = dirname($tmpRibbonTarget) . '/'; - $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write - foreach ($ribbonBinObjects as $aPath => $aContent) { - $zip->addFromString($tmpRootPath . $aPath, $aContent); - } - //the rels for files - $zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); + if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { + foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { + $zipContent[$ctrlProp['filePath']] = $ctrlProp['content']; } } - // Add relationships to ZIP file - $zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet)); - $zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet)); - - // Add document properties to ZIP file - $zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet)); - $zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet)); - $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet); - if ($customPropertiesPart !== null) { - $zip->addFromString('docProps/custom.xml', $customPropertiesPart); + $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + if ($this->includeCharts) { + $chartCount = $this->spreadSheet->getSheet($i)->getChartCount(); } - // Add theme to ZIP file - $zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet)); - - // Add string table to ZIP file - $zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable)); - - // Add styles to ZIP file - $zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet)); - - // Add workbook to ZIP file - $zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas)); - - $chartCount = 0; - // Add worksheets - for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - $zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts)); - if ($this->includeCharts) { - $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); - if (count($charts) > 0) { - foreach ($charts as $chart) { - $zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); - ++$chartCount; - } - } - } + // Add drawing and image relationship parts + if (($drawingCount > 0) || ($chartCount > 0)) { + // Drawing relationships + $zipContent['xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels'] = $this->getWriterPartRels()->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts); + + // Drawings + $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); + } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { + // Drawings + $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $this->getWriterPartDrawing()->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts); } - $chartRef1 = 0; - // Add worksheet relationships (drawings, ...) - for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { - // Add relationships - $zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts)); - - // Add unparsedLoadedData - $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName(); - $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData(); - if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) { - foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) { - $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']); - } - } - if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) { - foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) { - $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']); + // Add unparsed drawings + if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'])) { + foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) { + $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); + if ($drawingFile !== false) { + //$drawingFile = ltrim($drawingFile, '.'); + //$zipContent['xl' . $drawingFile] = $drawingXml; + $zipContent['xl/drawings/drawing' . ($i + 1) . '.xml'] = $drawingXml; } } + } - $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection(); - $drawingCount = count($drawings); - if ($this->includeCharts) { - $chartCount = $this->spreadSheet->getSheet($i)->getChartCount(); - } + // Add comment relationship parts + if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { + // VML Comments relationships + $zipContent['xl/drawings/_rels/vmlDrawing' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeVMLDrawingRelationships($this->spreadSheet->getSheet($i)); - // Add drawing and image relationship parts - if (($drawingCount > 0) || ($chartCount > 0)) { - // Drawing relationships - $zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts)); + // VML Comments + $zipContent['xl/drawings/vmlDrawing' . ($i + 1) . '.vml'] = $this->getWriterPartComments()->writeVMLComments($this->spreadSheet->getSheet($i)); - // Drawings - $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); - } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) { - // Drawings - $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts)); - } + // Comments + $zipContent['xl/comments' . ($i + 1) . '.xml'] = $this->getWriterPartComments()->writeComments($this->spreadSheet->getSheet($i)); - // Add unparsed drawings - if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'])) { - foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['Drawings'] as $relId => $drawingXml) { - $drawingFile = array_search($relId, $unparsedLoadedData['sheets'][$sheetCodeName]['drawingOriginalIds']); - if ($drawingFile !== false) { - $drawingFile = ltrim($drawingFile, '.'); - $zip->addFromString('xl' . $drawingFile, $drawingXml); - } + // Media + foreach ($this->spreadSheet->getSheet($i)->getComments() as $comment) { + if ($comment->hasBackgroundImage()) { + $image = $comment->getBackgroundImage(); + $zipContent['xl/media/' . $image->getMediaFilename()] = $this->processDrawing($image); } } + } - // Add comment relationship parts - if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { - // VML Comments - $zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i))); - - // Comments - $zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i))); - } - - // Add unparsed relationship parts - if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { - foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { - $zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']); - } + // Add unparsed relationship parts + if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'])) { + foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['vmlDrawings'] as $vmlDrawing) { + $zipContent[$vmlDrawing['filePath']] = $vmlDrawing['content']; } + } - // Add header/footer relationship parts - if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { - // VML Drawings - $zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i))); + // Add header/footer relationship parts + if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { + // VML Drawings + $zipContent['xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml'] = $this->getWriterPartDrawing()->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)); - // VML Drawing relationships - $zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i))); + // VML Drawing relationships + $zipContent['xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels'] = $this->getWriterPartRels()->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)); - // Media - foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { - $zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); - } + // Media + foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { + $zipContent['xl/media/' . $image->getIndexedFilename()] = file_get_contents($image->getPath()); } } - // Add media - for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { - if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) { - $imageContents = null; - $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); - if (strpos($imagePath, 'zip://') !== false) { - $imagePath = substr($imagePath, 6); - $imagePathSplitted = explode('#', $imagePath); - - $imageZip = new ZipArchive(); - $imageZip->open($imagePathSplitted[0]); - $imageContents = $imageZip->getFromName($imagePathSplitted[1]); - $imageZip->close(); - unset($imageZip); - } else { - $imageContents = file_get_contents($imagePath); - } + // Add Table parts + $tables = $this->spreadSheet->getSheet($i)->getTableCollection(); + foreach ($tables as $table) { + $zipContent['xl/tables/table' . $tableRef1 . '.xml'] = $this->getWriterPartTable()->writeTable($table, $tableRef1++); + } + } - $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); - } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { - ob_start(); - call_user_func( - $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), - $this->getDrawingHashTable()->getByIndex($i)->getImageResource() - ); - $imageContents = ob_get_contents(); - ob_end_clean(); - - $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + // Add media + for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { + if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) { + $imageContents = null; + $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); + if (strpos($imagePath, 'zip://') !== false) { + $imagePath = substr($imagePath, 6); + $imagePathSplitted = explode('#', $imagePath); + + $imageZip = new ZipArchive(); + $imageZip->open($imagePathSplitted[0]); + $imageContents = $imageZip->getFromName($imagePathSplitted[1]); + $imageZip->close(); + unset($imageZip); + } else { + $imageContents = file_get_contents($imagePath); } + + $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; + } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) { + ob_start(); + /** @var callable */ + $callable = $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(); + call_user_func( + $callable, + $this->getDrawingHashTable()->getByIndex($i)->getImageResource() + ); + $imageContents = ob_get_contents(); + ob_end_clean(); + + $zipContent['xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()] = $imageContents; } + } - Functions::setReturnDateType($saveDateReturnType); - Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); + Functions::setReturnDateType($saveDateReturnType); + Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); - // Close file - if ($zip->close() === false) { - throw new WriterException("Could not close zip file $pFilename."); - } + $this->openFileHandle($filename); - // If a temporary file was used, copy it to the correct file stream - if ($originalFilename != $pFilename) { - if (copy($pFilename, $originalFilename) === false) { - throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename."); - } - @unlink($pFilename); - } - } else { - throw new WriterException('PhpSpreadsheet object unassigned.'); + $options = new Archive(); + $options->setEnableZip64(false); + $options->setOutputStream($this->fileHandle); + + $this->zip = new ZipStream(null, $options); + + $this->addZipFiles($zipContent); + + // Close file + try { + $this->zip->finish(); + } catch (OverflowException $e) { + throw new WriterException('Could not close resource.'); } + + $this->maybeCloseFileHandle(); } /** * Get Spreadsheet object. * - * @throws WriterException - * * @return Spreadsheet */ public function getSpreadsheet() { - if ($this->spreadSheet !== null) { - return $this->spreadSheet; - } - - throw new WriterException('No Spreadsheet object assigned.'); + return $this->spreadSheet; } /** @@ -465,7 +593,7 @@ public function getStringTable() /** * Get Style HashTable. * - * @return HashTable + * @return HashTable<\PhpOffice\PhpSpreadsheet\Style\Style> */ public function getStyleHashTable() { @@ -475,7 +603,7 @@ public function getStyleHashTable() /** * Get Conditional HashTable. * - * @return HashTable + * @return HashTable */ public function getStylesConditionalHashTable() { @@ -485,7 +613,7 @@ public function getStylesConditionalHashTable() /** * Get Fill HashTable. * - * @return HashTable + * @return HashTable */ public function getFillHashTable() { @@ -495,7 +623,7 @@ public function getFillHashTable() /** * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable. * - * @return HashTable + * @return HashTable */ public function getFontHashTable() { @@ -505,7 +633,7 @@ public function getFontHashTable() /** * Get Borders HashTable. * - * @return HashTable + * @return HashTable */ public function getBordersHashTable() { @@ -515,7 +643,7 @@ public function getBordersHashTable() /** * Get NumberFormat HashTable. * - * @return HashTable + * @return HashTable */ public function getNumFmtHashTable() { @@ -525,7 +653,7 @@ public function getNumFmtHashTable() /** * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable. * - * @return HashTable + * @return HashTable */ public function getDrawingHashTable() { @@ -545,14 +673,79 @@ public function getOffice2003Compatibility() /** * Set Office2003 compatibility. * - * @param bool $pValue Office2003 compatibility? + * @param bool $office2003compatibility Office2003 compatibility? * * @return $this */ - public function setOffice2003Compatibility($pValue) + public function setOffice2003Compatibility($office2003compatibility) { - $this->office2003compatibility = $pValue; + $this->office2003compatibility = $office2003compatibility; return $this; } + + private $pathNames = []; + + private function addZipFile(string $path, string $content): void + { + if (!in_array($path, $this->pathNames)) { + $this->pathNames[] = $path; + $this->zip->addFile($path, $content); + } + } + + private function addZipFiles(array $zipContent): void + { + foreach ($zipContent as $path => $content) { + $this->addZipFile($path, $content); + } + } + + /** + * @return mixed + */ + private function processDrawing(WorksheetDrawing $drawing) + { + $data = null; + $filename = $drawing->getPath(); + $imageData = getimagesize($filename); + + if (is_array($imageData)) { + switch ($imageData[2]) { + case 1: // GIF, not supported by BIFF8, we convert to PNG + $image = imagecreatefromgif($filename); + if ($image !== false) { + ob_start(); + imagepng($image); + $data = ob_get_contents(); + ob_end_clean(); + } + + break; + + case 2: // JPEG + $data = file_get_contents($filename); + + break; + + case 3: // PNG + $data = file_get_contents($filename); + + break; + + case 6: // Windows DIB (BMP), we convert to PNG + $image = imagecreatefrombmp($filename); + if ($image !== false) { + ob_start(); + imagepng($image); + $data = ob_get_contents(); + ob_end_clean(); + } + + break; + } + } + + return $data; + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php index c9c3e055..23b78a2f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Chart.php @@ -26,14 +26,11 @@ class Chart extends WriterPart /** * Write charts to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart * @param mixed $calculateCellValues * - * @throws WriterException - * * @return string XML Output */ - public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calculateCellValues = true) + public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $calculateCellValues = true) { $this->calculateCellValues = $calculateCellValues; @@ -46,7 +43,7 @@ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calcu } // Ensure that data series values are up-to-date before we save if ($this->calculateCellValues) { - $pChart->refresh(); + $chart->refresh(); } // XML header @@ -72,22 +69,22 @@ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calcu $objWriter->startElement('c:chart'); - $this->writeTitle($objWriter, $pChart->getTitle()); + $this->writeTitle($objWriter, $chart->getTitle()); $objWriter->startElement('c:autoTitleDeleted'); $objWriter->writeAttribute('val', 0); $objWriter->endElement(); - $this->writePlotArea($objWriter, $pChart->getWorksheet(), $pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines()); + $this->writePlotArea($objWriter, $chart->getPlotArea(), $chart->getXAxisLabel(), $chart->getYAxisLabel(), $chart->getChartAxisX(), $chart->getChartAxisY(), $chart->getMajorGridlines(), $chart->getMinorGridlines()); - $this->writeLegend($objWriter, $pChart->getLegend()); + $this->writeLegend($objWriter, $chart->getLegend()); $objWriter->startElement('c:plotVisOnly'); - $objWriter->writeAttribute('val', (int) $pChart->getPlotVisibleOnly()); + $objWriter->writeAttribute('val', (int) $chart->getPlotVisibleOnly()); $objWriter->endElement(); $objWriter->startElement('c:dispBlanksAs'); - $objWriter->writeAttribute('val', $pChart->getDisplayBlanksAs()); + $objWriter->writeAttribute('val', $chart->getDisplayBlanksAs()); $objWriter->endElement(); $objWriter->startElement('c:showDLblsOverMax'); @@ -106,13 +103,8 @@ public function writeChart(\PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $calcu /** * Write Chart Title. - * - * @param XMLWriter $objWriter XML Writer - * @param Title $title - * - * @throws WriterException */ - private function writeTitle(XMLWriter $objWriter, Title $title = null) + private function writeTitle(XMLWriter $objWriter, ?Title $title = null): void { if ($title === null) { return; @@ -134,7 +126,7 @@ private function writeTitle(XMLWriter $objWriter, Title $title = null) if ((is_array($caption)) && (count($caption) > 0)) { $caption = $caption[0]; } - $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a'); + $this->getParentWriter()->getWriterPartstringtable()->writeRichTextForCharts($objWriter, $caption, 'a'); $objWriter->endElement(); $objWriter->endElement(); @@ -151,13 +143,8 @@ private function writeTitle(XMLWriter $objWriter, Title $title = null) /** * Write Chart Legend. - * - * @param XMLWriter $objWriter XML Writer - * @param Legend $legend - * - * @throws WriterException */ - private function writeLegend(XMLWriter $objWriter, Legend $legend = null) + private function writeLegend(XMLWriter $objWriter, ?Legend $legend = null): void { if ($legend === null) { return; @@ -202,20 +189,8 @@ private function writeLegend(XMLWriter $objWriter, Legend $legend = null) /** * Write Chart Plot Area. - * - * @param XMLWriter $objWriter XML Writer - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pSheet - * @param PlotArea $plotArea - * @param Title $xAxisLabel - * @param Title $yAxisLabel - * @param Axis $xAxis - * @param Axis $yAxis - * @param null|GridLines $majorGridlines - * @param null|GridLines $minorGridlines - * - * @throws WriterException */ - private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pSheet, PlotArea $plotArea, Title $xAxisLabel = null, Title $yAxisLabel = null, Axis $xAxis = null, Axis $yAxis = null, GridLines $majorGridlines = null, GridLines $minorGridlines = null) + private function writePlotArea(XMLWriter $objWriter, PlotArea $plotArea, ?Title $xAxisLabel = null, ?Title $yAxisLabel = null, ?Axis $xAxis = null, ?Axis $yAxis = null, ?GridLines $majorGridlines = null, ?GridLines $minorGridlines = null): void { if ($plotArea === null) { return; @@ -232,10 +207,12 @@ private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\W $chartTypes = self::getChartType($plotArea); $catIsMultiLevelSeries = $valIsMultiLevelSeries = false; $plotGroupingType = ''; + $chartType = null; foreach ($chartTypes as $chartType) { $objWriter->startElement('c:' . $chartType); $groupCount = $plotArea->getPlotGroupCount(); + $plotGroup = null; for ($i = 0; $i < $groupCount; ++$i) { $plotGroup = $plotArea->getPlotGroupByIndex($i); $groupType = $plotGroup->getPlotType(); @@ -257,7 +234,7 @@ private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\W $this->writeDataLabels($objWriter, $layout); - if ($chartType === DataSeries::TYPE_LINECHART) { + if ($chartType === DataSeries::TYPE_LINECHART && $plotGroup) { // Line only, Line3D can't be smoothed $objWriter->startElement('c:smooth'); $objWriter->writeAttribute('val', (int) $plotGroup->getSmoothLine()); @@ -329,10 +306,10 @@ private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\W if ($chartType === DataSeries::TYPE_BUBBLECHART) { $this->writeValueAxis($objWriter, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines); } else { - $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $yAxis); + $this->writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $catIsMultiLevelSeries, $xAxis); } - $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $majorGridlines, $minorGridlines); + $this->writeValueAxis($objWriter, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $yAxis, $majorGridlines, $minorGridlines); } $objWriter->endElement(); @@ -340,11 +317,8 @@ private function writePlotArea(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\W /** * Write Data Labels. - * - * @param XMLWriter $objWriter XML Writer - * @param \PhpOffice\PhpSpreadsheet\Chart\Layout $chartLayout Chart layout */ - private function writeDataLabels(XMLWriter $objWriter, Layout $chartLayout = null) + private function writeDataLabels(XMLWriter $objWriter, ?Layout $chartLayout = null): void { $objWriter->startElement('c:dLbls'); @@ -389,16 +363,11 @@ private function writeDataLabels(XMLWriter $objWriter, Layout $chartLayout = nul /** * Write Category Axis. * - * @param XMLWriter $objWriter XML Writer - * @param Title $xAxisLabel * @param string $id1 * @param string $id2 * @param bool $isMultiLevelSeries - * @param Axis $yAxis - * - * @throws WriterException */ - private function writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $isMultiLevelSeries, Axis $yAxis) + private function writeCategoryAxis(XMLWriter $objWriter, ?Title $xAxisLabel, $id1, $id2, $isMultiLevelSeries, Axis $yAxis): void { $objWriter->startElement('c:catAx'); @@ -509,19 +478,12 @@ private function writeCategoryAxis($objWriter, $xAxisLabel, $id1, $id2, $isMulti /** * Write Value Axis. * - * @param XMLWriter $objWriter XML Writer - * @param Title $yAxisLabel - * @param string $groupType Chart type + * @param null|string $groupType Chart type * @param string $id1 * @param string $id2 * @param bool $isMultiLevelSeries - * @param Axis $xAxis - * @param GridLines $majorGridlines - * @param GridLines $minorGridlines - * - * @throws WriterException */ - private function writeValueAxis($objWriter, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, Axis $xAxis, GridLines $majorGridlines, GridLines $minorGridlines) + private function writeValueAxis(XMLWriter $objWriter, ?Title $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, Axis $xAxis, GridLines $majorGridlines, GridLines $minorGridlines): void { $objWriter->startElement('c:valAx'); @@ -997,13 +959,9 @@ private function writeValueAxis($objWriter, $yAxisLabel, $groupType, $id1, $id2, /** * Get the data series type(s) for a chart plot series. * - * @param PlotArea $plotArea - * - * @throws WriterException - * - * @return array|string + * @return string[] */ - private static function getChartType($plotArea) + private static function getChartType(PlotArea $plotArea): array { $groupCount = $plotArea->getPlotGroupCount(); @@ -1026,13 +984,10 @@ private static function getChartType($plotArea) /** * Method writing plot series values. * - * @param XMLWriter $objWriter XML Writer - * @param int $val value for idx (default: 3) - * @param string $fillColor hex color (default: FF9900) - * - * @return XMLWriter XML Writer + * @param int $val value for idx (default: 3) + * @param string $fillColor hex color (default: FF9900) */ - private function writePlotSeriesValuesElement($objWriter, $val = 3, $fillColor = 'FF9900') + private function writePlotSeriesValuesElement(XMLWriter $objWriter, $val = 3, $fillColor = 'FF9900'): void { $objWriter->startElement('c:dPt'); $objWriter->startElement('c:idx'); @@ -1051,23 +1006,17 @@ private function writePlotSeriesValuesElement($objWriter, $val = 3, $fillColor = $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); - - return $objWriter; } /** * Write Plot Group (series of related plots). * - * @param DataSeries $plotGroup * @param string $groupType Type of plot for dataseries - * @param XMLWriter $objWriter XML Writer - * @param bool &$catIsMultiLevelSeries Is category a multi-series category - * @param bool &$valIsMultiLevelSeries Is value set a multi-series set - * @param string &$plotGroupingType Type of grouping for multi-series values - * - * @throws WriterException + * @param bool $catIsMultiLevelSeries Is category a multi-series category + * @param bool $valIsMultiLevelSeries Is value set a multi-series set + * @param string $plotGroupingType Type of grouping for multi-series values */ - private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType) + private function writePlotGroup(?DataSeries $plotGroup, $groupType, XMLWriter $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType): void { if ($plotGroup === null) { return; @@ -1104,11 +1053,12 @@ private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMulti } } + $plotSeriesIdx = 0; foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { $objWriter->startElement('c:ser'); $plotLabel = $plotGroup->getPlotLabelByIndex($plotSeriesIdx); - if ($plotLabel) { + if ($plotLabel && $groupType !== DataSeries::TYPE_LINECHART) { $fillColor = $plotLabel->getFillColor(); if ($fillColor !== null && !is_array($fillColor)) { $objWriter->startElement('c:spPr'); @@ -1166,6 +1116,15 @@ private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMulti if ($groupType == DataSeries::TYPE_STOCKCHART) { $objWriter->startElement('a:noFill'); $objWriter->endElement(); + } elseif ($plotLabel) { + $fillColor = $plotLabel->getFillColor(); + if (is_string($fillColor)) { + $objWriter->startElement('a:solidFill'); + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $fillColor); + $objWriter->endElement(); + $objWriter->endElement(); + } } $objWriter->endElement(); $objWriter->endElement(); @@ -1247,11 +1206,8 @@ private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMulti /** * Write Plot Series Label. - * - * @param DataSeriesValues $plotSeriesLabel - * @param XMLWriter $objWriter XML Writer */ - private function writePlotSeriesLabel($plotSeriesLabel, $objWriter) + private function writePlotSeriesLabel(?DataSeriesValues $plotSeriesLabel, XMLWriter $objWriter): void { if ($plotSeriesLabel === null) { return; @@ -1281,12 +1237,10 @@ private function writePlotSeriesLabel($plotSeriesLabel, $objWriter) /** * Write Plot Series Values. * - * @param DataSeriesValues $plotSeriesValues - * @param XMLWriter $objWriter XML Writer * @param string $groupType Type of plot for dataseries * @param string $dataType Datatype of series values */ - private function writePlotSeriesValues($plotSeriesValues, XMLWriter $objWriter, $groupType, $dataType = 'str') + private function writePlotSeriesValues(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter, $groupType, $dataType = 'str'): void { if ($plotSeriesValues === null) { return; @@ -1372,11 +1326,8 @@ private function writePlotSeriesValues($plotSeriesValues, XMLWriter $objWriter, /** * Write Bubble Chart Details. - * - * @param DataSeriesValues $plotSeriesValues - * @param XMLWriter $objWriter XML Writer */ - private function writeBubbles($plotSeriesValues, $objWriter) + private function writeBubbles(?DataSeriesValues $plotSeriesValues, XMLWriter $objWriter): void { if ($plotSeriesValues === null) { return; @@ -1417,11 +1368,8 @@ private function writeBubbles($plotSeriesValues, $objWriter) /** * Write Layout. - * - * @param XMLWriter $objWriter XML Writer - * @param Layout $layout */ - private function writeLayout(XMLWriter $objWriter, Layout $layout = null) + private function writeLayout(XMLWriter $objWriter, ?Layout $layout = null): void { $objWriter->startElement('c:layout'); @@ -1485,10 +1433,8 @@ private function writeLayout(XMLWriter $objWriter, Layout $layout = null) /** * Write Alternate Content block. - * - * @param XMLWriter $objWriter XML Writer */ - private function writeAlternateContent($objWriter) + private function writeAlternateContent(XMLWriter $objWriter): void { $objWriter->startElement('mc:AlternateContent'); $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); @@ -1513,10 +1459,8 @@ private function writeAlternateContent($objWriter) /** * Write Printer Settings. - * - * @param XMLWriter $objWriter XML Writer */ - private function writePrintSettings($objWriter) + private function writePrintSettings(XMLWriter $objWriter): void { $objWriter->startElement('c:printSettings'); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php index a95298af..ea0f1faa 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Comments.php @@ -11,13 +11,9 @@ class Comments extends WriterPart /** * Write comments to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet) + public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; @@ -31,7 +27,7 @@ public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWo $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Comments cache - $comments = $pWorksheet->getComments(); + $comments = $worksheet->getComments(); // Authors cache $authors = []; @@ -69,23 +65,20 @@ public function writeComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWo /** * Write comment to XML format. * - * @param XMLWriter $objWriter XML Writer - * @param string $pCellReference Cell reference - * @param Comment $pComment Comment - * @param array $pAuthors Array of authors - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception + * @param string $cellReference Cell reference + * @param Comment $comment Comment + * @param array $authors Array of authors */ - private function writeComment(XMLWriter $objWriter, $pCellReference, Comment $pComment, array $pAuthors) + private function writeComment(XMLWriter $objWriter, $cellReference, Comment $comment, array $authors): void { // comment $objWriter->startElement('comment'); - $objWriter->writeAttribute('ref', $pCellReference); - $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]); + $objWriter->writeAttribute('ref', $cellReference); + $objWriter->writeAttribute('authorId', $authors[$comment->getAuthor()]); // text $objWriter->startElement('text'); - $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); + $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $comment->getText()); $objWriter->endElement(); $objWriter->endElement(); @@ -94,13 +87,9 @@ private function writeComment(XMLWriter $objWriter, $pCellReference, Comment $pC /** * Write VML comments to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ - public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet) + public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; @@ -114,7 +103,7 @@ public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $ $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Comments cache - $comments = $pWorksheet->getComments(); + $comments = $worksheet->getComments(); // xml $objWriter->startElement('xml'); @@ -168,15 +157,13 @@ public function writeVMLComments(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $ /** * Write VML comment to XML format. * - * @param XMLWriter $objWriter XML Writer - * @param string $pCellReference Cell reference, eg: 'A1' - * @param Comment $pComment Comment + * @param string $cellReference Cell reference, eg: 'A1' + * @param Comment $comment Comment */ - private function writeVMLComment(XMLWriter $objWriter, $pCellReference, Comment $pComment) + private function writeVMLComment(XMLWriter $objWriter, $cellReference, Comment $comment): void { // Metadata - [$column, $row] = Coordinate::coordinateFromString($pCellReference); - $column = Coordinate::columnIndexFromString($column); + [$column, $row] = Coordinate::indexesFromString($cellReference); $id = 1024 + $column + $row; $id = substr($id, 0, 4); @@ -184,13 +171,19 @@ private function writeVMLComment(XMLWriter $objWriter, $pCellReference, Comment $objWriter->startElement('v:shape'); $objWriter->writeAttribute('id', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t202'); - $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden')); - $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $comment->getMarginLeft() . ';margin-top:' . $comment->getMarginTop() . ';width:' . $comment->getWidth() . ';height:' . $comment->getHeight() . ';z-index:1;visibility:' . ($comment->getVisible() ? 'visible' : 'hidden')); + $objWriter->writeAttribute('fillcolor', '#' . $comment->getFillColor()->getRGB()); $objWriter->writeAttribute('o:insetmode', 'auto'); // v:fill $objWriter->startElement('v:fill'); - $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('color2', '#' . $comment->getFillColor()->getRGB()); + if ($comment->hasBackgroundImage()) { + $bgImage = $comment->getBackgroundImage(); + $objWriter->writeAttribute('o:relid', 'rId' . $bgImage->getImageIndex()); + $objWriter->writeAttribute('o:title', $bgImage->getName()); + $objWriter->writeAttribute('type', 'frame'); + } $objWriter->endElement(); // v:shadow diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php index 6b22d713..acb85b57 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/ContentTypes.php @@ -13,11 +13,8 @@ class ContentTypes extends WriterPart /** * Write content types to XML format. * - * @param Spreadsheet $spreadsheet * @param bool $includeCharts Flag indicating if we should include drawing details for charts * - * @throws WriterException - * * @return string XML Output */ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = false) @@ -88,6 +85,16 @@ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = fal // Shared strings $this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); + // Table + $table = 1; + for ($i = 0; $i < $sheetCount; ++$i) { + $tableCount = $spreadsheet->getSheet($i)->getTableCollection()->count(); + + for ($t = 1; $t <= $tableCount; ++$t) { + $this->writeOverrideContentType($objWriter, '/xl/tables/table' . $table++ . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'); + } + } + // Add worksheet relationship content types $unparsedLoadedData = $spreadsheet->getUnparsedLoadedData(); $chart = 1; @@ -144,7 +151,7 @@ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = fal if ($spreadsheet->hasRibbonBinObjects()) { // Some additional objects in the ribbon ? // we need to write "Extension" but not already write for media content - $tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); + $tabRibbonTypes = array_diff($spreadsheet->getRibbonBinObjects('types') ?? [], array_keys($aMediaContentTypes)); foreach ($tabRibbonTypes as $aRibbonType) { $mimeType = 'image/.' . $aRibbonType; //we wrote $mimeType like customUI Editor $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType); @@ -161,6 +168,23 @@ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = fal } } } + + if (count($spreadsheet->getSheet($i)->getComments()) > 0) { + foreach ($spreadsheet->getSheet($i)->getComments() as $comment) { + if (!$comment->hasBackgroundImage()) { + continue; + } + + $bgImage = $comment->getBackgroundImage(); + $bgImageExtentionKey = strtolower($bgImage->getImageFileExtensionForSave(false)); + + if (!isset($aMediaContentTypes[$bgImageExtentionKey])) { + $aMediaContentTypes[$bgImageExtentionKey] = $bgImage->getImageMimeType(); + + $this->writeDefaultContentType($objWriter, $bgImageExtentionKey, $aMediaContentTypes[$bgImageExtentionKey]); + } + } + } } // unparsed defaults @@ -186,39 +210,34 @@ public function writeContentTypes(Spreadsheet $spreadsheet, $includeCharts = fal /** * Get image mime type. * - * @param string $pFile Filename - * - * @throws WriterException + * @param string $filename Filename * * @return string Mime Type */ - private function getImageMimeType($pFile) + private function getImageMimeType($filename) { - if (File::fileExists($pFile)) { - $image = getimagesize($pFile); + if (File::fileExists($filename)) { + $image = getimagesize($filename); - return image_type_to_mime_type($image[2]); + return image_type_to_mime_type((is_array($image) && count($image) >= 3) ? $image[2] : 0); } - throw new WriterException("File $pFile does not exist"); + throw new WriterException("File $filename does not exist"); } /** * Write Default content type. * - * @param XMLWriter $objWriter XML Writer - * @param string $pPartname Part name - * @param string $pContentType Content type - * - * @throws WriterException + * @param string $partName Part name + * @param string $contentType Content type */ - private function writeDefaultContentType(XMLWriter $objWriter, $pPartname, $pContentType) + private function writeDefaultContentType(XMLWriter $objWriter, $partName, $contentType): void { - if ($pPartname != '' && $pContentType != '') { + if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Default'); - $objWriter->writeAttribute('Extension', $pPartname); - $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->writeAttribute('Extension', $partName); + $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); @@ -228,19 +247,16 @@ private function writeDefaultContentType(XMLWriter $objWriter, $pPartname, $pCon /** * Write Override content type. * - * @param XMLWriter $objWriter XML Writer - * @param string $pPartname Part name - * @param string $pContentType Content type - * - * @throws WriterException + * @param string $partName Part name + * @param string $contentType Content type */ - private function writeOverrideContentType(XMLWriter $objWriter, $pPartname, $pContentType) + private function writeOverrideContentType(XMLWriter $objWriter, $partName, $contentType): void { - if ($pPartname != '' && $pContentType != '') { + if ($partName != '' && $contentType != '') { // Write content type $objWriter->startElement('Override'); - $objWriter->writeAttribute('PartName', $pPartname); - $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->writeAttribute('PartName', $partName); + $objWriter->writeAttribute('ContentType', $contentType); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php new file mode 100644 index 00000000..b8285fcb --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DefinedNames.php @@ -0,0 +1,242 @@ +objWriter = $objWriter; + $this->spreadsheet = $spreadsheet; + } + + public function write(): void + { + // Write defined names + $this->objWriter->startElement('definedNames'); + + // Named ranges + if (count($this->spreadsheet->getDefinedNames()) > 0) { + // Named ranges + $this->writeNamedRangesAndFormulae(); + } + + // Other defined names + $sheetCount = $this->spreadsheet->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // NamedRange for autoFilter + $this->writeNamedRangeForAutofilter($this->spreadsheet->getSheet($i), $i); + + // NamedRange for Print_Titles + $this->writeNamedRangeForPrintTitles($this->spreadsheet->getSheet($i), $i); + + // NamedRange for Print_Area + $this->writeNamedRangeForPrintArea($this->spreadsheet->getSheet($i), $i); + } + + $this->objWriter->endElement(); + } + + /** + * Write defined names. + */ + private function writeNamedRangesAndFormulae(): void + { + // Loop named ranges + $definedNames = $this->spreadsheet->getDefinedNames(); + foreach ($definedNames as $definedName) { + $this->writeDefinedName($definedName); + } + } + + /** + * Write Defined Name for named range. + */ + private function writeDefinedName(DefinedName $definedName): void + { + // definedName for named range + $local = -1; + if ($definedName->getLocalOnly() && $definedName->getScope() !== null) { + try { + $local = $definedName->getScope()->getParent()->getIndex($definedName->getScope()); + } catch (Exception $e) { + // See issue 2266 - deleting sheet which contains + // defined names will cause Exception above. + return; + } + } + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', $definedName->getName()); + if ($local >= 0) { + $this->objWriter->writeAttribute( + 'localSheetId', + "$local" + ); + } + + $definedRange = $this->getDefinedRange($definedName); + + $this->objWriter->writeRawData($definedRange); + + $this->objWriter->endElement(); + } + + /** + * Write Defined Name for autoFilter. + */ + private function writeNamedRangeForAutofilter(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for autoFilter + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + $this->objWriter->writeAttribute('hidden', '1'); + + // Create absolute coordinate and write as raw text + $range = Coordinate::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref so we can make the cell ref absolute + [, $range[0]] = Worksheet::extractSheetTitle($range[0], true); + + $range[0] = Coordinate::absoluteCoordinate($range[0]); + $range[1] = Coordinate::absoluteCoordinate($range[1]); + $range = implode(':', $range); + + $this->objWriter->writeRawData('\'' . str_replace("'", "''", $worksheet->getTitle() ?? '') . '\'!' . $range); + + $this->objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles. + */ + private function writeNamedRangeForPrintTitles(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for PrintTitles + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm.Print_Titles'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + + // Setting string + $settingString = ''; + + // Columns to repeat + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $repeat = $worksheet->getPageSetup()->getColumnsToRepeatAtLeft(); + + $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + // Rows to repeat + if ($worksheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($worksheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $settingString .= ','; + } + + $repeat = $worksheet->getPageSetup()->getRowsToRepeatAtTop(); + + $settingString .= '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + $this->objWriter->writeRawData($settingString); + + $this->objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles. + */ + private function writeNamedRangeForPrintArea(Worksheet $worksheet, int $worksheetId = 0): void + { + // NamedRange for PrintArea + if ($worksheet->getPageSetup()->isPrintAreaSet()) { + $this->objWriter->startElement('definedName'); + $this->objWriter->writeAttribute('name', '_xlnm.Print_Area'); + $this->objWriter->writeAttribute('localSheetId', "$worksheetId"); + + // Print area + $printArea = Coordinate::splitRange($worksheet->getPageSetup()->getPrintArea()); + + $chunks = []; + foreach ($printArea as $printAreaRect) { + $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); + $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); + $chunks[] = '\'' . str_replace("'", "''", $worksheet->getTitle()) . '\'!' . implode(':', $printAreaRect); + } + + $this->objWriter->writeRawData(implode(',', $chunks)); + + $this->objWriter->endElement(); + } + } + + private function getDefinedRange(DefinedName $definedName): string + { + $definedRange = $definedName->getValue(); + $splitCount = preg_match_all( + '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui', + $definedRange, + $splitRanges, + PREG_OFFSET_CAPTURE + ); + + $lengths = array_map('strlen', array_column($splitRanges[0], 0)); + $offsets = array_column($splitRanges[0], 1); + + $worksheets = $splitRanges[2]; + $columns = $splitRanges[6]; + $rows = $splitRanges[7]; + + while ($splitCount > 0) { + --$splitCount; + $length = $lengths[$splitCount]; + $offset = $offsets[$splitCount]; + $worksheet = $worksheets[$splitCount][0]; + $column = $columns[$splitCount][0]; + $row = $rows[$splitCount][0]; + + $newRange = ''; + if (empty($worksheet)) { + if (($offset === 0) || ($definedRange[$offset - 1] !== ':')) { + // We should have a worksheet + $ws = $definedName->getWorksheet(); + $worksheet = ($ws === null) ? null : $ws->getTitle(); + } + } else { + $worksheet = str_replace("''", "'", trim($worksheet, "'")); + } + + if (!empty($worksheet)) { + $newRange = "'" . str_replace("'", "''", $worksheet) . "'!"; + } + $newRange = "{$newRange}{$column}{$row}"; + + $definedRange = substr($definedRange, 0, $offset) . $newRange . substr($definedRange, $offset + $length); + } + + if (substr($definedRange, 0, 1) === '=') { + $definedRange = substr($definedRange, 1); + } + + return $definedRange; + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php index 2a18d5c7..43ce442f 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/DocProps.php @@ -2,6 +2,8 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\Document\Properties; +use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -10,10 +12,6 @@ class DocProps extends WriterPart /** * Write docProps/app.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeDocPropsApp(Spreadsheet $spreadsheet) @@ -109,10 +107,6 @@ public function writeDocPropsApp(Spreadsheet $spreadsheet) /** * Write docProps/core.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeDocPropsCore(Spreadsheet $spreadsheet) @@ -145,13 +139,17 @@ public function writeDocPropsCore(Spreadsheet $spreadsheet) // dcterms:created $objWriter->startElement('dcterms:created'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getCreated())); + $created = $spreadsheet->getProperties()->getCreated(); + $date = Date::dateTimeFromTimestamp("$created"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dcterms:modified $objWriter->startElement('dcterms:modified'); $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $objWriter->writeRawData(date(DATE_W3C, $spreadsheet->getProperties()->getModified())); + $created = $spreadsheet->getProperties()->getModified(); + $date = Date::dateTimeFromTimestamp("$created"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); // dc:title @@ -178,17 +176,13 @@ public function writeDocPropsCore(Spreadsheet $spreadsheet) /** * Write docProps/custom.xml to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * - * @return string XML Output + * @return null|string XML Output */ public function writeDocPropsCustom(Spreadsheet $spreadsheet) { $customPropertyList = $spreadsheet->getProperties()->getCustomProperties(); if (empty($customPropertyList)) { - return; + return null; } // Create XML writer @@ -217,21 +211,22 @@ public function writeDocPropsCustom(Spreadsheet $spreadsheet) $objWriter->writeAttribute('name', $customProperty); switch ($propertyType) { - case 'i': + case Properties::PROPERTY_TYPE_INTEGER: $objWriter->writeElement('vt:i4', $propertyValue); break; - case 'f': + case Properties::PROPERTY_TYPE_FLOAT: $objWriter->writeElement('vt:r8', $propertyValue); break; - case 'b': + case Properties::PROPERTY_TYPE_BOOLEAN: $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); break; - case 'd': + case Properties::PROPERTY_TYPE_DATE: $objWriter->startElement('vt:filetime'); - $objWriter->writeRawData(date(DATE_W3C, $propertyValue)); + $date = Date::dateTimeFromTimestamp("$propertyValue"); + $objWriter->writeRawData($date->format(DATE_W3C)); $objWriter->endElement(); break; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php index 08256a1d..816bb9d4 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Drawing.php @@ -3,6 +3,7 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; +use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; @@ -14,14 +15,11 @@ class Drawing extends WriterPart /** * Write drawings to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet * @param bool $includeCharts Flag indicating if we should include drawing details for charts * - * @throws WriterException - * * @return string XML Output */ - public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $includeCharts = false) + public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $includeCharts = false) { // Create XML writer $objWriter = null; @@ -41,7 +39,7 @@ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWo // Loop through images and write drawings $i = 1; - $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { /** @var BaseDrawing $pDrawing */ $pDrawing = $iterator->current(); @@ -55,19 +53,22 @@ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWo } if ($includeCharts) { - $chartCount = $pWorksheet->getChartCount(); + $chartCount = $worksheet->getChartCount(); // Loop through charts and write the chart position if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { - $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c + $i); + $chart = $worksheet->getChartByIndex((string) $c); + if ($chart !== false) { + $this->writeChart($objWriter, $chart, $c + $i); + } } } } // unparsed AlternateContent - $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData(); - if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'])) { - foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) { + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'])) { + foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingAlternateContents'] as $drawingAlternateContent) { $objWriter->writeRaw($drawingAlternateContent); } } @@ -81,38 +82,36 @@ public function writeDrawings(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWo /** * Write drawings to XML format. * - * @param XMLWriter $objWriter XML Writer - * @param \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart - * @param int $pRelationId + * @param int $relationId */ - public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $pChart, $pRelationId = -1) + public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart\Chart $chart, $relationId = -1): void { - $tl = $pChart->getTopLeftPosition(); - $tl['colRow'] = Coordinate::coordinateFromString($tl['cell']); - $br = $pChart->getBottomRightPosition(); - $br['colRow'] = Coordinate::coordinateFromString($br['cell']); + $tl = $chart->getTopLeftPosition(); + $tlColRow = Coordinate::indexesFromString($tl['cell']); + $br = $chart->getBottomRightPosition(); + $brColRow = Coordinate::indexesFromString($br['cell']); $objWriter->startElement('xdr:twoCellAnchor'); $objWriter->startElement('xdr:from'); - $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($tl['colRow'][0]) - 1); - $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['xOffset'])); - $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); - $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($tl['yOffset'])); + $objWriter->writeElement('xdr:col', (string) ($tlColRow[0] - 1)); + $objWriter->writeElement('xdr:colOff', self::stringEmu($tl['xOffset'])); + $objWriter->writeElement('xdr:row', (string) ($tlColRow[1] - 1)); + $objWriter->writeElement('xdr:rowOff', self::stringEmu($tl['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:to'); - $objWriter->writeElement('xdr:col', Coordinate::columnIndexFromString($br['colRow'][0]) - 1); - $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['xOffset'])); - $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); - $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($br['yOffset'])); + $objWriter->writeElement('xdr:col', (string) ($brColRow[0] - 1)); + $objWriter->writeElement('xdr:colOff', self::stringEmu($br['xOffset'])); + $objWriter->writeElement('xdr:row', (string) ($brColRow[1] - 1)); + $objWriter->writeElement('xdr:rowOff', self::stringEmu($br['yOffset'])); $objWriter->endElement(); $objWriter->startElement('xdr:graphicFrame'); $objWriter->writeAttribute('macro', ''); $objWriter->startElement('xdr:nvGraphicFramePr'); $objWriter->startElement('xdr:cNvPr'); - $objWriter->writeAttribute('name', 'Chart ' . $pRelationId); - $objWriter->writeAttribute('id', 1025 * $pRelationId); + $objWriter->writeAttribute('name', 'Chart ' . $relationId); + $objWriter->writeAttribute('id', (string) (1025 * $relationId)); $objWriter->endElement(); $objWriter->startElement('xdr:cNvGraphicFramePr'); $objWriter->startElement('a:graphicFrameLocks'); @@ -137,7 +136,7 @@ public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart $objWriter->startElement('c:chart'); $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $objWriter->writeAttribute('r:id', 'rId' . $pRelationId); + $objWriter->writeAttribute('r:id', 'rId' . $relationId); $objWriter->endElement(); $objWriter->endElement(); $objWriter->endElement(); @@ -152,35 +151,58 @@ public function writeChart(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Chart /** * Write drawings to XML format. * - * @param XMLWriter $objWriter XML Writer - * @param BaseDrawing $pDrawing - * @param int $pRelationId + * @param int $relationId * @param null|int $hlinkClickId - * - * @throws WriterException */ - public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRelationId = -1, $hlinkClickId = null) + public function writeDrawing(XMLWriter $objWriter, BaseDrawing $drawing, $relationId = -1, $hlinkClickId = null): void { - if ($pRelationId >= 0) { - // xdr:oneCellAnchor - $objWriter->startElement('xdr:oneCellAnchor'); - // Image location - $aCoordinates = Coordinate::coordinateFromString($pDrawing->getCoordinates()); - $aCoordinates[0] = Coordinate::columnIndexFromString($aCoordinates[0]); - - // xdr:from - $objWriter->startElement('xdr:from'); - $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1); - $objWriter->writeElement('xdr:colOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetX())); - $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1); - $objWriter->writeElement('xdr:rowOff', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getOffsetY())); - $objWriter->endElement(); + if ($relationId >= 0) { + $isTwoCellAnchor = $drawing->getCoordinates2() !== ''; + if ($isTwoCellAnchor) { + // xdr:twoCellAnchor + $objWriter->startElement('xdr:twoCellAnchor'); + if ($drawing->validEditAs()) { + $objWriter->writeAttribute('editAs', $drawing->getEditAs()); + } + // Image location + $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); + $aCoordinates2 = Coordinate::indexesFromString($drawing->getCoordinates2()); + + // xdr:from + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); + $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); + $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); + $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); + $objWriter->endElement(); - // xdr:ext - $objWriter->startElement('xdr:ext'); - $objWriter->writeAttribute('cx', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getWidth())); - $objWriter->writeAttribute('cy', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getHeight())); - $objWriter->endElement(); + // xdr:to + $objWriter->startElement('xdr:to'); + $objWriter->writeElement('xdr:col', (string) ($aCoordinates2[0] - 1)); + $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX2())); + $objWriter->writeElement('xdr:row', (string) ($aCoordinates2[1] - 1)); + $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY2())); + $objWriter->endElement(); + } else { + // xdr:oneCellAnchor + $objWriter->startElement('xdr:oneCellAnchor'); + // Image location + $aCoordinates = Coordinate::indexesFromString($drawing->getCoordinates()); + + // xdr:from + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', (string) ($aCoordinates[0] - 1)); + $objWriter->writeElement('xdr:colOff', self::stringEmu($drawing->getOffsetX())); + $objWriter->writeElement('xdr:row', (string) ($aCoordinates[1] - 1)); + $objWriter->writeElement('xdr:rowOff', self::stringEmu($drawing->getOffsetY())); + $objWriter->endElement(); + + // xdr:ext + $objWriter->startElement('xdr:ext'); + $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); + $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); + $objWriter->endElement(); + } // xdr:pic $objWriter->startElement('xdr:pic'); @@ -190,9 +212,9 @@ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRela // xdr:cNvPr $objWriter->startElement('xdr:cNvPr'); - $objWriter->writeAttribute('id', $pRelationId); - $objWriter->writeAttribute('name', $pDrawing->getName()); - $objWriter->writeAttribute('descr', $pDrawing->getDescription()); + $objWriter->writeAttribute('id', (string) $relationId); + $objWriter->writeAttribute('name', $drawing->getName()); + $objWriter->writeAttribute('descr', $drawing->getDescription()); //a:hlinkClick $this->writeHyperLinkDrawing($objWriter, $hlinkClickId); @@ -217,7 +239,7 @@ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRela // a:blip $objWriter->startElement('a:blip'); $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId); + $objWriter->writeAttribute('r:embed', 'rId' . $relationId); $objWriter->endElement(); // a:stretch @@ -232,7 +254,13 @@ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRela // a:xfrm $objWriter->startElement('a:xfrm'); - $objWriter->writeAttribute('rot', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getRotation())); + $objWriter->writeAttribute('rot', (string) SharedDrawing::degreesToAngle($drawing->getRotation())); + if ($isTwoCellAnchor) { + $objWriter->startElement('a:ext'); + $objWriter->writeAttribute('cx', self::stringEmu($drawing->getWidth())); + $objWriter->writeAttribute('cy', self::stringEmu($drawing->getHeight())); + $objWriter->endElement(); + } $objWriter->endElement(); // a:prstGeom @@ -244,25 +272,25 @@ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRela $objWriter->endElement(); - if ($pDrawing->getShadow()->getVisible()) { + if ($drawing->getShadow()->getVisible()) { // a:effectLst $objWriter->startElement('a:effectLst'); // a:outerShdw $objWriter->startElement('a:outerShdw'); - $objWriter->writeAttribute('blurRad', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius())); - $objWriter->writeAttribute('dist', \PhpOffice\PhpSpreadsheet\Shared\Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance())); - $objWriter->writeAttribute('dir', \PhpOffice\PhpSpreadsheet\Shared\Drawing::degreesToAngle($pDrawing->getShadow()->getDirection())); - $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment()); + $objWriter->writeAttribute('blurRad', self::stringEmu($drawing->getShadow()->getBlurRadius())); + $objWriter->writeAttribute('dist', self::stringEmu($drawing->getShadow()->getDistance())); + $objWriter->writeAttribute('dir', (string) SharedDrawing::degreesToAngle($drawing->getShadow()->getDirection())); + $objWriter->writeAttribute('algn', $drawing->getShadow()->getAlignment()); $objWriter->writeAttribute('rotWithShape', '0'); // a:srgbClr $objWriter->startElement('a:srgbClr'); - $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB()); + $objWriter->writeAttribute('val', $drawing->getShadow()->getColor()->getRGB()); // a:alpha $objWriter->startElement('a:alpha'); - $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000); + $objWriter->writeAttribute('val', (string) ($drawing->getShadow()->getAlpha() * 1000)); $objWriter->endElement(); $objWriter->endElement(); @@ -287,13 +315,9 @@ public function writeDrawing(XMLWriter $objWriter, BaseDrawing $pDrawing, $pRela /** * Write VML header/footer images to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * - * @throws WriterException - * * @return string XML Output */ - public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet) + public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; @@ -307,7 +331,7 @@ public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\W $objWriter->startDocument('1.0', 'UTF-8', 'yes'); // Header/footer images - $images = $pWorksheet->getHeaderFooter()->getImages(); + $images = $worksheet->getHeaderFooter()->getImages(); // xml $objWriter->startElement('xml'); @@ -436,33 +460,31 @@ public function writeVMLHeaderFooterImages(\PhpOffice\PhpSpreadsheet\Worksheet\W /** * Write VML comment to XML format. * - * @param XMLWriter $objWriter XML Writer - * @param string $pReference Reference - * @param HeaderFooterDrawing $pImage Image + * @param string $reference Reference */ - private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $pReference, HeaderFooterDrawing $pImage) + private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $reference, HeaderFooterDrawing $image): void { // Calculate object id - preg_match('{(\d+)}', md5($pReference), $m); - $id = 1500 + (substr($m[1], 0, 2) * 1); + preg_match('{(\d+)}', md5($reference), $m); + $id = 1500 + ((int) substr($m[1], 0, 2) * 1); // Calculate offset - $width = $pImage->getWidth(); - $height = $pImage->getHeight(); - $marginLeft = $pImage->getOffsetX(); - $marginTop = $pImage->getOffsetY(); + $width = $image->getWidth(); + $height = $image->getHeight(); + $marginLeft = $image->getOffsetX(); + $marginTop = $image->getOffsetY(); // v:shape $objWriter->startElement('v:shape'); - $objWriter->writeAttribute('id', $pReference); + $objWriter->writeAttribute('id', $reference); $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); $objWriter->writeAttribute('type', '#_x0000_t75'); $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); // v:imagedata $objWriter->startElement('v:imagedata'); - $objWriter->writeAttribute('o:relid', 'rId' . $pReference); - $objWriter->writeAttribute('o:title', $pImage->getName()); + $objWriter->writeAttribute('o:relid', 'rId' . $reference); + $objWriter->writeAttribute('o:title', $image->getName()); $objWriter->endElement(); // o:lock @@ -477,9 +499,7 @@ private function writeVMLHeaderFooterImage(XMLWriter $objWriter, $pReference, He /** * Get an array of all drawings. * - * @param Spreadsheet $spreadsheet - * - * @return \PhpOffice\PhpSpreadsheet\Worksheet\Drawing[] All drawings in PhpSpreadsheet + * @return BaseDrawing[] All drawings in PhpSpreadsheet */ public function allDrawings(Spreadsheet $spreadsheet) { @@ -502,10 +522,9 @@ public function allDrawings(Spreadsheet $spreadsheet) } /** - * @param XMLWriter $objWriter * @param null|int $hlinkClickId */ - private function writeHyperLinkDrawing(XMLWriter $objWriter, $hlinkClickId) + private function writeHyperLinkDrawing(XMLWriter $objWriter, $hlinkClickId): void { if ($hlinkClickId === null) { return; @@ -516,4 +535,9 @@ private function writeHyperLinkDrawing(XMLWriter $objWriter, $hlinkClickId) $objWriter->writeAttribute('r:id', 'rId' . $hlinkClickId); $objWriter->endElement(); } + + private static function stringEmu(int $pixelValue): string + { + return (string) SharedDrawing::pixelsToEMU($pixelValue); + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php index 76c196b4..238fb5bf 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Rels.php @@ -4,6 +4,7 @@ use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing; use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; @@ -12,10 +13,6 @@ class Rels extends WriterPart /** * Write relationships to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws WriterException - * * @return string XML Output */ public function writeRelationships(Spreadsheet $spreadsheet) @@ -87,10 +84,6 @@ public function writeRelationships(Spreadsheet $spreadsheet) /** * Write workbook relationships to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws WriterException - * * @return string XML Output */ public function writeWorkbookRelationships(Spreadsheet $spreadsheet) @@ -168,15 +161,13 @@ public function writeWorkbookRelationships(Spreadsheet $spreadsheet) * rId1 - Drawings * rId_hyperlink_x - Hyperlinks * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * @param int $pWorksheetId + * @param int $worksheetId * @param bool $includeCharts Flag indicating if we should write charts - * - * @throws WriterException + * @param int $tableRef Table ID * * @return string XML Output */ - public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, $pWorksheetId = 1, $includeCharts = false) + public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, $worksheetId = 1, $includeCharts = false, $tableRef = 1) { // Create XML writer $objWriter = null; @@ -194,27 +185,32 @@ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Write drawing relationships? - $d = 0; $drawingOriginalIds = []; - $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData(); - if (isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds'])) { - $drawingOriginalIds = $unparsedLoadedData['sheets'][$pWorksheet->getCodeName()]['drawingOriginalIds']; + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { + $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; } if ($includeCharts) { - $charts = $pWorksheet->getChartCollection(); + $charts = $worksheet->getChartCollection(); } else { $charts = []; } - if (($pWorksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) { - $relPath = '../drawings/drawing' . $pWorksheetId . '.xml'; - $rId = ++$d; + if (($worksheet->getDrawingCollection()->count() > 0) || (count($charts) > 0) || $drawingOriginalIds) { + $rId = 1; + // Use original $relPath to get original $rId. + // Take first. In future can be overwritten. + // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet::writeDrawings) + reset($drawingOriginalIds); + $relPath = key($drawingOriginalIds); if (isset($drawingOriginalIds[$relPath])) { $rId = (int) (substr($drawingOriginalIds[$relPath], 3)); } + // Generate new $relPath to write drawing relationship + $relPath = '../drawings/drawing' . $worksheetId . '.xml'; $this->writeRelationship( $objWriter, $rId, @@ -225,7 +221,7 @@ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\ // Write hyperlink relationships? $i = 1; - foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) { + foreach ($worksheet->getHyperlinkCollection() as $hyperlink) { if (!$hyperlink->isInternal()) { $this->writeRelationship( $objWriter, @@ -241,50 +237,61 @@ public function writeWorksheetRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\ // Write comments relationship? $i = 1; - if (count($pWorksheet->getComments()) > 0) { + if (count($worksheet->getComments()) > 0) { $this->writeRelationship( $objWriter, '_comments_vml' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', - '../drawings/vmlDrawing' . $pWorksheetId . '.vml' + '../drawings/vmlDrawing' . $worksheetId . '.vml' ); $this->writeRelationship( $objWriter, '_comments' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments', - '../comments' . $pWorksheetId . '.xml' + '../comments' . $worksheetId . '.xml' + ); + } + + // Write Table + $tableCount = $worksheet->getTableCollection()->count(); + for ($i = 1; $i <= $tableCount; ++$i) { + $this->writeRelationship( + $objWriter, + '_table_' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table', + '../tables/table' . $tableRef++ . '.xml' ); } // Write header/footer relationship? $i = 1; - if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) { + if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $this->writeRelationship( $objWriter, '_headerfooter_vml' . $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', - '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml' + '../drawings/vmlDrawingHF' . $worksheetId . '.vml' ); } - $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'ctrlProps', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp'); - $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'vmlDrawings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing'); - $this->writeUnparsedRelationship($pWorksheet, $objWriter, 'printerSettings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings'); + $this->writeUnparsedRelationship($worksheet, $objWriter, 'ctrlProps', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/ctrlProp'); + $this->writeUnparsedRelationship($worksheet, $objWriter, 'vmlDrawings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing'); + $this->writeUnparsedRelationship($worksheet, $objWriter, 'printerSettings', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/printerSettings'); $objWriter->endElement(); return $objWriter->getData(); } - private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, XMLWriter $objWriter, $relationship, $type) + private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, XMLWriter $objWriter, $relationship, $type): void { - $unparsedLoadedData = $pWorksheet->getParent()->getUnparsedLoadedData(); - if (!isset($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship])) { + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (!isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship])) { return; } - foreach ($unparsedLoadedData['sheets'][$pWorksheet->getCodeName()][$relationship] as $rId => $value) { + foreach ($unparsedLoadedData['sheets'][$worksheet->getCodeName()][$relationship] as $rId => $value) { $this->writeRelationship( $objWriter, $rId, @@ -297,15 +304,12 @@ private function writeUnparsedRelationship(\PhpOffice\PhpSpreadsheet\Worksheet\W /** * Write drawing relationships to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * @param int &$chartRef Chart ID + * @param int $chartRef Chart ID * @param bool $includeCharts Flag indicating if we should write charts * - * @throws WriterException - * * @return string XML Output */ - public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet, &$chartRef, $includeCharts = false) + public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet, &$chartRef, $includeCharts = false) { // Create XML writer $objWriter = null; @@ -324,18 +328,19 @@ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Wo // Loop through images and write relationships $i = 1; - $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + $iterator = $worksheet->getDrawingCollection()->getIterator(); while ($iterator->valid()) { - if ($iterator->current() instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing - || $iterator->current() instanceof MemoryDrawing) { + $drawing = $iterator->current(); + if ( + $drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\Drawing + || $drawing instanceof MemoryDrawing + ) { // Write relationship for image drawing - /** @var \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing */ - $drawing = $iterator->current(); $this->writeRelationship( $objWriter, $i, 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', - '../media/' . str_replace(' ', '', $drawing->getIndexedFilename()) + '../media/' . $drawing->getIndexedFilename() ); $i = $this->writeDrawingHyperLink($objWriter, $drawing, $i); @@ -347,7 +352,7 @@ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Wo if ($includeCharts) { // Loop through charts and write relationships - $chartCount = $pWorksheet->getChartCount(); + $chartCount = $worksheet->getChartCount(); if ($chartCount > 0) { for ($c = 0; $c < $chartCount; ++$c) { $this->writeRelationship( @@ -368,13 +373,9 @@ public function writeDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Wo /** * Write header/footer drawing relationships to XML format. * - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet - * - * @throws WriterException - * * @return string XML Output */ - public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $pWorksheet) + public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet) { // Create XML writer $objWriter = null; @@ -392,7 +393,7 @@ public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\ $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // Loop through images and write relationships - foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) { + foreach ($worksheet->getHeaderFooter()->getImages() as $key => $value) { // Write relationship for image drawing $this->writeRelationship( $objWriter, @@ -407,28 +408,62 @@ public function writeHeaderFooterDrawingRelationships(\PhpOffice\PhpSpreadsheet\ return $objWriter->getData(); } + public function writeVMLDrawingRelationships(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): string + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Loop through images and write relationships + foreach ($worksheet->getComments() as $comment) { + if (!$comment->hasBackgroundImage()) { + continue; + } + + $bgImage = $comment->getBackgroundImage(); + $this->writeRelationship( + $objWriter, + $bgImage->getImageIndex(), + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + '../media/' . $bgImage->getMediaFilename() + ); + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + /** * Write Override content type. * - * @param XMLWriter $objWriter XML Writer - * @param int $pId Relationship ID. rId will be prepended! - * @param string $pType Relationship type - * @param string $pTarget Relationship target - * @param string $pTargetMode Relationship target mode - * - * @throws WriterException + * @param int $id Relationship ID. rId will be prepended! + * @param string $type Relationship type + * @param string $target Relationship target + * @param string $targetMode Relationship target mode */ - private function writeRelationship(XMLWriter $objWriter, $pId, $pType, $pTarget, $pTargetMode = '') + private function writeRelationship(XMLWriter $objWriter, $id, $type, $target, $targetMode = ''): void { - if ($pType != '' && $pTarget != '') { + if ($type != '' && $target != '') { // Write relationship $objWriter->startElement('Relationship'); - $objWriter->writeAttribute('Id', 'rId' . $pId); - $objWriter->writeAttribute('Type', $pType); - $objWriter->writeAttribute('Target', $pTarget); + $objWriter->writeAttribute('Id', 'rId' . $id); + $objWriter->writeAttribute('Type', $type); + $objWriter->writeAttribute('Target', $target); - if ($pTargetMode != '') { - $objWriter->writeAttribute('TargetMode', $pTargetMode); + if ($targetMode != '') { + $objWriter->writeAttribute('TargetMode', $targetMode); } $objWriter->endElement(); @@ -437,16 +472,7 @@ private function writeRelationship(XMLWriter $objWriter, $pId, $pType, $pTarget, } } - /** - * @param $objWriter - * @param \PhpOffice\PhpSpreadsheet\Worksheet\Drawing $drawing - * @param $i - * - * @throws WriterException - * - * @return int - */ - private function writeDrawingHyperLink($objWriter, $drawing, $i) + private function writeDrawingHyperLink(XMLWriter $objWriter, BaseDrawing $drawing, int $i): int { if ($drawing->getHyperlink() === null) { return $i; diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php index 8a0cfe34..8005207c 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsRibbon.php @@ -10,10 +10,6 @@ class RelsRibbon extends WriterPart /** * Write relationships for additional objects of custom UI (ribbon). * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeRibbonRelationships(Spreadsheet $spreadsheet) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php index 01ad38de..55bcd360 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/RelsVBA.php @@ -10,10 +10,6 @@ class RelsVBA extends WriterPart /** * Write relationships for a signed VBA Project. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeVBARelationships(Spreadsheet $spreadsheet) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php index 19604e44..f9a2e711 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/StringTable.php @@ -8,19 +8,18 @@ use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; -use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class StringTable extends WriterPart { /** * Create worksheet stringtable. * - * @param Worksheet $pSheet Worksheet - * @param string[] $pExistingTable Existing table to eventually merge with + * @param Worksheet $worksheet Worksheet + * @param string[] $existingTable Existing table to eventually merge with * * @return string[] String table for worksheet */ - public function createStringTable(Worksheet $pSheet, $pExistingTable = null) + public function createStringTable(Worksheet $worksheet, $existingTable = null) { // Create string lookup table $aStringTable = []; @@ -28,27 +27,31 @@ public function createStringTable(Worksheet $pSheet, $pExistingTable = null) $aFlippedStringTable = null; // For faster lookup // Is an existing table given? - if (($pExistingTable !== null) && is_array($pExistingTable)) { - $aStringTable = $pExistingTable; + if (($existingTable !== null) && is_array($existingTable)) { + $aStringTable = $existingTable; } // Fill index array $aFlippedStringTable = $this->flipStringTable($aStringTable); // Loop through cells - foreach ($pSheet->getCoordinates() as $coordinate) { - $cell = $pSheet->getCell($coordinate); + foreach ($worksheet->getCoordinates() as $coordinate) { + $cell = $worksheet->getCell($coordinate); $cellValue = $cell->getValue(); - if (!is_object($cellValue) && + if ( + !is_object($cellValue) && ($cellValue !== null) && $cellValue !== '' && - !isset($aFlippedStringTable[$cellValue]) && - ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL)) { + ($cell->getDataType() == DataType::TYPE_STRING || $cell->getDataType() == DataType::TYPE_STRING2 || $cell->getDataType() == DataType::TYPE_NULL) && + !isset($aFlippedStringTable[$cellValue]) + ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue] = true; - } elseif ($cellValue instanceof RichText && + } elseif ( + $cellValue instanceof RichText && ($cellValue !== null) && - !isset($aFlippedStringTable[$cellValue->getHashCode()])) { + !isset($aFlippedStringTable[$cellValue->getHashCode()]) + ) { $aStringTable[] = $cellValue; $aFlippedStringTable[$cellValue->getHashCode()] = true; } @@ -60,13 +63,11 @@ public function createStringTable(Worksheet $pSheet, $pExistingTable = null) /** * Write string table to XML format. * - * @param string[] $pStringTable - * - * @throws WriterException + * @param string[] $stringTable * * @return string XML Output */ - public function writeStringTable(array $pStringTable) + public function writeStringTable(array $stringTable) { // Create XML writer $objWriter = null; @@ -82,10 +83,10 @@ public function writeStringTable(array $pStringTable) // String table $objWriter->startElement('sst'); $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - $objWriter->writeAttribute('uniqueCount', count($pStringTable)); + $objWriter->writeAttribute('uniqueCount', count($stringTable)); // Loop through string table - foreach ($pStringTable as $textElement) { + foreach ($stringTable as $textElement) { $objWriter->startElement('si'); if (!$textElement instanceof RichText) { @@ -111,18 +112,16 @@ public function writeStringTable(array $pStringTable) /** * Write Rich Text. * - * @param XMLWriter $objWriter XML Writer - * @param RichText $pRichText Rich text * @param string $prefix Optional Namespace prefix */ - public function writeRichText(XMLWriter $objWriter, RichText $pRichText, $prefix = null) + public function writeRichText(XMLWriter $objWriter, RichText $richText, $prefix = null): void { if ($prefix !== null) { $prefix .= ':'; } // Loop through rich text elements - $elements = $pRichText->getRichTextElements(); + $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); @@ -194,16 +193,15 @@ public function writeRichText(XMLWriter $objWriter, RichText $pRichText, $prefix /** * Write Rich Text. * - * @param XMLWriter $objWriter XML Writer - * @param RichText|string $pRichText text string or Rich text + * @param RichText|string $richText text string or Rich text * @param string $prefix Optional Namespace prefix */ - public function writeRichTextForCharts(XMLWriter $objWriter, $pRichText = null, $prefix = null) + public function writeRichTextForCharts(XMLWriter $objWriter, $richText = null, $prefix = null): void { - if (!$pRichText instanceof RichText) { - $textRun = $pRichText; - $pRichText = new RichText(); - $pRichText->createTextRun($textRun); + if (!$richText instanceof RichText) { + $textRun = $richText; + $richText = new RichText(); + $richText->createTextRun($textRun); } if ($prefix !== null) { @@ -211,7 +209,7 @@ public function writeRichTextForCharts(XMLWriter $objWriter, $pRichText = null, } // Loop through rich text elements - $elements = $pRichText->getRichTextElements(); + $elements = $richText->getRichTextElements(); foreach ($elements as $element) { // r $objWriter->startElement($prefix . 'r'); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php index 16e800e0..cb2e3850 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Style.php @@ -18,10 +18,6 @@ class Style extends WriterPart /** * Write styles to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeStyles(Spreadsheet $spreadsheet) @@ -149,38 +145,34 @@ public function writeStyles(Spreadsheet $spreadsheet) /** * Write Fill. - * - * @param XMLWriter $objWriter XML Writer - * @param Fill $pFill Fill style */ - private function writeFill(XMLWriter $objWriter, Fill $pFill) + private function writeFill(XMLWriter $objWriter, Fill $fill): void { // Check if this is a pattern type or gradient type - if ($pFill->getFillType() === Fill::FILL_GRADIENT_LINEAR || - $pFill->getFillType() === Fill::FILL_GRADIENT_PATH) { + if ( + $fill->getFillType() === Fill::FILL_GRADIENT_LINEAR || + $fill->getFillType() === Fill::FILL_GRADIENT_PATH + ) { // Gradient fill - $this->writeGradientFill($objWriter, $pFill); - } elseif ($pFill->getFillType() !== null) { + $this->writeGradientFill($objWriter, $fill); + } elseif ($fill->getFillType() !== null) { // Pattern fill - $this->writePatternFill($objWriter, $pFill); + $this->writePatternFill($objWriter, $fill); } } /** * Write Gradient Fill. - * - * @param XMLWriter $objWriter XML Writer - * @param Fill $pFill Fill style */ - private function writeGradientFill(XMLWriter $objWriter, Fill $pFill) + private function writeGradientFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // gradientFill $objWriter->startElement('gradientFill'); - $objWriter->writeAttribute('type', $pFill->getFillType()); - $objWriter->writeAttribute('degree', $pFill->getRotation()); + $objWriter->writeAttribute('type', $fill->getFillType()); + $objWriter->writeAttribute('degree', $fill->getRotation()); // stop $objWriter->startElement('stop'); @@ -188,7 +180,7 @@ private function writeGradientFill(XMLWriter $objWriter, Fill $pFill) // color $objWriter->startElement('color'); - $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); $objWriter->endElement(); $objWriter->endElement(); @@ -199,7 +191,7 @@ private function writeGradientFill(XMLWriter $objWriter, Fill $pFill) // color $objWriter->startElement('color'); - $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); $objWriter->endElement(); @@ -209,34 +201,38 @@ private function writeGradientFill(XMLWriter $objWriter, Fill $pFill) $objWriter->endElement(); } + private static function writePatternColors(Fill $fill): bool + { + if ($fill->getFillType() === Fill::FILL_NONE) { + return false; + } + + return $fill->getFillType() === Fill::FILL_SOLID || $fill->getColorsChanged(); + } + /** * Write Pattern Fill. - * - * @param XMLWriter $objWriter XML Writer - * @param Fill $pFill Fill style */ - private function writePatternFill(XMLWriter $objWriter, Fill $pFill) + private function writePatternFill(XMLWriter $objWriter, Fill $fill): void { // fill $objWriter->startElement('fill'); // patternFill $objWriter->startElement('patternFill'); - $objWriter->writeAttribute('patternType', $pFill->getFillType()); + $objWriter->writeAttribute('patternType', $fill->getFillType()); - if ($pFill->getFillType() !== Fill::FILL_NONE) { + if (self::writePatternColors($fill)) { // fgColor - if ($pFill->getStartColor()->getARGB()) { + if ($fill->getStartColor()->getARGB()) { $objWriter->startElement('fgColor'); - $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->writeAttribute('rgb', $fill->getStartColor()->getARGB()); $objWriter->endElement(); } - } - if ($pFill->getFillType() !== Fill::FILL_NONE) { // bgColor - if ($pFill->getEndColor()->getARGB()) { + if ($fill->getEndColor()->getARGB()) { $objWriter->startElement('bgColor'); - $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->writeAttribute('rgb', $fill->getEndColor()->getARGB()); $objWriter->endElement(); } } @@ -248,11 +244,8 @@ private function writePatternFill(XMLWriter $objWriter, Fill $pFill) /** * Write Font. - * - * @param XMLWriter $objWriter XML Writer - * @param Font $pFont Font style */ - private function writeFont(XMLWriter $objWriter, Font $pFont) + private function writeFont(XMLWriter $objWriter, Font $font): void { // font $objWriter->startElement('font'); @@ -263,62 +256,62 @@ private function writeFont(XMLWriter $objWriter, Font $pFont) // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does // for conditional formatting). Otherwise it will apparently not be picked up in conditional // formatting style dialog - if ($pFont->getBold() !== null) { + if ($font->getBold() !== null) { $objWriter->startElement('b'); - $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0'); + $objWriter->writeAttribute('val', $font->getBold() ? '1' : '0'); $objWriter->endElement(); } // Italic - if ($pFont->getItalic() !== null) { + if ($font->getItalic() !== null) { $objWriter->startElement('i'); - $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0'); + $objWriter->writeAttribute('val', $font->getItalic() ? '1' : '0'); $objWriter->endElement(); } // Strikethrough - if ($pFont->getStrikethrough() !== null) { + if ($font->getStrikethrough() !== null) { $objWriter->startElement('strike'); - $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0'); + $objWriter->writeAttribute('val', $font->getStrikethrough() ? '1' : '0'); $objWriter->endElement(); } // Underline - if ($pFont->getUnderline() !== null) { + if ($font->getUnderline() !== null) { $objWriter->startElement('u'); - $objWriter->writeAttribute('val', $pFont->getUnderline()); + $objWriter->writeAttribute('val', $font->getUnderline()); $objWriter->endElement(); } // Superscript / subscript - if ($pFont->getSuperscript() === true || $pFont->getSubscript() === true) { + if ($font->getSuperscript() === true || $font->getSubscript() === true) { $objWriter->startElement('vertAlign'); - if ($pFont->getSuperscript() === true) { + if ($font->getSuperscript() === true) { $objWriter->writeAttribute('val', 'superscript'); - } elseif ($pFont->getSubscript() === true) { + } elseif ($font->getSubscript() === true) { $objWriter->writeAttribute('val', 'subscript'); } $objWriter->endElement(); } // Size - if ($pFont->getSize() !== null) { + if ($font->getSize() !== null) { $objWriter->startElement('sz'); - $objWriter->writeAttribute('val', StringHelper::formatNumber($pFont->getSize())); + $objWriter->writeAttribute('val', StringHelper::formatNumber($font->getSize())); $objWriter->endElement(); } // Foreground color - if ($pFont->getColor()->getARGB() !== null) { + if ($font->getColor()->getARGB() !== null) { $objWriter->startElement('color'); - $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB()); + $objWriter->writeAttribute('rgb', $font->getColor()->getARGB()); $objWriter->endElement(); } // Name - if ($pFont->getName() !== null) { + if ($font->getName() !== null) { $objWriter->startElement('name'); - $objWriter->writeAttribute('val', $pFont->getName()); + $objWriter->writeAttribute('val', $font->getName()); $objWriter->endElement(); } @@ -327,16 +320,13 @@ private function writeFont(XMLWriter $objWriter, Font $pFont) /** * Write Border. - * - * @param XMLWriter $objWriter XML Writer - * @param Borders $pBorders Borders style */ - private function writeBorder(XMLWriter $objWriter, Borders $pBorders) + private function writeBorder(XMLWriter $objWriter, Borders $borders): void { // Write border $objWriter->startElement('border'); // Diagonal? - switch ($pBorders->getDiagonalDirection()) { + switch ($borders->getDiagonalDirection()) { case Borders::DIAGONAL_UP: $objWriter->writeAttribute('diagonalUp', 'true'); $objWriter->writeAttribute('diagonalDown', 'false'); @@ -355,84 +345,78 @@ private function writeBorder(XMLWriter $objWriter, Borders $pBorders) } // BorderPr - $this->writeBorderPr($objWriter, 'left', $pBorders->getLeft()); - $this->writeBorderPr($objWriter, 'right', $pBorders->getRight()); - $this->writeBorderPr($objWriter, 'top', $pBorders->getTop()); - $this->writeBorderPr($objWriter, 'bottom', $pBorders->getBottom()); - $this->writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal()); + $this->writeBorderPr($objWriter, 'left', $borders->getLeft()); + $this->writeBorderPr($objWriter, 'right', $borders->getRight()); + $this->writeBorderPr($objWriter, 'top', $borders->getTop()); + $this->writeBorderPr($objWriter, 'bottom', $borders->getBottom()); + $this->writeBorderPr($objWriter, 'diagonal', $borders->getDiagonal()); $objWriter->endElement(); } /** * Write Cell Style Xf. - * - * @param XMLWriter $objWriter XML Writer - * @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style - * @param Spreadsheet $spreadsheet Workbook - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ - private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle, Spreadsheet $spreadsheet) + private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style, Spreadsheet $spreadsheet): void { // xf $objWriter->startElement('xf'); $objWriter->writeAttribute('xfId', 0); - $objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode())); - if ($pStyle->getQuotePrefix()) { + $objWriter->writeAttribute('fontId', (int) $this->getParentWriter()->getFontHashTable()->getIndexForHashCode($style->getFont()->getHashCode())); + if ($style->getQuotePrefix()) { $objWriter->writeAttribute('quotePrefix', 1); } - if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) { - $objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164)); + if ($style->getNumberFormat()->getBuiltInFormatCode() === false) { + $objWriter->writeAttribute('numFmtId', (int) ($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($style->getNumberFormat()->getHashCode()) + 164)); } else { - $objWriter->writeAttribute('numFmtId', (int) $pStyle->getNumberFormat()->getBuiltInFormatCode()); + $objWriter->writeAttribute('numFmtId', (int) $style->getNumberFormat()->getBuiltInFormatCode()); } - $objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode())); - $objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode())); + $objWriter->writeAttribute('fillId', (int) $this->getParentWriter()->getFillHashTable()->getIndexForHashCode($style->getFill()->getHashCode())); + $objWriter->writeAttribute('borderId', (int) $this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($style->getBorders()->getHashCode())); // Apply styles? - $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0'); - $objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0'); - $objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0'); - $objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0'); - $objWriter->writeAttribute('applyAlignment', ($spreadsheet->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0'); - if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('applyFont', ($spreadsheet->getDefaultStyle()->getFont()->getHashCode() != $style->getFont()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyNumberFormat', ($spreadsheet->getDefaultStyle()->getNumberFormat()->getHashCode() != $style->getNumberFormat()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyFill', ($spreadsheet->getDefaultStyle()->getFill()->getHashCode() != $style->getFill()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyBorder', ($spreadsheet->getDefaultStyle()->getBorders()->getHashCode() != $style->getBorders()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyAlignment', ($spreadsheet->getDefaultStyle()->getAlignment()->getHashCode() != $style->getAlignment()->getHashCode()) ? '1' : '0'); + if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->writeAttribute('applyProtection', 'true'); } // alignment $objWriter->startElement('alignment'); - $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); - $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + $objWriter->writeAttribute('horizontal', $style->getAlignment()->getHorizontal()); + $objWriter->writeAttribute('vertical', $style->getAlignment()->getVertical()); $textRotation = 0; - if ($pStyle->getAlignment()->getTextRotation() >= 0) { - $textRotation = $pStyle->getAlignment()->getTextRotation(); - } elseif ($pStyle->getAlignment()->getTextRotation() < 0) { - $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + if ($style->getAlignment()->getTextRotation() >= 0) { + $textRotation = $style->getAlignment()->getTextRotation(); + } elseif ($style->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $style->getAlignment()->getTextRotation(); } $objWriter->writeAttribute('textRotation', $textRotation); - $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false')); - $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false')); + $objWriter->writeAttribute('wrapText', ($style->getAlignment()->getWrapText() ? 'true' : 'false')); + $objWriter->writeAttribute('shrinkToFit', ($style->getAlignment()->getShrinkToFit() ? 'true' : 'false')); - if ($pStyle->getAlignment()->getIndent() > 0) { - $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent()); + if ($style->getAlignment()->getIndent() > 0) { + $objWriter->writeAttribute('indent', $style->getAlignment()->getIndent()); } - if ($pStyle->getAlignment()->getReadOrder() > 0) { - $objWriter->writeAttribute('readingOrder', $pStyle->getAlignment()->getReadOrder()); + if ($style->getAlignment()->getReadOrder() > 0) { + $objWriter->writeAttribute('readingOrder', $style->getAlignment()->getReadOrder()); } $objWriter->endElement(); // protection - if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { + if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT || $style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { $objWriter->startElement('protection'); - if ($pStyle->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) { - $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + if ($style->getProtection()->getLocked() != Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } - if ($pStyle->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { - $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + if ($style->getProtection()->getHidden() != Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } @@ -442,59 +426,62 @@ private function writeCellStyleXf(XMLWriter $objWriter, \PhpOffice\PhpSpreadshee /** * Write Cell Style Dxf. - * - * @param XMLWriter $objWriter XML Writer - * @param \PhpOffice\PhpSpreadsheet\Style\Style $pStyle Style */ - private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $pStyle) + private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadsheet\Style\Style $style): void { // dxf $objWriter->startElement('dxf'); // font - $this->writeFont($objWriter, $pStyle->getFont()); + $this->writeFont($objWriter, $style->getFont()); // numFmt - $this->writeNumFmt($objWriter, $pStyle->getNumberFormat()); + $this->writeNumFmt($objWriter, $style->getNumberFormat()); // fill - $this->writeFill($objWriter, $pStyle->getFill()); + $this->writeFill($objWriter, $style->getFill()); // alignment $objWriter->startElement('alignment'); - if ($pStyle->getAlignment()->getHorizontal() !== null) { - $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); + if ($style->getAlignment()->getHorizontal() !== null) { + $objWriter->writeAttribute('horizontal', $style->getAlignment()->getHorizontal()); } - if ($pStyle->getAlignment()->getVertical() !== null) { - $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + if ($style->getAlignment()->getVertical() !== null) { + $objWriter->writeAttribute('vertical', $style->getAlignment()->getVertical()); } - if ($pStyle->getAlignment()->getTextRotation() !== null) { + if ($style->getAlignment()->getTextRotation() !== null) { $textRotation = 0; - if ($pStyle->getAlignment()->getTextRotation() >= 0) { - $textRotation = $pStyle->getAlignment()->getTextRotation(); - } elseif ($pStyle->getAlignment()->getTextRotation() < 0) { - $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + if ($style->getAlignment()->getTextRotation() >= 0) { + $textRotation = $style->getAlignment()->getTextRotation(); + } elseif ($style->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $style->getAlignment()->getTextRotation(); } $objWriter->writeAttribute('textRotation', $textRotation); } $objWriter->endElement(); // border - $this->writeBorder($objWriter, $pStyle->getBorders()); + $this->writeBorder($objWriter, $style->getBorders()); // protection - if (($pStyle->getProtection()->getLocked() !== null) || ($pStyle->getProtection()->getHidden() !== null)) { - if ($pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT || - $pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT) { + if (($style->getProtection()->getLocked() !== null) || ($style->getProtection()->getHidden() !== null)) { + if ( + $style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT || + $style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT + ) { $objWriter->startElement('protection'); - if (($pStyle->getProtection()->getLocked() !== null) && - ($pStyle->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT)) { - $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + if ( + ($style->getProtection()->getLocked() !== null) && + ($style->getProtection()->getLocked() !== Protection::PROTECTION_INHERIT) + ) { + $objWriter->writeAttribute('locked', ($style->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } - if (($pStyle->getProtection()->getHidden() !== null) && - ($pStyle->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT)) { - $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + if ( + ($style->getProtection()->getHidden() !== null) && + ($style->getProtection()->getHidden() !== Protection::PROTECTION_INHERIT) + ) { + $objWriter->writeAttribute('hidden', ($style->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED ? 'true' : 'false')); } $objWriter->endElement(); } @@ -506,20 +493,18 @@ private function writeCellStyleDxf(XMLWriter $objWriter, \PhpOffice\PhpSpreadshe /** * Write BorderPr. * - * @param XMLWriter $objWriter XML Writer - * @param string $pName Element name - * @param Border $pBorder Border style + * @param string $name Element name */ - private function writeBorderPr(XMLWriter $objWriter, $pName, Border $pBorder) + private function writeBorderPr(XMLWriter $objWriter, $name, Border $border): void { // Write BorderPr - if ($pBorder->getBorderStyle() != Border::BORDER_NONE) { - $objWriter->startElement($pName); - $objWriter->writeAttribute('style', $pBorder->getBorderStyle()); + if ($border->getBorderStyle() != Border::BORDER_NONE) { + $objWriter->startElement($name); + $objWriter->writeAttribute('style', $border->getBorderStyle()); // color $objWriter->startElement('color'); - $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB()); + $objWriter->writeAttribute('rgb', $border->getColor()->getARGB()); $objWriter->endElement(); $objWriter->endElement(); @@ -529,19 +514,17 @@ private function writeBorderPr(XMLWriter $objWriter, $pName, Border $pBorder) /** * Write NumberFormat. * - * @param XMLWriter $objWriter XML Writer - * @param NumberFormat $pNumberFormat Number Format - * @param int $pId Number Format identifier + * @param int $id Number Format identifier */ - private function writeNumFmt(XMLWriter $objWriter, NumberFormat $pNumberFormat, $pId = 0) + private function writeNumFmt(XMLWriter $objWriter, NumberFormat $numberFormat, $id = 0): void { // Translate formatcode - $formatCode = $pNumberFormat->getFormatCode(); + $formatCode = $numberFormat->getFormatCode(); // numFmt if ($formatCode !== null) { $objWriter->startElement('numFmt'); - $objWriter->writeAttribute('numFmtId', ($pId + 164)); + $objWriter->writeAttribute('numFmtId', ($id + 164)); $objWriter->writeAttribute('formatCode', $formatCode); $objWriter->endElement(); } @@ -550,8 +533,6 @@ private function writeNumFmt(XMLWriter $objWriter, NumberFormat $pNumberFormat, /** * Get an array of all styles. * - * @param Spreadsheet $spreadsheet - * * @return \PhpOffice\PhpSpreadsheet\Style\Style[] All styles in PhpSpreadsheet */ public function allStyles(Spreadsheet $spreadsheet) @@ -562,8 +543,6 @@ public function allStyles(Spreadsheet $spreadsheet) /** * Get an array of all conditional styles. * - * @param Spreadsheet $spreadsheet - * * @return Conditional[] All conditional styles in PhpSpreadsheet */ public function allConditionalStyles(Spreadsheet $spreadsheet) @@ -586,8 +565,6 @@ public function allConditionalStyles(Spreadsheet $spreadsheet) /** * Get an array of all fills. * - * @param Spreadsheet $spreadsheet - * * @return Fill[] All fills in PhpSpreadsheet */ public function allFills(Spreadsheet $spreadsheet) @@ -618,8 +595,6 @@ public function allFills(Spreadsheet $spreadsheet) /** * Get an array of all fonts. * - * @param Spreadsheet $spreadsheet - * * @return Font[] All fonts in PhpSpreadsheet */ public function allFonts(Spreadsheet $spreadsheet) @@ -641,8 +616,6 @@ public function allFonts(Spreadsheet $spreadsheet) /** * Get an array of all borders. * - * @param Spreadsheet $spreadsheet - * * @return Borders[] All borders in PhpSpreadsheet */ public function allBorders(Spreadsheet $spreadsheet) @@ -664,8 +637,6 @@ public function allBorders(Spreadsheet $spreadsheet) /** * Get an array of all number formats. * - * @param Spreadsheet $spreadsheet - * * @return NumberFormat[] All number formats in PhpSpreadsheet */ public function allNumberFormats(Spreadsheet $spreadsheet) diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Table.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Table.php new file mode 100644 index 00000000..67dbd19b --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Table.php @@ -0,0 +1,111 @@ +getParentWriter()->getUseDiskCaching()) { + $objWriter = new XMLWriter(XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new XMLWriter(XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Table + $name = 'Table' . $tableRef; + $range = $table->getRange(); + + $objWriter->startElement('table'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('id', (string) $tableRef); + $objWriter->writeAttribute('name', $name); + $objWriter->writeAttribute('displayName', $table->getName() ?: $name); + $objWriter->writeAttribute('ref', $range); + $objWriter->writeAttribute('headerRowCount', $table->getShowHeaderRow() ? '1' : '0'); + $objWriter->writeAttribute('totalsRowCount', $table->getShowTotalsRow() ? '1' : '0'); + + // Table Boundaries + [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($table->getRange()); + + // Table Auto Filter + if ($table->getShowHeaderRow()) { + $objWriter->startElement('autoFilter'); + $objWriter->writeAttribute('ref', $range); + foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { + $column = $table->getColumnByOffset($offset); + + if (!$column->getShowFilterButton()) { + $objWriter->startElement('filterColumn'); + $objWriter->writeAttribute('colId', (string) $offset); + $objWriter->writeAttribute('hiddenButton', '1'); + $objWriter->endElement(); + } + } + $objWriter->endElement(); + } + + // Table Columns + $objWriter->startElement('tableColumns'); + $objWriter->writeAttribute('count', (string) ($rangeEnd[0] - $rangeStart[0] + 1)); + foreach (range($rangeStart[0], $rangeEnd[0]) as $offset => $columnIndex) { + $worksheet = $table->getWorksheet(); + if (!$worksheet) { + continue; + } + + $column = $table->getColumnByOffset($offset); + $cell = $worksheet->getCellByColumnAndRow($columnIndex, $rangeStart[1]); + + $objWriter->startElement('tableColumn'); + $objWriter->writeAttribute('id', (string) ($offset + 1)); + $objWriter->writeAttribute('name', $table->getShowHeaderRow() ? $cell->getValue() : 'Column' . ($offset + 1)); + + if ($table->getShowTotalsRow()) { + if ($column->getTotalsRowLabel()) { + $objWriter->writeAttribute('totalsRowLabel', $column->getTotalsRowLabel()); + } + if ($column->getTotalsRowFunction()) { + $objWriter->writeAttribute('totalsRowFunction', $column->getTotalsRowFunction()); + } + } + if ($column->getColumnFormula()) { + $objWriter->writeElement('calculatedColumnFormula', $column->getColumnFormula()); + } + + $objWriter->endElement(); + } + $objWriter->endElement(); + + // Table Styles + $objWriter->startElement('tableStyleInfo'); + $objWriter->writeAttribute('name', $table->getStyle()->getTheme()); + $objWriter->writeAttribute('showFirstColumn', $table->getStyle()->getShowFirstColumn() ? '1' : '0'); + $objWriter->writeAttribute('showLastColumn', $table->getStyle()->getShowLastColumn() ? '1' : '0'); + $objWriter->writeAttribute('showRowStripes', $table->getStyle()->getShowRowStripes() ? '1' : '0'); + $objWriter->writeAttribute('showColumnStripes', $table->getStyle()->getShowColumnStripes() ? '1' : '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } +} diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php index f5f8dc07..99177292 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Theme.php @@ -5,17 +5,12 @@ use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; -/** - * @category PhpSpreadsheet - * - * @copyright Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) - */ class Theme extends WriterPart { /** * Map of Major fonts to write. * - * @var array of string + * @var string[] */ private static $majorFonts = [ 'Jpan' => 'MS Pゴシック', @@ -53,7 +48,7 @@ class Theme extends WriterPart /** * Map of Minor fonts to write. * - * @var array of string + * @var string[] */ private static $minorFonts = [ 'Jpan' => 'MS Pゴシック', @@ -91,7 +86,7 @@ class Theme extends WriterPart /** * Map of core colours. * - * @var array of string + * @var string[] */ private static $colourScheme = [ 'dk2' => '1F497D', @@ -109,10 +104,6 @@ class Theme extends WriterPart /** * Write theme to XML format. * - * @param Spreadsheet $spreadsheet - * - * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception - * * @return string XML Output */ public function writeTheme(Spreadsheet $spreadsheet) @@ -793,13 +784,9 @@ public function writeTheme(Spreadsheet $spreadsheet) /** * Write fonts to XML format. * - * @param XMLWriter $objWriter - * @param string $latinFont - * @param array of string $fontSet - * - * @return string XML Output + * @param string[] $fontSet */ - private function writeFonts($objWriter, $latinFont, $fontSet) + private function writeFonts(XMLWriter $objWriter, string $latinFont, array $fontSet): void { // a:latin $objWriter->startElement('a:latin'); @@ -826,12 +813,8 @@ private function writeFonts($objWriter, $latinFont, $fontSet) /** * Write colour scheme to XML format. - * - * @param XMLWriter $objWriter - * - * @return string XML Output */ - private function writeColourScheme($objWriter) + private function writeColourScheme(XMLWriter $objWriter): void { foreach (self::$colourScheme as $colourName => $colourValue) { $objWriter->startElement('a:' . $colourName); diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php index fd936748..f9d7197d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Workbook.php @@ -2,24 +2,19 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; -use PhpOffice\PhpSpreadsheet\Cell\Coordinate; -use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; +use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DefinedNames as DefinedNamesWriter; class Workbook extends WriterPart { /** * Write workbook to XML format. * - * @param Spreadsheet $spreadsheet * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing * - * @throws WriterException - * * @return string XML Output */ public function writeWorkbook(Spreadsheet $spreadsheet, $recalcRequired = false) @@ -58,7 +53,7 @@ public function writeWorkbook(Spreadsheet $spreadsheet, $recalcRequired = false) $this->writeSheets($objWriter, $spreadsheet); // definedNames - $this->writeDefinedNames($objWriter, $spreadsheet); + (new DefinedNamesWriter($objWriter, $spreadsheet))->write(); // calcPr $this->writeCalcPr($objWriter, $recalcRequired); @@ -71,10 +66,8 @@ public function writeWorkbook(Spreadsheet $spreadsheet, $recalcRequired = false) /** * Write file version. - * - * @param XMLWriter $objWriter XML Writer */ - private function writeFileVersion(XMLWriter $objWriter) + private function writeFileVersion(XMLWriter $objWriter): void { $objWriter->startElement('fileVersion'); $objWriter->writeAttribute('appName', 'xl'); @@ -86,10 +79,8 @@ private function writeFileVersion(XMLWriter $objWriter) /** * Write WorkbookPr. - * - * @param XMLWriter $objWriter XML Writer */ - private function writeWorkbookPr(XMLWriter $objWriter) + private function writeWorkbookPr(XMLWriter $objWriter): void { $objWriter->startElement('workbookPr'); @@ -104,11 +95,8 @@ private function writeWorkbookPr(XMLWriter $objWriter) /** * Write BookViews. - * - * @param XMLWriter $objWriter XML Writer - * @param Spreadsheet $spreadsheet */ - private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet) + private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // bookViews $objWriter->startElement('bookViews'); @@ -133,11 +121,8 @@ private function writeBookViews(XMLWriter $objWriter, Spreadsheet $spreadsheet) /** * Write WorkbookProtection. - * - * @param XMLWriter $objWriter XML Writer - * @param Spreadsheet $spreadsheet */ - private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet) + private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { if ($spreadsheet->getSecurity()->isSecurityEnabled()) { $objWriter->startElement('workbookProtection'); @@ -160,10 +145,9 @@ private function writeWorkbookProtection(XMLWriter $objWriter, Spreadsheet $spre /** * Write calcPr. * - * @param XMLWriter $objWriter XML Writer * @param bool $recalcRequired Indicate whether formulas should be recalculated before writing */ - private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true) + private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true): void { $objWriter->startElement('calcPr'); @@ -182,13 +166,8 @@ private function writeCalcPr(XMLWriter $objWriter, $recalcRequired = true) /** * Write sheets. - * - * @param XMLWriter $objWriter XML Writer - * @param Spreadsheet $spreadsheet - * - * @throws WriterException */ - private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet) + private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet): void { // Write sheets $objWriter->startElement('sheets'); @@ -210,217 +189,25 @@ private function writeSheets(XMLWriter $objWriter, Spreadsheet $spreadsheet) /** * Write sheet. * - * @param XMLWriter $objWriter XML Writer - * @param string $pSheetname Sheet name - * @param int $pSheetId Sheet id - * @param int $pRelId Relationship ID + * @param string $worksheetName Sheet name + * @param int $worksheetId Sheet id + * @param int $relId Relationship ID * @param string $sheetState Sheet state (visible, hidden, veryHidden) - * - * @throws WriterException */ - private function writeSheet(XMLWriter $objWriter, $pSheetname, $pSheetId = 1, $pRelId = 1, $sheetState = 'visible') + private function writeSheet(XMLWriter $objWriter, $worksheetName, $worksheetId = 1, $relId = 1, $sheetState = 'visible'): void { - if ($pSheetname != '') { + if ($worksheetName != '') { // Write sheet $objWriter->startElement('sheet'); - $objWriter->writeAttribute('name', $pSheetname); - $objWriter->writeAttribute('sheetId', $pSheetId); + $objWriter->writeAttribute('name', $worksheetName); + $objWriter->writeAttribute('sheetId', $worksheetId); if ($sheetState !== 'visible' && $sheetState != '') { $objWriter->writeAttribute('state', $sheetState); } - $objWriter->writeAttribute('r:id', 'rId' . $pRelId); + $objWriter->writeAttribute('r:id', 'rId' . $relId); $objWriter->endElement(); } else { throw new WriterException('Invalid parameters passed.'); } } - - /** - * Write Defined Names. - * - * @param XMLWriter $objWriter XML Writer - * @param Spreadsheet $spreadsheet - * - * @throws WriterException - */ - private function writeDefinedNames(XMLWriter $objWriter, Spreadsheet $spreadsheet) - { - // Write defined names - $objWriter->startElement('definedNames'); - - // Named ranges - if (count($spreadsheet->getNamedRanges()) > 0) { - // Named ranges - $this->writeNamedRanges($objWriter, $spreadsheet); - } - - // Other defined names - $sheetCount = $spreadsheet->getSheetCount(); - for ($i = 0; $i < $sheetCount; ++$i) { - // definedName for autoFilter - $this->writeDefinedNameForAutofilter($objWriter, $spreadsheet->getSheet($i), $i); - - // definedName for Print_Titles - $this->writeDefinedNameForPrintTitles($objWriter, $spreadsheet->getSheet($i), $i); - - // definedName for Print_Area - $this->writeDefinedNameForPrintArea($objWriter, $spreadsheet->getSheet($i), $i); - } - - $objWriter->endElement(); - } - - /** - * Write named ranges. - * - * @param XMLWriter $objWriter XML Writer - * @param Spreadsheet $spreadsheet - * - * @throws WriterException - */ - private function writeNamedRanges(XMLWriter $objWriter, Spreadsheet $spreadsheet) - { - // Loop named ranges - $namedRanges = $spreadsheet->getNamedRanges(); - foreach ($namedRanges as $namedRange) { - $this->writeDefinedNameForNamedRange($objWriter, $namedRange); - } - } - - /** - * Write Defined Name for named range. - * - * @param XMLWriter $objWriter XML Writer - * @param NamedRange $pNamedRange - */ - private function writeDefinedNameForNamedRange(XMLWriter $objWriter, NamedRange $pNamedRange) - { - // definedName for named range - $objWriter->startElement('definedName'); - $objWriter->writeAttribute('name', $pNamedRange->getName()); - if ($pNamedRange->getLocalOnly()) { - $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope())); - } - - // Create absolute coordinate and write as raw text - $range = Coordinate::splitRange($pNamedRange->getRange()); - $iMax = count($range); - for ($i = 0; $i < $iMax; ++$i) { - $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . Coordinate::absoluteReference($range[$i][0]); - if (isset($range[$i][1])) { - $range[$i][1] = Coordinate::absoluteReference($range[$i][1]); - } - } - $range = Coordinate::buildRange($range); - - $objWriter->writeRawData($range); - - $objWriter->endElement(); - } - - /** - * Write Defined Name for autoFilter. - * - * @param XMLWriter $objWriter XML Writer - * @param Worksheet $pSheet - * @param int $pSheetId - */ - private function writeDefinedNameForAutofilter(XMLWriter $objWriter, Worksheet $pSheet, $pSheetId = 0) - { - // definedName for autoFilter - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); - if (!empty($autoFilterRange)) { - $objWriter->startElement('definedName'); - $objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); - $objWriter->writeAttribute('localSheetId', $pSheetId); - $objWriter->writeAttribute('hidden', '1'); - - // Create absolute coordinate and write as raw text - $range = Coordinate::splitRange($autoFilterRange); - $range = $range[0]; - // Strip any worksheet ref so we can make the cell ref absolute - [$ws, $range[0]] = Worksheet::extractSheetTitle($range[0], true); - - $range[0] = Coordinate::absoluteCoordinate($range[0]); - $range[1] = Coordinate::absoluteCoordinate($range[1]); - $range = implode(':', $range); - - $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range); - - $objWriter->endElement(); - } - } - - /** - * Write Defined Name for PrintTitles. - * - * @param XMLWriter $objWriter XML Writer - * @param Worksheet $pSheet - * @param int $pSheetId - */ - private function writeDefinedNameForPrintTitles(XMLWriter $objWriter, Worksheet $pSheet, $pSheetId = 0) - { - // definedName for PrintTitles - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - $objWriter->startElement('definedName'); - $objWriter->writeAttribute('name', '_xlnm.Print_Titles'); - $objWriter->writeAttribute('localSheetId', $pSheetId); - - // Setting string - $settingString = ''; - - // Columns to repeat - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { - $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); - - $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; - } - - // Rows to repeat - if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { - if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { - $settingString .= ','; - } - - $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop(); - - $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; - } - - $objWriter->writeRawData($settingString); - - $objWriter->endElement(); - } - } - - /** - * Write Defined Name for PrintTitles. - * - * @param XMLWriter $objWriter XML Writer - * @param Worksheet $pSheet - * @param int $pSheetId - */ - private function writeDefinedNameForPrintArea(XMLWriter $objWriter, Worksheet $pSheet, $pSheetId = 0) - { - // definedName for PrintArea - if ($pSheet->getPageSetup()->isPrintAreaSet()) { - $objWriter->startElement('definedName'); - $objWriter->writeAttribute('name', '_xlnm.Print_Area'); - $objWriter->writeAttribute('localSheetId', $pSheetId); - - // Print area - $printArea = Coordinate::splitRange($pSheet->getPageSetup()->getPrintArea()); - - $chunks = []; - foreach ($printArea as $printAreaRect) { - $printAreaRect[0] = Coordinate::absoluteReference($printAreaRect[0]); - $printAreaRect[1] = Coordinate::absoluteReference($printAreaRect[1]); - $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect); - } - - $objWriter->writeRawData(implode(',', $chunks)); - - $objWriter->endElement(); - } - } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php index 1d5a995a..eba4c927 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Worksheet.php @@ -2,37 +2,33 @@ namespace PhpOffice\PhpSpreadsheet\Writer\Xlsx; +use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; +use PhpOffice\PhpSpreadsheet\Calculation\Information\Value; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\RichText\RichText; +use PhpOffice\PhpSpreadsheet\Settings; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Shared\XMLWriter; use PhpOffice\PhpSpreadsheet\Style\Conditional; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar; +use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalFormattingRuleExtension; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column; use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule; use PhpOffice\PhpSpreadsheet\Worksheet\SheetView; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet; -use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; -/** - * @category PhpSpreadsheet - * - * @copyright Copyright (c) 2006 - 2015 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet) - */ class Worksheet extends WriterPart { /** * Write worksheet to XML format. * - * @param PhpspreadsheetWorksheet $pSheet - * @param string[] $pStringTable + * @param string[] $stringTable * @param bool $includeCharts Flag indicating if we should write charts * - * @throws WriterException - * * @return string XML Output */ - public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = null, $includeCharts = false) + public function writeWorksheet(PhpspreadsheetWorksheet $worksheet, $stringTable = null, $includeCharts = false) { // Create XML writer $objWriter = null; @@ -53,75 +49,83 @@ public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); $objWriter->writeAttribute('xmlns:x14', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); + $objWriter->writeAttribute('xmlns:xm', 'http://schemas.microsoft.com/office/excel/2006/main'); $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); $objWriter->writeAttribute('mc:Ignorable', 'x14ac'); $objWriter->writeAttribute('xmlns:x14ac', 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); // sheetPr - $this->writeSheetPr($objWriter, $pSheet); + $this->writeSheetPr($objWriter, $worksheet); // Dimension - $this->writeDimension($objWriter, $pSheet); + $this->writeDimension($objWriter, $worksheet); // sheetViews - $this->writeSheetViews($objWriter, $pSheet); + $this->writeSheetViews($objWriter, $worksheet); // sheetFormatPr - $this->writeSheetFormatPr($objWriter, $pSheet); + $this->writeSheetFormatPr($objWriter, $worksheet); // cols - $this->writeCols($objWriter, $pSheet); + $this->writeCols($objWriter, $worksheet); // sheetData - $this->writeSheetData($objWriter, $pSheet, $pStringTable); + $this->writeSheetData($objWriter, $worksheet, $stringTable); // sheetProtection - $this->writeSheetProtection($objWriter, $pSheet); + $this->writeSheetProtection($objWriter, $worksheet); // protectedRanges - $this->writeProtectedRanges($objWriter, $pSheet); + $this->writeProtectedRanges($objWriter, $worksheet); // autoFilter - $this->writeAutoFilter($objWriter, $pSheet); + $this->writeAutoFilter($objWriter, $worksheet); // mergeCells - $this->writeMergeCells($objWriter, $pSheet); + $this->writeMergeCells($objWriter, $worksheet); // conditionalFormatting - $this->writeConditionalFormatting($objWriter, $pSheet); + $this->writeConditionalFormatting($objWriter, $worksheet); // dataValidations - $this->writeDataValidations($objWriter, $pSheet); + $this->writeDataValidations($objWriter, $worksheet); // hyperlinks - $this->writeHyperlinks($objWriter, $pSheet); + $this->writeHyperlinks($objWriter, $worksheet); // Print options - $this->writePrintOptions($objWriter, $pSheet); + $this->writePrintOptions($objWriter, $worksheet); // Page margins - $this->writePageMargins($objWriter, $pSheet); + $this->writePageMargins($objWriter, $worksheet); // Page setup - $this->writePageSetup($objWriter, $pSheet); + $this->writePageSetup($objWriter, $worksheet); // Header / footer - $this->writeHeaderFooter($objWriter, $pSheet); + $this->writeHeaderFooter($objWriter, $worksheet); // Breaks - $this->writeBreaks($objWriter, $pSheet); + $this->writeBreaks($objWriter, $worksheet); // Drawings and/or Charts - $this->writeDrawings($objWriter, $pSheet, $includeCharts); + $this->writeDrawings($objWriter, $worksheet, $includeCharts); // LegacyDrawing - $this->writeLegacyDrawing($objWriter, $pSheet); + $this->writeLegacyDrawing($objWriter, $worksheet); // LegacyDrawingHF - $this->writeLegacyDrawingHF($objWriter, $pSheet); + $this->writeLegacyDrawingHF($objWriter, $worksheet); // AlternateContent - $this->writeAlternateContent($objWriter, $pSheet); + $this->writeAlternateContent($objWriter, $worksheet); + + // Table + $this->writeTable($objWriter, $worksheet); + + // ConditionalFormattingRuleExtensionList + // (Must be inserted last. Not insert last, an Excel parse error will occur) + $this->writeExtLst($objWriter, $worksheet); $objWriter->endElement(); @@ -131,42 +135,41 @@ public function writeWorksheet(PhpspreadsheetWorksheet $pSheet, $pStringTable = /** * Write SheetPr. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetPr $objWriter->startElement('sheetPr'); - if ($pSheet->getParent()->hasMacros()) { + if ($worksheet->getParent()->hasMacros()) { //if the workbook have macros, we need to have codeName for the sheet - if (!$pSheet->hasCodeName()) { - $pSheet->setCodeName($pSheet->getTitle()); + if (!$worksheet->hasCodeName()) { + $worksheet->setCodeName($worksheet->getTitle()); } - $objWriter->writeAttribute('codeName', $pSheet->getCodeName()); + self::writeAttributeNotNull($objWriter, 'codeName', $worksheet->getCodeName()); } - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { $objWriter->writeAttribute('filterMode', 1); - $pSheet->getAutoFilter()->showHideRows(); + if (!$worksheet->getAutoFilter()->getEvaluated()) { + $worksheet->getAutoFilter()->showHideRows(); + } } // tabColor - if ($pSheet->isTabColorSet()) { + if ($worksheet->isTabColorSet()) { $objWriter->startElement('tabColor'); - $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); + $objWriter->writeAttribute('rgb', $worksheet->getTabColor()->getARGB()); $objWriter->endElement(); } // outlinePr $objWriter->startElement('outlinePr'); - $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); - $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); + $objWriter->writeAttribute('summaryBelow', ($worksheet->getShowSummaryBelow() ? '1' : '0')); + $objWriter->writeAttribute('summaryRight', ($worksheet->getShowSummaryRight() ? '1' : '0')); $objWriter->endElement(); // pageSetUpPr - if ($pSheet->getPageSetup()->getFitToPage()) { + if ($worksheet->getPageSetup()->getFitToPage()) { $objWriter->startElement('pageSetUpPr'); $objWriter->writeAttribute('fitToPage', '1'); $objWriter->endElement(); @@ -177,34 +180,26 @@ private function writeSheetPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSh /** * Write Dimension. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeDimension(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // dimension $objWriter->startElement('dimension'); - $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); + $objWriter->writeAttribute('ref', $worksheet->calculateWorksheetDimension()); $objWriter->endElement(); } /** * Write SheetViews. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet - * - * @throws WriterException */ - private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetViews $objWriter->startElement('sheetViews'); // Sheet selected? $sheetSelected = false; - if ($this->getParentWriter()->getSpreadsheet()->getIndex($pSheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { + if ($this->getParentWriter()->getSpreadsheet()->getIndex($worksheet) == $this->getParentWriter()->getSpreadsheet()->getActiveSheetIndex()) { $sheetSelected = true; } @@ -214,55 +209,54 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('workbookViewId', '0'); // Zoom scales - if ($pSheet->getSheetView()->getZoomScale() != 100) { - $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + if ($worksheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', (string) $worksheet->getSheetView()->getZoomScale()); } - if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { - $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + if ($worksheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', (string) $worksheet->getSheetView()->getZoomScaleNormal()); } // Show zeros (Excel also writes this attribute only if set to false) - if ($pSheet->getSheetView()->getShowZeros() === false) { + if ($worksheet->getSheetView()->getShowZeros() === false) { $objWriter->writeAttribute('showZeros', 0); } // View Layout Type - if ($pSheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { - $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + if ($worksheet->getSheetView()->getView() !== SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $worksheet->getSheetView()->getView()); } // Gridlines - if ($pSheet->getShowGridlines()) { + if ($worksheet->getShowGridlines()) { $objWriter->writeAttribute('showGridLines', 'true'); } else { $objWriter->writeAttribute('showGridLines', 'false'); } // Row and column headers - if ($pSheet->getShowRowColHeaders()) { + if ($worksheet->getShowRowColHeaders()) { $objWriter->writeAttribute('showRowColHeaders', '1'); } else { $objWriter->writeAttribute('showRowColHeaders', '0'); } // Right-to-left - if ($pSheet->getRightToLeft()) { + if ($worksheet->getRightToLeft()) { $objWriter->writeAttribute('rightToLeft', 'true'); } - $activeCell = $pSheet->getActiveCell(); - $sqref = $pSheet->getSelectedCells(); + $topLeftCell = $worksheet->getTopLeftCell(); + $activeCell = $worksheet->getActiveCell(); + $sqref = $worksheet->getSelectedCells(); // Pane $pane = ''; - if ($pSheet->getFreezePane()) { - [$xSplit, $ySplit] = Coordinate::coordinateFromString($pSheet->getFreezePane()); + if ($worksheet->getFreezePane()) { + [$xSplit, $ySplit] = Coordinate::coordinateFromString($worksheet->getFreezePane() ?? ''); $xSplit = Coordinate::columnIndexFromString($xSplit); --$xSplit; --$ySplit; - $topLeftCell = $pSheet->getTopLeftCell(); - // pane $pane = 'topRight'; $objWriter->startElement('pane'); @@ -273,7 +267,7 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('ySplit', $ySplit); $pane = ($xSplit > 0) ? 'bottomRight' : 'bottomLeft'; } - $objWriter->writeAttribute('topLeftCell', $topLeftCell); + self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); $objWriter->writeAttribute('activePane', $pane); $objWriter->writeAttribute('state', 'frozen'); $objWriter->endElement(); @@ -287,6 +281,8 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement(); } + } else { + self::writeAttributeNotNull($objWriter, 'topLeftCell', $topLeftCell); } // Selection @@ -307,37 +303,36 @@ private function writeSheetViews(XMLWriter $objWriter, PhpspreadsheetWorksheet $ /** * Write SheetFormatPr. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetFormatPr $objWriter->startElement('sheetFormatPr'); // Default row height - if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { + if ($worksheet->getDefaultRowDimension()->getRowHeight() >= 0) { $objWriter->writeAttribute('customHeight', 'true'); - $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); + $objWriter->writeAttribute('defaultRowHeight', StringHelper::formatNumber($worksheet->getDefaultRowDimension()->getRowHeight())); } else { $objWriter->writeAttribute('defaultRowHeight', '14.4'); } // Set Zero Height row - if ((string) $pSheet->getDefaultRowDimension()->getZeroHeight() === '1' || - strtolower((string) $pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true') { + if ( + (string) $worksheet->getDefaultRowDimension()->getZeroHeight() === '1' || + strtolower((string) $worksheet->getDefaultRowDimension()->getZeroHeight()) == 'true' + ) { $objWriter->writeAttribute('zeroHeight', '1'); } // Default column width - if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { - $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($pSheet->getDefaultColumnDimension()->getWidth())); + if ($worksheet->getDefaultColumnDimension()->getWidth() >= 0) { + $objWriter->writeAttribute('defaultColWidth', StringHelper::formatNumber($worksheet->getDefaultColumnDimension()->getWidth())); } // Outline level - row $outlineLevelRow = 0; - foreach ($pSheet->getRowDimensions() as $dimension) { + foreach ($worksheet->getRowDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelRow) { $outlineLevelRow = $dimension->getOutlineLevel(); } @@ -346,7 +341,7 @@ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorkshee // Outline level - column $outlineLevelCol = 0; - foreach ($pSheet->getColumnDimensions() as $dimension) { + foreach ($worksheet->getColumnDimensions() as $dimension) { if ($dimension->getOutlineLevel() > $outlineLevelCol) { $outlineLevelCol = $dimension->getOutlineLevel(); } @@ -358,20 +353,17 @@ private function writeSheetFormatPr(XMLWriter $objWriter, PhpspreadsheetWorkshee /** * Write Cols. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // cols - if (count($pSheet->getColumnDimensions()) > 0) { + if (count($worksheet->getColumnDimensions()) > 0) { $objWriter->startElement('cols'); - $pSheet->calculateColumnWidths(); + $worksheet->calculateColumnWidths(); // Loop through column dimensions - foreach ($pSheet->getColumnDimensions() as $colDimension) { + foreach ($worksheet->getColumnDimensions() as $colDimension) { // col $objWriter->startElement('col'); $objWriter->writeAttribute('min', Coordinate::columnIndexFromString($colDimension->getColumnIndex())); @@ -396,7 +388,7 @@ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet } // Custom width? - if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { + if ($colDimension->getWidth() != $worksheet->getDefaultColumnDimension()->getWidth()) { $objWriter->writeAttribute('customWidth', 'true'); } @@ -422,132 +414,314 @@ private function writeCols(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet /** * Write SheetProtection. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeSheetProtection(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // sheetProtection $objWriter->startElement('sheetProtection'); - if ($pSheet->getProtection()->getPassword() !== '') { - $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword()); - } - - $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false')); - $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false')); - $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false')); - $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false')); - $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false')); - $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false')); - $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false')); - $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false')); - $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false')); - $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false')); - $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false')); - $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false')); - $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false')); - $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false')); - $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false')); - $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false')); + $protection = $worksheet->getProtection(); + + if ($protection->getAlgorithm()) { + $objWriter->writeAttribute('algorithmName', $protection->getAlgorithm()); + $objWriter->writeAttribute('hashValue', $protection->getPassword()); + $objWriter->writeAttribute('saltValue', $protection->getSalt()); + $objWriter->writeAttribute('spinCount', $protection->getSpinCount()); + } elseif ($protection->getPassword() !== '') { + $objWriter->writeAttribute('password', $protection->getPassword()); + } + + $objWriter->writeAttribute('sheet', ($protection->getSheet() ? 'true' : 'false')); + $objWriter->writeAttribute('objects', ($protection->getObjects() ? 'true' : 'false')); + $objWriter->writeAttribute('scenarios', ($protection->getScenarios() ? 'true' : 'false')); + $objWriter->writeAttribute('formatCells', ($protection->getFormatCells() ? 'true' : 'false')); + $objWriter->writeAttribute('formatColumns', ($protection->getFormatColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('formatRows', ($protection->getFormatRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertColumns', ($protection->getInsertColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('insertRows', ($protection->getInsertRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertHyperlinks', ($protection->getInsertHyperlinks() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteColumns', ($protection->getDeleteColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteRows', ($protection->getDeleteRows() ? 'true' : 'false')); + $objWriter->writeAttribute('selectLockedCells', ($protection->getSelectLockedCells() ? 'true' : 'false')); + $objWriter->writeAttribute('sort', ($protection->getSort() ? 'true' : 'false')); + $objWriter->writeAttribute('autoFilter', ($protection->getAutoFilter() ? 'true' : 'false')); + $objWriter->writeAttribute('pivotTables', ($protection->getPivotTables() ? 'true' : 'false')); + $objWriter->writeAttribute('selectUnlockedCells', ($protection->getSelectUnlockedCells() ? 'true' : 'false')); $objWriter->endElement(); } + private static function writeAttributeIf(XMLWriter $objWriter, $condition, string $attr, string $val): void + { + if ($condition) { + $objWriter->writeAttribute($attr, $val); + } + } + + private static function writeAttributeNotNull(XMLWriter $objWriter, string $attr, ?string $val): void + { + if ($val !== null) { + $objWriter->writeAttribute($attr, $val); + } + } + + private static function writeElementIf(XMLWriter $objWriter, $condition, string $attr, string $val): void + { + if ($condition) { + $objWriter->writeElement($attr, $val); + } + } + + private static function writeOtherCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void + { + $conditions = $conditional->getConditions(); + if ( + $conditional->getConditionType() == Conditional::CONDITION_CELLIS + || $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION + || !empty($conditions) + ) { + foreach ($conditions as $formula) { + // Formula + if (is_bool($formula)) { + $formula = $formula ? 'TRUE' : 'FALSE'; + } + $objWriter->writeElement('formula', Xlfn::addXlfn("$formula")); + } + } else { + if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) { + // formula copied from ms xlsx xml source file + $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0'); + } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) { + // formula copied from ms xlsx xml source file + $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0'); + } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSERRORS) { + // formula copied from ms xlsx xml source file + $objWriter->writeElement('formula', 'ISERROR(' . $cellCoordinate . ')'); + } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSERRORS) { + // formula copied from ms xlsx xml source file + $objWriter->writeElement('formula', 'NOT(ISERROR(' . $cellCoordinate . '))'); + } + } + } + + private static function writeTimePeriodCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void + { + $txt = $conditional->getText(); + if ($txt !== null) { + $objWriter->writeAttribute('timePeriod', $txt); + if (empty($conditional->getConditions())) { + if ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TODAY) { + $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_TOMORROW) { + $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()+1'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_YESTERDAY) { + $objWriter->writeElement('formula', 'FLOOR(' . $cellCoordinate . ')=TODAY()-1'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_7_DAYS) { + $objWriter->writeElement('formula', 'AND(TODAY()-FLOOR(' . $cellCoordinate . ',1)<=6,FLOOR(' . $cellCoordinate . ',1)<=TODAY())'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_WEEK) { + $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<(WEEKDAY(TODAY())+7))'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_WEEK) { + $objWriter->writeElement('formula', 'AND(TODAY()-ROUNDDOWN(' . $cellCoordinate . ',0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<=7-WEEKDAY(TODAY()))'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_WEEK) { + $objWriter->writeElement('formula', 'AND(ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(' . $cellCoordinate . ',0)-TODAY()<(15-WEEKDAY(TODAY())))'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_LAST_MONTH) { + $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0-1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0-1)))'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_THIS_MONTH) { + $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(TODAY()),YEAR(' . $cellCoordinate . ')=YEAR(TODAY()))'); + } elseif ($conditional->getOperatorType() == Conditional::TIMEPERIOD_NEXT_MONTH) { + $objWriter->writeElement('formula', 'AND(MONTH(' . $cellCoordinate . ')=MONTH(EDATE(TODAY(),0+1)),YEAR(' . $cellCoordinate . ')=YEAR(EDATE(TODAY(),0+1)))'); + } + } else { + $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); + } + } + } + + private static function writeTextCondElements(XMLWriter $objWriter, Conditional $conditional, string $cellCoordinate): void + { + $txt = $conditional->getText(); + if ($txt !== null) { + $objWriter->writeAttribute('text', $txt); + if (empty($conditional->getConditions())) { + if ($conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT) { + $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . ')))'); + } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH) { + $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); + } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH) { + $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',LEN("' . $txt . '"))="' . $txt . '"'); + } elseif ($conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS) { + $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $txt . '",' . $cellCoordinate . '))'); + } + } else { + $objWriter->writeElement('formula', (string) ($conditional->getConditions()[0])); + } + } + } + + private static function writeExtConditionalFormattingElements(XMLWriter $objWriter, ConditionalFormattingRuleExtension $ruleExtension): void + { + $prefix = 'x14'; + $objWriter->startElementNs($prefix, 'conditionalFormatting', null); + + $objWriter->startElementNs($prefix, 'cfRule', null); + $objWriter->writeAttribute('type', $ruleExtension->getCfRule()); + $objWriter->writeAttribute('id', $ruleExtension->getId()); + $objWriter->startElementNs($prefix, 'dataBar', null); + $dataBar = $ruleExtension->getDataBarExt(); + foreach ($dataBar->getXmlAttributes() as $attrKey => $val) { + $objWriter->writeAttribute($attrKey, $val); + } + $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); + if ($minCfvo) { + $objWriter->startElementNs($prefix, 'cfvo', null); + $objWriter->writeAttribute('type', $minCfvo->getType()); + if ($minCfvo->getCellFormula()) { + $objWriter->writeElement('xm:f', $minCfvo->getCellFormula()); + } + $objWriter->endElement(); //end cfvo + } + + $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); + if ($maxCfvo) { + $objWriter->startElementNs($prefix, 'cfvo', null); + $objWriter->writeAttribute('type', $maxCfvo->getType()); + if ($maxCfvo->getCellFormula()) { + $objWriter->writeElement('xm:f', $maxCfvo->getCellFormula()); + } + $objWriter->endElement(); //end cfvo + } + + foreach ($dataBar->getXmlElements() as $elmKey => $elmAttr) { + $objWriter->startElementNs($prefix, $elmKey, null); + foreach ($elmAttr as $attrKey => $attrVal) { + $objWriter->writeAttribute($attrKey, $attrVal); + } + $objWriter->endElement(); //end elmKey + } + $objWriter->endElement(); //end dataBar + $objWriter->endElement(); //end cfRule + $objWriter->writeElement('xm:sqref', $ruleExtension->getSqref()); + $objWriter->endElement(); //end conditionalFormatting + } + + private static function writeDataBarElements(XMLWriter $objWriter, $dataBar): void + { + /** @var ConditionalDataBar $dataBar */ + if ($dataBar) { + $objWriter->startElement('dataBar'); + self::writeAttributeIf($objWriter, null !== $dataBar->getShowValue(), 'showValue', $dataBar->getShowValue() ? '1' : '0'); + + $minCfvo = $dataBar->getMinimumConditionalFormatValueObject(); + if ($minCfvo) { + $objWriter->startElement('cfvo'); + self::writeAttributeIf($objWriter, $minCfvo->getType(), 'type', (string) $minCfvo->getType()); + self::writeAttributeIf($objWriter, $minCfvo->getValue(), 'val', (string) $minCfvo->getValue()); + $objWriter->endElement(); + } + $maxCfvo = $dataBar->getMaximumConditionalFormatValueObject(); + if ($maxCfvo) { + $objWriter->startElement('cfvo'); + self::writeAttributeIf($objWriter, $maxCfvo->getType(), 'type', (string) $maxCfvo->getType()); + self::writeAttributeIf($objWriter, $maxCfvo->getValue(), 'val', (string) $maxCfvo->getValue()); + $objWriter->endElement(); + } + if ($dataBar->getColor()) { + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $dataBar->getColor()); + $objWriter->endElement(); + } + $objWriter->endElement(); // end dataBar + + if ($dataBar->getConditionalFormattingRuleExt()) { + $objWriter->startElement('extLst'); + $extension = $dataBar->getConditionalFormattingRuleExt(); + $objWriter->startElement('ext'); + $objWriter->writeAttribute('uri', '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}'); + $objWriter->startElementNs('x14', 'id', null); + $objWriter->text($extension->getId()); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); //end extLst + } + } + } + /** * Write ConditionalFormatting. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet - * - * @throws WriterException */ - private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeConditionalFormatting(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Conditional id $id = 1; // Loop through styles in the current worksheet - foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + $objWriter->startElement('conditionalFormatting'); + $objWriter->writeAttribute('sqref', $cellCoordinate); + foreach ($conditionalStyles as $conditional) { // WHY was this again? // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { // continue; // } - if ($conditional->getConditionType() != Conditional::CONDITION_NONE) { - // conditionalFormatting - $objWriter->startElement('conditionalFormatting'); - $objWriter->writeAttribute('sqref', $cellCoordinate); - - // cfRule - $objWriter->startElement('cfRule'); - $objWriter->writeAttribute('type', $conditional->getConditionType()); - $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())); - $objWriter->writeAttribute('priority', $id++); - - if (($conditional->getConditionType() == Conditional::CONDITION_CELLIS || $conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT) - && $conditional->getOperatorType() != Conditional::OPERATOR_NONE) { - $objWriter->writeAttribute('operator', $conditional->getOperatorType()); - } - - if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - && $conditional->getText() !== null) { - $objWriter->writeAttribute('text', $conditional->getText()); - } - - if ($conditional->getStopIfTrue()) { - $objWriter->writeAttribute('stopIfTrue', '1'); - } - - if ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == Conditional::OPERATOR_CONTAINSTEXT - && $conditional->getText() !== null) { - $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))'); - } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == Conditional::OPERATOR_BEGINSWITH - && $conditional->getText() !== null) { - $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); - } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == Conditional::OPERATOR_ENDSWITH - && $conditional->getText() !== null) { - $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); - } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - && $conditional->getOperatorType() == Conditional::OPERATOR_NOTCONTAINS - && $conditional->getText() !== null) { - $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))'); - } elseif ($conditional->getConditionType() == Conditional::CONDITION_CELLIS - || $conditional->getConditionType() == Conditional::CONDITION_CONTAINSTEXT - || $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) { - foreach ($conditional->getConditions() as $formula) { - // Formula - $objWriter->writeElement('formula', $formula); - } - } elseif ($conditional->getConditionType() == Conditional::CONDITION_CONTAINSBLANKS) { - // formula copied from ms xlsx xml source file - $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))=0'); - } elseif ($conditional->getConditionType() == Conditional::CONDITION_NOTCONTAINSBLANKS) { - // formula copied from ms xlsx xml source file - $objWriter->writeElement('formula', 'LEN(TRIM(' . $cellCoordinate . '))>0'); - } + // cfRule + $objWriter->startElement('cfRule'); + $objWriter->writeAttribute('type', $conditional->getConditionType()); + self::writeAttributeIf( + $objWriter, + ($conditional->getConditionType() != Conditional::CONDITION_DATABAR), + 'dxfId', + (string) $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) + ); + $objWriter->writeAttribute('priority', $id++); + + self::writeAttributeif( + $objWriter, + ( + $conditional->getConditionType() === Conditional::CONDITION_CELLIS + || $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH + || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH + ) && $conditional->getOperatorType() !== Conditional::OPERATOR_NONE, + 'operator', + $conditional->getOperatorType() + ); + + self::writeAttributeIf($objWriter, $conditional->getStopIfTrue(), 'stopIfTrue', '1'); + + $cellRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellCoordinate))); + [$topLeftCell] = $cellRange[0]; + + if ( + $conditional->getConditionType() === Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_NOTCONTAINSTEXT + || $conditional->getConditionType() === Conditional::CONDITION_BEGINSWITH + || $conditional->getConditionType() === Conditional::CONDITION_ENDSWITH + ) { + self::writeTextCondElements($objWriter, $conditional, $topLeftCell); + } elseif ($conditional->getConditionType() === Conditional::CONDITION_TIMEPERIOD) { + self::writeTimePeriodCondElements($objWriter, $conditional, $topLeftCell); + } else { + self::writeOtherCondElements($objWriter, $conditional, $topLeftCell); + } - $objWriter->endElement(); + // + self::writeDataBarElements($objWriter, $conditional->getDataBar()); - $objWriter->endElement(); - } + $objWriter->endElement(); //end cfRule } + + $objWriter->endElement(); //end conditionalFormatting } } /** * Write DataValidations. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Datavalidation collection - $dataValidationCollection = $pSheet->getDataValidationCollection(); + $dataValidationCollection = $worksheet->getDataValidationCollection(); // Write data validations? if (!empty($dataValidationCollection)) { @@ -588,7 +762,7 @@ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksh $objWriter->writeAttribute('prompt', $dv->getPrompt()); } - $objWriter->writeAttribute('sqref', $coordinate); + $objWriter->writeAttribute('sqref', $dv->getSqref() ?? $coordinate); if ($dv->getFormula1() !== '') { $objWriter->writeElement('formula1', $dv->getFormula1()); @@ -606,14 +780,11 @@ private function writeDataValidations(XMLWriter $objWriter, PhpspreadsheetWorksh /** * Write Hyperlinks. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Hyperlink collection - $hyperlinkCollection = $pSheet->getHyperlinkCollection(); + $hyperlinkCollection = $worksheet->getHyperlinkCollection(); // Relation ID $relationId = 1; @@ -647,18 +818,15 @@ private function writeHyperlinks(XMLWriter $objWriter, PhpspreadsheetWorksheet $ /** * Write ProtectedRanges. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (count($pSheet->getProtectedCells()) > 0) { + if (count($worksheet->getProtectedCells()) > 0) { // protectedRanges $objWriter->startElement('protectedRanges'); // Loop protectedRanges - foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + foreach ($worksheet->getProtectedCells() as $protectedCell => $passwordHash) { // protectedRange $objWriter->startElement('protectedRange'); $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); @@ -675,18 +843,15 @@ private function writeProtectedRanges(XMLWriter $objWriter, PhpspreadsheetWorksh /** * Write MergeCells. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (count($pSheet->getMergeCells()) > 0) { + if (count($worksheet->getMergeCells()) > 0) { // mergeCells $objWriter->startElement('mergeCells'); // Loop mergeCells - foreach ($pSheet->getMergeCells() as $mergeCell) { + foreach ($worksheet->getMergeCells() as $mergeCell) { // mergeCell $objWriter->startElement('mergeCell'); $objWriter->writeAttribute('ref', $mergeCell); @@ -699,23 +864,20 @@ private function writeMergeCells(XMLWriter $objWriter, PhpspreadsheetWorksheet $ /** * Write PrintOptions. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // printOptions $objWriter->startElement('printOptions'); - $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true' : 'false')); + $objWriter->writeAttribute('gridLines', ($worksheet->getPrintGridlines() ? 'true' : 'false')); $objWriter->writeAttribute('gridLinesSet', 'true'); - if ($pSheet->getPageSetup()->getHorizontalCentered()) { + if ($worksheet->getPageSetup()->getHorizontalCentered()) { $objWriter->writeAttribute('horizontalCentered', 'true'); } - if ($pSheet->getPageSetup()->getVerticalCentered()) { + if ($worksheet->getPageSetup()->getVerticalCentered()) { $objWriter->writeAttribute('verticalCentered', 'true'); } @@ -724,32 +886,26 @@ private function writePrintOptions(XMLWriter $objWriter, PhpspreadsheetWorksheet /** * Write PageMargins. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writePageMargins(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageMargins $objWriter->startElement('pageMargins'); - $objWriter->writeAttribute('left', StringHelper::formatNumber($pSheet->getPageMargins()->getLeft())); - $objWriter->writeAttribute('right', StringHelper::formatNumber($pSheet->getPageMargins()->getRight())); - $objWriter->writeAttribute('top', StringHelper::formatNumber($pSheet->getPageMargins()->getTop())); - $objWriter->writeAttribute('bottom', StringHelper::formatNumber($pSheet->getPageMargins()->getBottom())); - $objWriter->writeAttribute('header', StringHelper::formatNumber($pSheet->getPageMargins()->getHeader())); - $objWriter->writeAttribute('footer', StringHelper::formatNumber($pSheet->getPageMargins()->getFooter())); + $objWriter->writeAttribute('left', StringHelper::formatNumber($worksheet->getPageMargins()->getLeft())); + $objWriter->writeAttribute('right', StringHelper::formatNumber($worksheet->getPageMargins()->getRight())); + $objWriter->writeAttribute('top', StringHelper::formatNumber($worksheet->getPageMargins()->getTop())); + $objWriter->writeAttribute('bottom', StringHelper::formatNumber($worksheet->getPageMargins()->getBottom())); + $objWriter->writeAttribute('header', StringHelper::formatNumber($worksheet->getPageMargins()->getHeader())); + $objWriter->writeAttribute('footer', StringHelper::formatNumber($worksheet->getPageMargins()->getFooter())); $objWriter->endElement(); } /** * Write AutoFilter. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + $autoFilterRange = $worksheet->getAutoFilter()->getRange(); if (!empty($autoFilterRange)) { // autoFilter $objWriter->startElement('autoFilter'); @@ -763,13 +919,13 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('ref', str_replace('$', '', $range)); - $columns = $pSheet->getAutoFilter()->getColumns(); + $columns = $worksheet->getAutoFilter()->getColumns(); if (count($columns) > 0) { foreach ($columns as $columnID => $column) { $rules = $column->getRules(); if (count($rules) > 0) { $objWriter->startElement('filterColumn'); - $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + $objWriter->writeAttribute('colId', $worksheet->getAutoFilter()->getColumnOffset($columnID)); $objWriter->startElement($column->getFilterType()); if ($column->getJoin() == Column::AUTOFILTER_COLUMN_JOIN_AND) { @@ -777,9 +933,11 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ } foreach ($rules as $rule) { - if (($column->getFilterType() === Column::AUTOFILTER_FILTERTYPE_FILTER) && + if ( + ($column->getFilterType() === Column::AUTOFILTER_FILTERTYPE_FILTER) && ($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && - ($rule->getValue() === '')) { + ($rule->getValue() === '') + ) { // Filter rule for Blanks $objWriter->writeAttribute('blank', 1); } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { @@ -787,15 +945,18 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ $objWriter->writeAttribute('type', $rule->getGrouping()); $val = $column->getAttribute('val'); if ($val !== null) { - $objWriter->writeAttribute('val', $val); + $objWriter->writeAttribute('val', "$val"); } $maxVal = $column->getAttribute('maxVal'); if ($maxVal !== null) { - $objWriter->writeAttribute('maxVal', $maxVal); + $objWriter->writeAttribute('maxVal', "$maxVal"); } } elseif ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { // Top 10 Filter Rule - $objWriter->writeAttribute('val', $rule->getValue()); + $ruleValue = $rule->getValue(); + if (!is_array($ruleValue)) { + $objWriter->writeAttribute('val', "$ruleValue"); + } $objWriter->writeAttribute('percent', (($rule->getOperator() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); $objWriter->writeAttribute('top', (($rule->getGrouping() === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1' : '0')); } else { @@ -807,14 +968,18 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ } if ($rule->getRuleType() === Rule::AUTOFILTER_RULETYPE_DATEGROUP) { // Date Group filters - foreach ($rule->getValue() as $key => $value) { - if ($value > '') { - $objWriter->writeAttribute($key, $value); + $ruleValue = $rule->getValue(); + if (is_array($ruleValue)) { + foreach ($ruleValue as $key => $value) { + $objWriter->writeAttribute($key, "$value"); } } $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); } else { - $objWriter->writeAttribute('val', $rule->getValue()); + $ruleValue = $rule->getValue(); + if (!is_array($ruleValue)) { + $objWriter->writeAttribute('val', "$ruleValue"); + } } $objWriter->endElement(); @@ -831,40 +996,57 @@ private function writeAutoFilter(XMLWriter $objWriter, PhpspreadsheetWorksheet $ } } + /** + * Write Table. + */ + private function writeTable(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void + { + $tableCount = $worksheet->getTableCollection()->count(); + + $objWriter->startElement('tableParts'); + $objWriter->writeAttribute('count', (string) $tableCount); + + for ($t = 1; $t <= $tableCount; ++$t) { + $objWriter->startElement('tablePart'); + $objWriter->writeAttribute('r:id', 'rId_table_' . $t); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + /** * Write PageSetup. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // pageSetup $objWriter->startElement('pageSetup'); - $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); - $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); + $objWriter->writeAttribute('paperSize', $worksheet->getPageSetup()->getPaperSize()); + $objWriter->writeAttribute('orientation', $worksheet->getPageSetup()->getOrientation()); - if ($pSheet->getPageSetup()->getScale() !== null) { - $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); + if ($worksheet->getPageSetup()->getScale() !== null) { + $objWriter->writeAttribute('scale', $worksheet->getPageSetup()->getScale()); } - if ($pSheet->getPageSetup()->getFitToHeight() !== null) { - $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); + if ($worksheet->getPageSetup()->getFitToHeight() !== null) { + $objWriter->writeAttribute('fitToHeight', $worksheet->getPageSetup()->getFitToHeight()); } else { $objWriter->writeAttribute('fitToHeight', '0'); } - if ($pSheet->getPageSetup()->getFitToWidth() !== null) { - $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); + if ($worksheet->getPageSetup()->getFitToWidth() !== null) { + $objWriter->writeAttribute('fitToWidth', $worksheet->getPageSetup()->getFitToWidth()); } else { $objWriter->writeAttribute('fitToWidth', '0'); } - if ($pSheet->getPageSetup()->getFirstPageNumber() !== null) { - $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); + if ($worksheet->getPageSetup()->getFirstPageNumber() !== null) { + $objWriter->writeAttribute('firstPageNumber', $worksheet->getPageSetup()->getFirstPageNumber()); $objWriter->writeAttribute('useFirstPageNumber', '1'); } + $objWriter->writeAttribute('pageOrder', $worksheet->getPageSetup()->getPageOrder()); - $getUnparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - if (isset($getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId'])) { - $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$pSheet->getCodeName()]['pageSetupRelId']); + $getUnparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + if (isset($getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId'])) { + $objWriter->writeAttribute('r:id', $getUnparsedLoadedData['sheets'][$worksheet->getCodeName()]['pageSetupRelId']); } $objWriter->endElement(); @@ -872,40 +1054,34 @@ private function writePageSetup(XMLWriter $objWriter, PhpspreadsheetWorksheet $p /** * Write Header / Footer. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeHeaderFooter(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // headerFooter $objWriter->startElement('headerFooter'); - $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); - $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); - $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); - $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); - - $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); - $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); - $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); - $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); - $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); - $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); + $objWriter->writeAttribute('differentOddEven', ($worksheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); + $objWriter->writeAttribute('differentFirst', ($worksheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); + $objWriter->writeAttribute('scaleWithDoc', ($worksheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); + $objWriter->writeAttribute('alignWithMargins', ($worksheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); + + $objWriter->writeElement('oddHeader', $worksheet->getHeaderFooter()->getOddHeader()); + $objWriter->writeElement('oddFooter', $worksheet->getHeaderFooter()->getOddFooter()); + $objWriter->writeElement('evenHeader', $worksheet->getHeaderFooter()->getEvenHeader()); + $objWriter->writeElement('evenFooter', $worksheet->getHeaderFooter()->getEvenFooter()); + $objWriter->writeElement('firstHeader', $worksheet->getHeaderFooter()->getFirstHeader()); + $objWriter->writeElement('firstFooter', $worksheet->getHeaderFooter()->getFirstFooter()); $objWriter->endElement(); } /** * Write Breaks. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // Get row and column breaks $aRowBreaks = []; $aColumnBreaks = []; - foreach ($pSheet->getBreaks() as $cell => $breakType) { + foreach ($worksheet->getBreaks() as $cell => $breakType) { if ($breakType == PhpspreadsheetWorksheet::BREAK_ROW) { $aRowBreaks[] = $cell; } elseif ($breakType == PhpspreadsheetWorksheet::BREAK_COLUMN) { @@ -953,29 +1129,25 @@ private function writeBreaks(XMLWriter $objWriter, PhpspreadsheetWorksheet $pShe /** * Write SheetData. * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet - * @param string[] $pStringTable String table - * - * @throws WriterException + * @param string[] $stringTable String table */ - private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, array $pStringTable) + private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, array $stringTable): void { // Flipped stringtable, for faster index searching - $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable); + $aFlippedStringTable = $this->getParentWriter()->getWriterPartstringtable()->flipStringTable($stringTable); // sheetData $objWriter->startElement('sheetData'); // Get column count - $colCount = Coordinate::columnIndexFromString($pSheet->getHighestColumn()); + $colCount = Coordinate::columnIndexFromString($worksheet->getHighestColumn()); // Highest row number - $highestRow = $pSheet->getHighestRow(); + $highestRow = $worksheet->getHighestRow(); // Loop through cells $cellsByRow = []; - foreach ($pSheet->getCoordinates() as $coordinate) { + foreach ($worksheet->getCoordinates() as $coordinate) { $cellAddress = Coordinate::coordinateFromString($coordinate); $cellsByRow[$cellAddress[1]][] = $coordinate; } @@ -983,7 +1155,7 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p $currentRow = 0; while ($currentRow++ < $highestRow) { // Get row dimension - $rowDimension = $pSheet->getRowDimension($currentRow); + $rowDimension = $worksheet->getRowDimension($currentRow); // Write current row? $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; @@ -1025,7 +1197,7 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p if (isset($cellsByRow[$currentRow])) { foreach ($cellsByRow[$currentRow] as $cellAddress) { // Write cell - $this->writeCell($objWriter, $pSheet, $cellAddress, $aFlippedStringTable); + $this->writeCell($objWriter, $worksheet, $cellAddress, $aFlippedStringTable); } } @@ -1037,27 +1209,123 @@ private function writeSheetData(XMLWriter $objWriter, PhpspreadsheetWorksheet $p $objWriter->endElement(); } + /** + * @param RichText|string $cellValue + */ + private function writeCellInlineStr(XMLWriter $objWriter, string $mappedType, $cellValue): void + { + $objWriter->writeAttribute('t', $mappedType); + if (!$cellValue instanceof RichText) { + $objWriter->startElement('is'); + $objWriter->writeElement( + 't', + StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue, Settings::htmlEntityFlags())) + ); + $objWriter->endElement(); + } elseif ($cellValue instanceof RichText) { + $objWriter->startElement('is'); + $this->getParentWriter()->getWriterPartstringtable()->writeRichText($objWriter, $cellValue); + $objWriter->endElement(); + } + } + + /** + * @param RichText|string $cellValue + * @param string[] $flippedStringTable + */ + private function writeCellString(XMLWriter $objWriter, string $mappedType, $cellValue, array $flippedStringTable): void + { + $objWriter->writeAttribute('t', $mappedType); + if (!$cellValue instanceof RichText) { + self::writeElementIf($objWriter, isset($flippedStringTable[$cellValue]), 'v', $flippedStringTable[$cellValue] ?? ''); + } else { + $objWriter->writeElement('v', $flippedStringTable[$cellValue->getHashCode()]); + } + } + + /** + * @param float|int $cellValue + */ + private function writeCellNumeric(XMLWriter $objWriter, $cellValue): void + { + //force a decimal to be written if the type is float + if (is_float($cellValue)) { + // force point as decimal separator in case current locale uses comma + $cellValue = str_replace(',', '.', (string) $cellValue); + if (strpos($cellValue, '.') === false) { + $cellValue = $cellValue . '.0'; + } + } + $objWriter->writeElement('v', $cellValue); + } + + private function writeCellBoolean(XMLWriter $objWriter, string $mappedType, bool $cellValue): void + { + $objWriter->writeAttribute('t', $mappedType); + $objWriter->writeElement('v', $cellValue ? '1' : '0'); + } + + private function writeCellError(XMLWriter $objWriter, string $mappedType, string $cellValue, string $formulaerr = '#NULL!'): void + { + $objWriter->writeAttribute('t', $mappedType); + $cellIsFormula = substr($cellValue, 0, 1) === '='; + self::writeElementIf($objWriter, $cellIsFormula, 'f', Xlfn::addXlfnStripEquals($cellValue)); + $objWriter->writeElement('v', $cellIsFormula ? $formulaerr : $cellValue); + } + + private function writeCellFormula(XMLWriter $objWriter, string $cellValue, Cell $cell): void + { + $calculatedValue = $this->getParentWriter()->getPreCalculateFormulas() ? $cell->getCalculatedValue() : $cellValue; + if (is_string($calculatedValue)) { + if (ErrorValue::isError($calculatedValue)) { + $this->writeCellError($objWriter, 'e', $cellValue, $calculatedValue); + + return; + } + $objWriter->writeAttribute('t', 'str'); + $calculatedValue = StringHelper::controlCharacterPHP2OOXML($calculatedValue); + } elseif (is_bool($calculatedValue)) { + $objWriter->writeAttribute('t', 'b'); + $calculatedValue = (int) $calculatedValue; + } + + $attributes = $cell->getFormulaAttributes(); + if (($attributes['t'] ?? null) === 'array') { + $objWriter->startElement('f'); + $objWriter->writeAttribute('t', 'array'); + $objWriter->writeAttribute('ref', $cell->getCoordinate()); + $objWriter->writeAttribute('aca', '1'); + $objWriter->writeAttribute('ca', '1'); + $objWriter->text(substr($cellValue, 1)); + $objWriter->endElement(); + } else { + $objWriter->writeElement('f', Xlfn::addXlfnStripEquals($cellValue)); + self::writeElementIf( + $objWriter, + $this->getParentWriter()->getOffice2003Compatibility() === false, + 'v', + ($this->getParentWriter()->getPreCalculateFormulas() && !is_array($calculatedValue) && substr($calculatedValue ?? '', 0, 1) !== '#') + ? StringHelper::formatNumber($calculatedValue) : '0' + ); + } + } + /** * Write Cell. * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet - * @param Cell $pCellAddress Cell Address - * @param string[] $pFlippedStringTable String table (flipped), for faster index searching - * - * @throws WriterException + * @param string $cellAddress Cell Address + * @param string[] $flippedStringTable String table (flipped), for faster index searching */ - private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $pCellAddress, array $pFlippedStringTable) + private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, string $cellAddress, array $flippedStringTable): void { // Cell - $pCell = $pSheet->getCell($pCellAddress); + $pCell = $worksheet->getCell($cellAddress); $objWriter->startElement('c'); - $objWriter->writeAttribute('r', $pCellAddress); + $objWriter->writeAttribute('r', $cellAddress); // Sheet styles - if ($pCell->getXfIndex() != '') { - $objWriter->writeAttribute('s', $pCell->getXfIndex()); - } + $xfi = $pCell->getXfIndex(); + self::writeAttributeIf($objWriter, $xfi, 's', $xfi); // If cell value is supplied, write cell value $cellValue = $pCell->getValue(); @@ -1065,101 +1333,30 @@ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet // Map type $mappedType = $pCell->getDataType(); - // Write data type depending on its type - switch (strtolower($mappedType)) { - case 'inlinestr': // Inline string - case 's': // String - case 'b': // Boolean - $objWriter->writeAttribute('t', $mappedType); - - break; - case 'f': // Formula - $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ? - $pCell->getCalculatedValue() : $cellValue; - if (is_string($calculatedValue)) { - $objWriter->writeAttribute('t', 'str'); - } elseif (is_bool($calculatedValue)) { - $objWriter->writeAttribute('t', 'b'); - } - - break; - case 'e': // Error - $objWriter->writeAttribute('t', $mappedType); - } - // Write data depending on its type switch (strtolower($mappedType)) { case 'inlinestr': // Inline string - if (!$cellValue instanceof RichText) { - $objWriter->writeElement('t', StringHelper::controlCharacterPHP2OOXML(htmlspecialchars($cellValue))); - } elseif ($cellValue instanceof RichText) { - $objWriter->startElement('is'); - $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue); - $objWriter->endElement(); - } + $this->writeCellInlineStr($objWriter, $mappedType, $cellValue); break; case 's': // String - if (!$cellValue instanceof RichText) { - if (isset($pFlippedStringTable[$cellValue])) { - $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]); - } - } elseif ($cellValue instanceof RichText) { - $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]); - } + $this->writeCellString($objWriter, $mappedType, $cellValue, $flippedStringTable); break; case 'f': // Formula - $attributes = $pCell->getFormulaAttributes(); - if (($attributes['t'] ?? null) === 'array') { - $objWriter->startElement('f'); - $objWriter->writeAttribute('t', 'array'); - $objWriter->writeAttribute('ref', $pCellAddress); - $objWriter->writeAttribute('aca', '1'); - $objWriter->writeAttribute('ca', '1'); - $objWriter->text(substr($cellValue, 1)); - $objWriter->endElement(); - } else { - $objWriter->writeElement('f', substr($cellValue, 1)); - } - if ($this->getParentWriter()->getOffice2003Compatibility() === false) { - if ($this->getParentWriter()->getPreCalculateFormulas()) { - if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) !== '#') { - $objWriter->writeElement('v', StringHelper::formatNumber($calculatedValue)); - } else { - $objWriter->writeElement('v', '0'); - } - } else { - $objWriter->writeElement('v', '0'); - } - } + $this->writeCellFormula($objWriter, $cellValue, $pCell); break; case 'n': // Numeric - //force a decimal to be written if the type is float - if (is_float($cellValue)) { - // force point as decimal separator in case current locale uses comma - $cellValue = str_replace(',', '.', (string) $cellValue); - if (strpos($cellValue, '.') === false) { - $cellValue = $cellValue . '.0'; - } - } - $objWriter->writeElement('v', $cellValue); + $this->writeCellNumeric($objWriter, $cellValue); break; case 'b': // Boolean - $objWriter->writeElement('v', ($cellValue ? '1' : '0')); + $this->writeCellBoolean($objWriter, $mappedType, $cellValue); break; case 'e': // Error - if (substr($cellValue, 0, 1) === '=') { - $objWriter->writeElement('f', substr($cellValue, 1)); - $objWriter->writeElement('v', substr($cellValue, 1)); - } else { - $objWriter->writeElement('v', $cellValue); - } - - break; + $this->writeCellError($objWriter, $mappedType, $cellValue); } } @@ -1169,16 +1366,14 @@ private function writeCell(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet /** * Write Drawings. * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet * @param bool $includeCharts Flag indicating if we should include drawing details for charts */ - private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet, $includeCharts = false) + private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet, $includeCharts = false): void { - $unparsedLoadedData = $pSheet->getParent()->getUnparsedLoadedData(); - $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']); - $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; - if ($chartCount == 0 && $pSheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { + $unparsedLoadedData = $worksheet->getParent()->getUnparsedLoadedData(); + $hasUnparsedDrawing = isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']); + $chartCount = ($includeCharts) ? $worksheet->getChartCollection()->count() : 0; + if ($chartCount == 0 && $worksheet->getDrawingCollection()->count() == 0 && !$hasUnparsedDrawing) { return; } @@ -1186,9 +1381,10 @@ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pS $objWriter->startElement('drawing'); $rId = 'rId1'; - if (isset($unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds'])) { - $drawingOriginalIds = $unparsedLoadedData['sheets'][$pSheet->getCodeName()]['drawingOriginalIds']; + if (isset($unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds'])) { + $drawingOriginalIds = $unparsedLoadedData['sheets'][$worksheet->getCodeName()]['drawingOriginalIds']; // take first. In future can be overriten + // (! synchronize with \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels::writeWorksheetRelationships) $rId = reset($drawingOriginalIds); } @@ -1198,14 +1394,11 @@ private function writeDrawings(XMLWriter $objWriter, PhpspreadsheetWorksheet $pS /** * Write LegacyDrawing. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains comments, add the relationships - if (count($pSheet->getComments()) > 0) { + if (count($worksheet->getComments()) > 0) { $objWriter->startElement('legacyDrawing'); $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); $objWriter->endElement(); @@ -1214,28 +1407,60 @@ private function writeLegacyDrawing(XMLWriter $objWriter, PhpspreadsheetWorkshee /** * Write LegacyDrawingHF. - * - * @param XMLWriter $objWriter XML Writer - * @param PhpspreadsheetWorksheet $pSheet Worksheet */ - private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeLegacyDrawingHF(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { // If sheet contains images, add the relationships - if (count($pSheet->getHeaderFooter()->getImages()) > 0) { + if (count($worksheet->getHeaderFooter()->getImages()) > 0) { $objWriter->startElement('legacyDrawingHF'); $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); $objWriter->endElement(); } } - private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $pSheet) + private function writeAlternateContent(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void { - if (empty($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'])) { + if (empty($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'])) { return; } - foreach ($pSheet->getParent()->getUnparsedLoadedData()['sheets'][$pSheet->getCodeName()]['AlternateContents'] as $alternateContent) { + foreach ($worksheet->getParent()->getUnparsedLoadedData()['sheets'][$worksheet->getCodeName()]['AlternateContents'] as $alternateContent) { $objWriter->writeRaw($alternateContent); } } + + /** + * write + * only implementation conditionalFormattings. + * + * @url https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 + */ + private function writeExtLst(XMLWriter $objWriter, PhpspreadsheetWorksheet $worksheet): void + { + $conditionalFormattingRuleExtList = []; + foreach ($worksheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + /** @var Conditional $conditional */ + foreach ($conditionalStyles as $conditional) { + $dataBar = $conditional->getDataBar(); + // @phpstan-ignore-next-line + if ($dataBar && $dataBar->getConditionalFormattingRuleExt()) { + $conditionalFormattingRuleExtList[] = $dataBar->getConditionalFormattingRuleExt(); + } + } + } + + if (count($conditionalFormattingRuleExtList) > 0) { + $conditionalFormattingRuleExtNsPrefix = 'x14'; + $objWriter->startElement('extLst'); + $objWriter->startElement('ext'); + $objWriter->writeAttribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); + $objWriter->startElementNs($conditionalFormattingRuleExtNsPrefix, 'conditionalFormattings', null); + foreach ($conditionalFormattingRuleExtList as $extension) { + self::writeExtConditionalFormattingElements($objWriter, $extension); + } + $objWriter->endElement(); //end conditionalFormattings + $objWriter->endElement(); //end ext + $objWriter->endElement(); //end extLst + } + } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php index 7119512c..0bfb356d 100644 --- a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/WriterPart.php @@ -25,11 +25,9 @@ public function getParentWriter() /** * Set parent Xlsx object. - * - * @param Xlsx $pWriter */ - public function __construct(Xlsx $pWriter) + public function __construct(Xlsx $writer) { - $this->parentWriter = $pWriter; + $this->parentWriter = $writer; } } diff --git a/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php new file mode 100644 index 00000000..c88ef245 --- /dev/null +++ b/lib/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Writer/Xlsx/Xlfn.php @@ -0,0 +1,166 @@ +=7.0.0", + "psr/http-message": "^1.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/lib/psr/http-factory/src/RequestFactoryInterface.php b/lib/psr/http-factory/src/RequestFactoryInterface.php new file mode 100644 index 00000000..cb39a08b --- /dev/null +++ b/lib/psr/http-factory/src/RequestFactoryInterface.php @@ -0,0 +1,18 @@ +=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/lib/psr/http-message/src/MessageInterface.php b/lib/psr/http-message/src/MessageInterface.php new file mode 100644 index 00000000..dd46e5ec --- /dev/null +++ b/lib/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(); + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader($name); + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader($name); + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine($name); + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader($name, $value); + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader($name, $value); + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader($name); + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(); + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body); +} diff --git a/lib/psr/http-message/src/RequestInterface.php b/lib/psr/http-message/src/RequestInterface.php new file mode 100644 index 00000000..a96d4fd6 --- /dev/null +++ b/lib/psr/http-message/src/RequestInterface.php @@ -0,0 +1,129 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(); + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(); + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles); + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data); + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(); + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute($name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute($name, $value); + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name); +} diff --git a/lib/psr/http-message/src/StreamInterface.php b/lib/psr/http-message/src/StreamInterface.php new file mode 100644 index 00000000..f68f3912 --- /dev/null +++ b/lib/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(); + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(); + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(); + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(); + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(); + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(); + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(); + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme($scheme); + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo($user, $password = null); + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost($host); + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort($port); + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath($path); + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery($query); + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment($fragment); + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(); +} diff --git a/lib/ralouphie/getallheaders/LICENSE b/lib/ralouphie/getallheaders/LICENSE new file mode 100644 index 00000000..be5540c2 --- /dev/null +++ b/lib/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/ralouphie/getallheaders/README.md b/lib/ralouphie/getallheaders/README.md new file mode 100644 index 00000000..9430d76b --- /dev/null +++ b/lib/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/lib/ralouphie/getallheaders/composer.json b/lib/ralouphie/getallheaders/composer.json new file mode 100644 index 00000000..de8ce62e --- /dev/null +++ b/lib/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/lib/ralouphie/getallheaders/src/getallheaders.php b/lib/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 00000000..c7285a5b --- /dev/null +++ b/lib/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/lib/symfony/deprecation-contracts/.gitignore b/lib/symfony/deprecation-contracts/.gitignore new file mode 100644 index 00000000..c49a5d8d --- /dev/null +++ b/lib/symfony/deprecation-contracts/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/lib/symfony/deprecation-contracts/CHANGELOG.md b/lib/symfony/deprecation-contracts/CHANGELOG.md new file mode 100644 index 00000000..7932e261 --- /dev/null +++ b/lib/symfony/deprecation-contracts/CHANGELOG.md @@ -0,0 +1,5 @@ +CHANGELOG +========= + +The changelog is maintained for all Symfony contracts at the following URL: +https://github.com/symfony/contracts/blob/main/CHANGELOG.md diff --git a/lib/symfony/deprecation-contracts/LICENSE b/lib/symfony/deprecation-contracts/LICENSE new file mode 100644 index 00000000..ad85e173 --- /dev/null +++ b/lib/symfony/deprecation-contracts/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020-2021 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/lib/symfony/deprecation-contracts/README.md b/lib/symfony/deprecation-contracts/README.md new file mode 100644 index 00000000..4957933a --- /dev/null +++ b/lib/symfony/deprecation-contracts/README.md @@ -0,0 +1,26 @@ +Symfony Deprecation Contracts +============================= + +A generic function and convention to trigger deprecation notices. + +This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices. + +By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component, +the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments. + +The function requires at least 3 arguments: + - the name of the Composer package that is triggering the deprecation + - the version of the package that introduced the deprecation + - the message of the deprecation + - more arguments can be provided: they will be inserted in the message using `printf()` formatting + +Example: +```php +trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin'); +``` + +This will generate the following message: +`Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.` + +While not necessarily recommended, the deprecation notices can be completely ignored by declaring an empty +`function trigger_deprecation() {}` in your application. diff --git a/lib/symfony/deprecation-contracts/composer.json b/lib/symfony/deprecation-contracts/composer.json new file mode 100644 index 00000000..38848896 --- /dev/null +++ b/lib/symfony/deprecation-contracts/composer.json @@ -0,0 +1,35 @@ +{ + "name": "symfony/deprecation-contracts", + "type": "library", + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "2.4-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + } +} diff --git a/lib/symfony/deprecation-contracts/function.php b/lib/symfony/deprecation-contracts/function.php new file mode 100644 index 00000000..d4371504 --- /dev/null +++ b/lib/symfony/deprecation-contracts/function.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if (!function_exists('trigger_deprecation')) { + /** + * Triggers a silenced deprecation notice. + * + * @param string $package The name of the Composer package that is triggering the deprecation + * @param string $version The version of the package that introduced the deprecation + * @param string $message The message of the deprecation + * @param mixed ...$args Values to insert in the message using printf() formatting + * + * @author Nicolas Grekas + */ + function trigger_deprecation(string $package, string $version, string $message, ...$args): void + { + @trigger_error(($package || $version ? "Since $package $version: " : '').($args ? vsprintf($message, $args) : $message), \E_USER_DEPRECATED); + } +} diff --git a/lib/symfony/polyfill-mbstring/LICENSE b/lib/symfony/polyfill-mbstring/LICENSE new file mode 100644 index 00000000..4cd8bdd3 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-2019 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/lib/symfony/polyfill-mbstring/Mbstring.php b/lib/symfony/polyfill-mbstring/Mbstring.php new file mode 100644 index 00000000..693749f2 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/Mbstring.php @@ -0,0 +1,873 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Mbstring; + +/** + * Partial mbstring implementation in PHP, iconv based, UTF-8 centric. + * + * Implemented: + * - mb_chr - Returns a specific character from its Unicode code point + * - mb_convert_encoding - Convert character encoding + * - mb_convert_variables - Convert character code in variable(s) + * - mb_decode_mimeheader - Decode string in MIME header field + * - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED + * - mb_decode_numericentity - Decode HTML numeric string reference to character + * - mb_encode_numericentity - Encode character to HTML numeric string reference + * - mb_convert_case - Perform case folding on a string + * - mb_detect_encoding - Detect character encoding + * - mb_get_info - Get internal settings of mbstring + * - mb_http_input - Detect HTTP input character encoding + * - mb_http_output - Set/Get HTTP output character encoding + * - mb_internal_encoding - Set/Get internal character encoding + * - mb_list_encodings - Returns an array of all supported encodings + * - mb_ord - Returns the Unicode code point of a character + * - mb_output_handler - Callback function converts character encoding in output buffer + * - mb_scrub - Replaces ill-formed byte sequences with substitute characters + * - mb_strlen - Get string length + * - mb_strpos - Find position of first occurrence of string in a string + * - mb_strrpos - Find position of last occurrence of a string in a string + * - mb_str_split - Convert a string to an array + * - mb_strtolower - Make a string lowercase + * - mb_strtoupper - Make a string uppercase + * - mb_substitute_character - Set/Get substitution character + * - mb_substr - Get part of string + * - mb_stripos - Finds position of first occurrence of a string within another, case insensitive + * - mb_stristr - Finds first occurrence of a string within another, case insensitive + * - mb_strrchr - Finds the last occurrence of a character in a string within another + * - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive + * - mb_strripos - Finds position of last occurrence of a string within another, case insensitive + * - mb_strstr - Finds first occurrence of a string within another + * - mb_strwidth - Return width of string + * - mb_substr_count - Count the number of substring occurrences + * + * Not implemented: + * - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more) + * - mb_ereg_* - Regular expression with multibyte support + * - mb_parse_str - Parse GET/POST/COOKIE data and set global variable + * - mb_preferred_mime_name - Get MIME charset string + * - mb_regex_encoding - Returns current encoding for multibyte regex as string + * - mb_regex_set_options - Set/Get the default options for mbregex functions + * - mb_send_mail - Send encoded mail + * - mb_split - Split multibyte string using regular expression + * - mb_strcut - Get part of string + * - mb_strimwidth - Get truncated string with specified width + * + * @author Nicolas Grekas + * + * @internal + */ +final class Mbstring +{ + public const MB_CASE_FOLD = \PHP_INT_MAX; + + private const CASE_FOLD = [ + ['µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"], + ['μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'], + ]; + + private static $encodingList = ['ASCII', 'UTF-8']; + private static $language = 'neutral'; + private static $internalEncoding = 'UTF-8'; + + public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null) + { + if (\is_array($fromEncoding) || ($fromEncoding !== null && false !== strpos($fromEncoding, ','))) { + $fromEncoding = self::mb_detect_encoding($s, $fromEncoding); + } else { + $fromEncoding = self::getEncoding($fromEncoding); + } + + $toEncoding = self::getEncoding($toEncoding); + + if ('BASE64' === $fromEncoding) { + $s = base64_decode($s); + $fromEncoding = $toEncoding; + } + + if ('BASE64' === $toEncoding) { + return base64_encode($s); + } + + if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) { + if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) { + $fromEncoding = 'Windows-1252'; + } + if ('UTF-8' !== $fromEncoding) { + $s = \iconv($fromEncoding, 'UTF-8//IGNORE', $s); + } + + return preg_replace_callback('/[\x80-\xFF]+/', [__CLASS__, 'html_encoding_callback'], $s); + } + + if ('HTML-ENTITIES' === $fromEncoding) { + $s = html_entity_decode($s, \ENT_COMPAT, 'UTF-8'); + $fromEncoding = 'UTF-8'; + } + + return \iconv($fromEncoding, $toEncoding.'//IGNORE', $s); + } + + public static function mb_convert_variables($toEncoding, $fromEncoding, &...$vars) + { + $ok = true; + array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) { + if (false === $v = self::mb_convert_encoding($v, $toEncoding, $fromEncoding)) { + $ok = false; + } + }); + + return $ok ? $fromEncoding : false; + } + + public static function mb_decode_mimeheader($s) + { + return \iconv_mime_decode($s, 2, self::$internalEncoding); + } + + public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null) + { + trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', \E_USER_WARNING); + } + + public static function mb_decode_numericentity($s, $convmap, $encoding = null) + { + if (null !== $s && !is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !is_scalar($encoding)) { + trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return ''; // Instead of null (cf. mb_encode_numericentity). + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $cnt = floor(\count($convmap) / 4) * 4; + + for ($i = 0; $i < $cnt; $i += 4) { + // collector_decode_htmlnumericentity ignores $convmap[$i + 3] + $convmap[$i] += $convmap[$i + 2]; + $convmap[$i + 1] += $convmap[$i + 2]; + } + + $s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) { + $c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1]; + for ($i = 0; $i < $cnt; $i += 4) { + if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) { + return self::mb_chr($c - $convmap[$i + 2]); + } + } + + return $m[0]; + }, $s); + + if (null === $encoding) { + return $s; + } + + return \iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false) + { + if (null !== $s && !is_scalar($s) && !(\is_object($s) && method_exists($s, '__toString'))) { + trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + if (!\is_array($convmap) || (80000 > \PHP_VERSION_ID && !$convmap)) { + return false; + } + + if (null !== $encoding && !is_scalar($encoding)) { + trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', \E_USER_WARNING); + + return null; // Instead of '' (cf. mb_decode_numericentity). + } + + if (null !== $is_hex && !is_scalar($is_hex)) { + trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', \E_USER_WARNING); + + return null; + } + + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $cnt = floor(\count($convmap) / 4) * 4; + $i = 0; + $len = \strlen($s); + $result = ''; + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + $c = self::mb_ord($uchr); + + for ($j = 0; $j < $cnt; $j += 4) { + if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) { + $cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3]; + $result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';'; + continue 2; + } + } + $result .= $uchr; + } + + if (null === $encoding) { + return $result; + } + + return \iconv('UTF-8', $encoding.'//IGNORE', $result); + } + + public static function mb_convert_case($s, $mode, $encoding = null) + { + $s = (string) $s; + if ('' === $s) { + return ''; + } + + $encoding = self::getEncoding($encoding); + + if ('UTF-8' === $encoding) { + $encoding = null; + if (!preg_match('//u', $s)) { + $s = @\iconv('UTF-8', 'UTF-8//IGNORE', $s); + } + } else { + $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + } + + if (\MB_CASE_TITLE == $mode) { + static $titleRegexp = null; + if (null === $titleRegexp) { + $titleRegexp = self::getData('titleCaseRegexp'); + } + $s = preg_replace_callback($titleRegexp, [__CLASS__, 'title_case'], $s); + } else { + if (\MB_CASE_UPPER == $mode) { + static $upper = null; + if (null === $upper) { + $upper = self::getData('upperCase'); + } + $map = $upper; + } else { + if (self::MB_CASE_FOLD === $mode) { + $s = str_replace(self::CASE_FOLD[0], self::CASE_FOLD[1], $s); + } + + static $lower = null; + if (null === $lower) { + $lower = self::getData('lowerCase'); + } + $map = $lower; + } + + static $ulenMask = ["\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4]; + + $i = 0; + $len = \strlen($s); + + while ($i < $len) { + $ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"]; + $uchr = substr($s, $i, $ulen); + $i += $ulen; + + if (isset($map[$uchr])) { + $uchr = $map[$uchr]; + $nlen = \strlen($uchr); + + if ($nlen == $ulen) { + $nlen = $i; + do { + $s[--$nlen] = $uchr[--$ulen]; + } while ($ulen); + } else { + $s = substr_replace($s, $uchr, $i - $ulen, $ulen); + $len += $nlen - $ulen; + $i += $nlen - $ulen; + } + } + } + } + + if (null === $encoding) { + return $s; + } + + return \iconv('UTF-8', $encoding.'//IGNORE', $s); + } + + public static function mb_internal_encoding($encoding = null) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + $normalizedEncoding = self::getEncoding($encoding); + + if ('UTF-8' === $normalizedEncoding || false !== @\iconv($normalizedEncoding, $normalizedEncoding, ' ')) { + self::$internalEncoding = $normalizedEncoding; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($encoding) must be a valid encoding, "%s" given', $encoding)); + } + + public static function mb_language($lang = null) + { + if (null === $lang) { + return self::$language; + } + + switch ($normalizedLang = strtolower($lang)) { + case 'uni': + case 'neutral': + self::$language = $normalizedLang; + + return true; + } + + if (80000 > \PHP_VERSION_ID) { + return false; + } + + throw new \ValueError(sprintf('Argument #1 ($language) must be a valid language, "%s" given', $lang)); + } + + public static function mb_list_encodings() + { + return ['UTF-8']; + } + + public static function mb_encoding_aliases($encoding) + { + switch (strtoupper($encoding)) { + case 'UTF8': + case 'UTF-8': + return ['utf8']; + } + + return false; + } + + public static function mb_check_encoding($var = null, $encoding = null) + { + if (null === $encoding) { + if (null === $var) { + return false; + } + $encoding = self::$internalEncoding; + } + + return self::mb_detect_encoding($var, [$encoding]) || false !== @\iconv($encoding, $encoding, $var); + } + + public static function mb_detect_encoding($str, $encodingList = null, $strict = false) + { + if (null === $encodingList) { + $encodingList = self::$encodingList; + } else { + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + } + + foreach ($encodingList as $enc) { + switch ($enc) { + case 'ASCII': + if (!preg_match('/[\x80-\xFF]/', $str)) { + return $enc; + } + break; + + case 'UTF8': + case 'UTF-8': + if (preg_match('//u', $str)) { + return 'UTF-8'; + } + break; + + default: + if (0 === strncmp($enc, 'ISO-8859-', 9)) { + return $enc; + } + } + } + + return false; + } + + public static function mb_detect_order($encodingList = null) + { + if (null === $encodingList) { + return self::$encodingList; + } + + if (!\is_array($encodingList)) { + $encodingList = array_map('trim', explode(',', $encodingList)); + } + $encodingList = array_map('strtoupper', $encodingList); + + foreach ($encodingList as $enc) { + switch ($enc) { + default: + if (strncmp($enc, 'ISO-8859-', 9)) { + return false; + } + // no break + case 'ASCII': + case 'UTF8': + case 'UTF-8': + } + } + + self::$encodingList = $encodingList; + + return true; + } + + public static function mb_strlen($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return \strlen($s); + } + + return @\iconv_strlen($s, $encoding); + } + + public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strpos($haystack, $needle, $offset); + } + + $needle = (string) $needle; + if ('' === $needle) { + if (80000 > \PHP_VERSION_ID) { + trigger_error(__METHOD__.': Empty delimiter', \E_USER_WARNING); + + return false; + } + + return 0; + } + + return \iconv_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return strrpos($haystack, $needle, $offset); + } + + if ($offset != (int) $offset) { + $offset = 0; + } elseif ($offset = (int) $offset) { + if ($offset < 0) { + if (0 > $offset += self::mb_strlen($needle)) { + $haystack = self::mb_substr($haystack, 0, $offset, $encoding); + } + $offset = 0; + } else { + $haystack = self::mb_substr($haystack, $offset, 2147483647, $encoding); + } + } + + $pos = '' !== $needle || 80000 > \PHP_VERSION_ID + ? \iconv_strrpos($haystack, $needle, $encoding) + : self::mb_strlen($haystack, $encoding); + + return false !== $pos ? $offset + $pos : false; + } + + public static function mb_str_split($string, $split_length = 1, $encoding = null) + { + if (null !== $string && !is_scalar($string) && !(\is_object($string) && method_exists($string, '__toString'))) { + trigger_error('mb_str_split() expects parameter 1 to be string, '.\gettype($string).' given', \E_USER_WARNING); + + return null; + } + + if (1 > $split_length = (int) $split_length) { + if (80000 > \PHP_VERSION_ID) { + trigger_error('The length of each segment must be greater than zero', \E_USER_WARNING); + return false; + } + + throw new \ValueError('Argument #2 ($length) must be greater than 0'); + } + + if (null === $encoding) { + $encoding = mb_internal_encoding(); + } + + if ('UTF-8' === $encoding = self::getEncoding($encoding)) { + $rx = '/('; + while (65535 < $split_length) { + $rx .= '.{65535}'; + $split_length -= 65535; + } + $rx .= '.{'.$split_length.'})/us'; + + return preg_split($rx, $string, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + } + + $result = []; + $length = mb_strlen($string, $encoding); + + for ($i = 0; $i < $length; $i += $split_length) { + $result[] = mb_substr($string, $i, $split_length, $encoding); + } + + return $result; + } + + public static function mb_strtolower($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_LOWER, $encoding); + } + + public static function mb_strtoupper($s, $encoding = null) + { + return self::mb_convert_case($s, \MB_CASE_UPPER, $encoding); + } + + public static function mb_substitute_character($c = null) + { + if (null === $c) { + return 'none'; + } + if (0 === strcasecmp($c, 'none')) { + return true; + } + if (80000 > \PHP_VERSION_ID) { + return false; + } + if (\is_int($c) || 'long' === $c || 'entity' === $c) { + return false; + } + + throw new \ValueError('Argument #1 ($substitute_character) must be "none", "long", "entity" or a valid codepoint'); + } + + public static function mb_substr($s, $start, $length = null, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + return (string) substr($s, $start, null === $length ? 2147483647 : $length); + } + + if ($start < 0) { + $start = \iconv_strlen($s, $encoding) + $start; + if ($start < 0) { + $start = 0; + } + } + + if (null === $length) { + $length = 2147483647; + } elseif ($length < 0) { + $length = \iconv_strlen($s, $encoding) + $length - $start; + if ($length < 0) { + return ''; + } + } + + return (string) \iconv_substr($s, $start, $length, $encoding); + } + + public static function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) + { + $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); + $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); + + return self::mb_strpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_stristr($haystack, $needle, $part = false, $encoding = null) + { + $pos = self::mb_stripos($haystack, $needle, 0, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrchr($haystack, $needle, $part = false, $encoding = null) + { + $encoding = self::getEncoding($encoding); + if ('CP850' === $encoding || 'ASCII' === $encoding) { + $pos = strrpos($haystack, $needle); + } else { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = \iconv_strrpos($haystack, $needle, $encoding); + } + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strrichr($haystack, $needle, $part = false, $encoding = null) + { + $needle = self::mb_substr($needle, 0, 1, $encoding); + $pos = self::mb_strripos($haystack, $needle, $encoding); + + return self::getSubpart($pos, $part, $haystack, $encoding); + } + + public static function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) + { + $haystack = self::mb_convert_case($haystack, self::MB_CASE_FOLD, $encoding); + $needle = self::mb_convert_case($needle, self::MB_CASE_FOLD, $encoding); + + return self::mb_strrpos($haystack, $needle, $offset, $encoding); + } + + public static function mb_strstr($haystack, $needle, $part = false, $encoding = null) + { + $pos = strpos($haystack, $needle); + if (false === $pos) { + return false; + } + if ($part) { + return substr($haystack, 0, $pos); + } + + return substr($haystack, $pos); + } + + public static function mb_get_info($type = 'all') + { + $info = [ + 'internal_encoding' => self::$internalEncoding, + 'http_output' => 'pass', + 'http_output_conv_mimetypes' => '^(text/|application/xhtml\+xml)', + 'func_overload' => 0, + 'func_overload_list' => 'no overload', + 'mail_charset' => 'UTF-8', + 'mail_header_encoding' => 'BASE64', + 'mail_body_encoding' => 'BASE64', + 'illegal_chars' => 0, + 'encoding_translation' => 'Off', + 'language' => self::$language, + 'detect_order' => self::$encodingList, + 'substitute_character' => 'none', + 'strict_detection' => 'Off', + ]; + + if ('all' === $type) { + return $info; + } + if (isset($info[$type])) { + return $info[$type]; + } + + return false; + } + + public static function mb_http_input($type = '') + { + return false; + } + + public static function mb_http_output($encoding = null) + { + return null !== $encoding ? 'pass' === $encoding : 'pass'; + } + + public static function mb_strwidth($s, $encoding = null) + { + $encoding = self::getEncoding($encoding); + + if ('UTF-8' !== $encoding) { + $s = \iconv($encoding, 'UTF-8//IGNORE', $s); + } + + $s = preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $s, -1, $wide); + + return ($wide << 1) + \iconv_strlen($s, 'UTF-8'); + } + + public static function mb_substr_count($haystack, $needle, $encoding = null) + { + return substr_count($haystack, $needle); + } + + public static function mb_output_handler($contents, $status) + { + return $contents; + } + + public static function mb_chr($code, $encoding = null) + { + if (0x80 > $code %= 0x200000) { + $s = \chr($code); + } elseif (0x800 > $code) { + $s = \chr(0xC0 | $code >> 6).\chr(0x80 | $code & 0x3F); + } elseif (0x10000 > $code) { + $s = \chr(0xE0 | $code >> 12).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } else { + $s = \chr(0xF0 | $code >> 18).\chr(0x80 | $code >> 12 & 0x3F).\chr(0x80 | $code >> 6 & 0x3F).\chr(0x80 | $code & 0x3F); + } + + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, $encoding, 'UTF-8'); + } + + return $s; + } + + public static function mb_ord($s, $encoding = null) + { + if ('UTF-8' !== $encoding = self::getEncoding($encoding)) { + $s = mb_convert_encoding($s, 'UTF-8', $encoding); + } + + if (1 === \strlen($s)) { + return \ord($s); + } + + $code = ($s = unpack('C*', substr($s, 0, 4))) ? $s[1] : 0; + if (0xF0 <= $code) { + return (($code - 0xF0) << 18) + (($s[2] - 0x80) << 12) + (($s[3] - 0x80) << 6) + $s[4] - 0x80; + } + if (0xE0 <= $code) { + return (($code - 0xE0) << 12) + (($s[2] - 0x80) << 6) + $s[3] - 0x80; + } + if (0xC0 <= $code) { + return (($code - 0xC0) << 6) + $s[2] - 0x80; + } + + return $code; + } + + private static function getSubpart($pos, $part, $haystack, $encoding) + { + if (false === $pos) { + return false; + } + if ($part) { + return self::mb_substr($haystack, 0, $pos, $encoding); + } + + return self::mb_substr($haystack, $pos, null, $encoding); + } + + private static function html_encoding_callback(array $m) + { + $i = 1; + $entities = ''; + $m = unpack('C*', htmlentities($m[0], \ENT_COMPAT, 'UTF-8')); + + while (isset($m[$i])) { + if (0x80 > $m[$i]) { + $entities .= \chr($m[$i++]); + continue; + } + if (0xF0 <= $m[$i]) { + $c = (($m[$i++] - 0xF0) << 18) + (($m[$i++] - 0x80) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } elseif (0xE0 <= $m[$i]) { + $c = (($m[$i++] - 0xE0) << 12) + (($m[$i++] - 0x80) << 6) + $m[$i++] - 0x80; + } else { + $c = (($m[$i++] - 0xC0) << 6) + $m[$i++] - 0x80; + } + + $entities .= '&#'.$c.';'; + } + + return $entities; + } + + private static function title_case(array $s) + { + return self::mb_convert_case($s[1], \MB_CASE_UPPER, 'UTF-8').self::mb_convert_case($s[2], \MB_CASE_LOWER, 'UTF-8'); + } + + private static function getData($file) + { + if (file_exists($file = __DIR__.'/Resources/unidata/'.$file.'.php')) { + return require $file; + } + + return false; + } + + private static function getEncoding($encoding) + { + if (null === $encoding) { + return self::$internalEncoding; + } + + if ('UTF-8' === $encoding) { + return 'UTF-8'; + } + + $encoding = strtoupper($encoding); + + if ('8BIT' === $encoding || 'BINARY' === $encoding) { + return 'CP850'; + } + + if ('UTF8' === $encoding) { + return 'UTF-8'; + } + + return $encoding; + } +} diff --git a/lib/symfony/polyfill-mbstring/README.md b/lib/symfony/polyfill-mbstring/README.md new file mode 100644 index 00000000..478b40da --- /dev/null +++ b/lib/symfony/polyfill-mbstring/README.md @@ -0,0 +1,13 @@ +Symfony Polyfill / Mbstring +=========================== + +This component provides a partial, native PHP implementation for the +[Mbstring](https://php.net/mbstring) extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/lib/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php b/lib/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php new file mode 100644 index 00000000..fac60b08 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php @@ -0,0 +1,1397 @@ + 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + 'À' => 'à', + 'Á' => 'á', + 'Â' => 'â', + 'Ã' => 'ã', + 'Ä' => 'ä', + 'Å' => 'å', + 'Æ' => 'æ', + 'Ç' => 'ç', + 'È' => 'è', + 'É' => 'é', + 'Ê' => 'ê', + 'Ë' => 'ë', + 'Ì' => 'ì', + 'Í' => 'í', + 'Î' => 'î', + 'Ï' => 'ï', + 'Ð' => 'ð', + 'Ñ' => 'ñ', + 'Ò' => 'ò', + 'Ó' => 'ó', + 'Ô' => 'ô', + 'Õ' => 'õ', + 'Ö' => 'ö', + 'Ø' => 'ø', + 'Ù' => 'ù', + 'Ú' => 'ú', + 'Û' => 'û', + 'Ü' => 'ü', + 'Ý' => 'ý', + 'Þ' => 'þ', + 'Ā' => 'ā', + 'Ă' => 'ă', + 'Ą' => 'ą', + 'Ć' => 'ć', + 'Ĉ' => 'ĉ', + 'Ċ' => 'ċ', + 'Č' => 'č', + 'Ď' => 'ď', + 'Đ' => 'đ', + 'Ē' => 'ē', + 'Ĕ' => 'ĕ', + 'Ė' => 'ė', + 'Ę' => 'ę', + 'Ě' => 'ě', + 'Ĝ' => 'ĝ', + 'Ğ' => 'ğ', + 'Ġ' => 'ġ', + 'Ģ' => 'ģ', + 'Ĥ' => 'ĥ', + 'Ħ' => 'ħ', + 'Ĩ' => 'ĩ', + 'Ī' => 'ī', + 'Ĭ' => 'ĭ', + 'Į' => 'į', + 'İ' => 'i̇', + 'IJ' => 'ij', + 'Ĵ' => 'ĵ', + 'Ķ' => 'ķ', + 'Ĺ' => 'ĺ', + 'Ļ' => 'ļ', + 'Ľ' => 'ľ', + 'Ŀ' => 'ŀ', + 'Ł' => 'ł', + 'Ń' => 'ń', + 'Ņ' => 'ņ', + 'Ň' => 'ň', + 'Ŋ' => 'ŋ', + 'Ō' => 'ō', + 'Ŏ' => 'ŏ', + 'Ő' => 'ő', + 'Œ' => 'œ', + 'Ŕ' => 'ŕ', + 'Ŗ' => 'ŗ', + 'Ř' => 'ř', + 'Ś' => 'ś', + 'Ŝ' => 'ŝ', + 'Ş' => 'ş', + 'Š' => 'š', + 'Ţ' => 'ţ', + 'Ť' => 'ť', + 'Ŧ' => 'ŧ', + 'Ũ' => 'ũ', + 'Ū' => 'ū', + 'Ŭ' => 'ŭ', + 'Ů' => 'ů', + 'Ű' => 'ű', + 'Ų' => 'ų', + 'Ŵ' => 'ŵ', + 'Ŷ' => 'ŷ', + 'Ÿ' => 'ÿ', + 'Ź' => 'ź', + 'Ż' => 'ż', + 'Ž' => 'ž', + 'Ɓ' => 'ɓ', + 'Ƃ' => 'ƃ', + 'Ƅ' => 'ƅ', + 'Ɔ' => 'ɔ', + 'Ƈ' => 'ƈ', + 'Ɖ' => 'ɖ', + 'Ɗ' => 'ɗ', + 'Ƌ' => 'ƌ', + 'Ǝ' => 'ǝ', + 'Ə' => 'ə', + 'Ɛ' => 'ɛ', + 'Ƒ' => 'ƒ', + 'Ɠ' => 'ɠ', + 'Ɣ' => 'ɣ', + 'Ɩ' => 'ɩ', + 'Ɨ' => 'ɨ', + 'Ƙ' => 'ƙ', + 'Ɯ' => 'ɯ', + 'Ɲ' => 'ɲ', + 'Ɵ' => 'ɵ', + 'Ơ' => 'ơ', + 'Ƣ' => 'ƣ', + 'Ƥ' => 'ƥ', + 'Ʀ' => 'ʀ', + 'Ƨ' => 'ƨ', + 'Ʃ' => 'ʃ', + 'Ƭ' => 'ƭ', + 'Ʈ' => 'ʈ', + 'Ư' => 'ư', + 'Ʊ' => 'ʊ', + 'Ʋ' => 'ʋ', + 'Ƴ' => 'ƴ', + 'Ƶ' => 'ƶ', + 'Ʒ' => 'ʒ', + 'Ƹ' => 'ƹ', + 'Ƽ' => 'ƽ', + 'DŽ' => 'dž', + 'Dž' => 'dž', + 'LJ' => 'lj', + 'Lj' => 'lj', + 'NJ' => 'nj', + 'Nj' => 'nj', + 'Ǎ' => 'ǎ', + 'Ǐ' => 'ǐ', + 'Ǒ' => 'ǒ', + 'Ǔ' => 'ǔ', + 'Ǖ' => 'ǖ', + 'Ǘ' => 'ǘ', + 'Ǚ' => 'ǚ', + 'Ǜ' => 'ǜ', + 'Ǟ' => 'ǟ', + 'Ǡ' => 'ǡ', + 'Ǣ' => 'ǣ', + 'Ǥ' => 'ǥ', + 'Ǧ' => 'ǧ', + 'Ǩ' => 'ǩ', + 'Ǫ' => 'ǫ', + 'Ǭ' => 'ǭ', + 'Ǯ' => 'ǯ', + 'DZ' => 'dz', + 'Dz' => 'dz', + 'Ǵ' => 'ǵ', + 'Ƕ' => 'ƕ', + 'Ƿ' => 'ƿ', + 'Ǹ' => 'ǹ', + 'Ǻ' => 'ǻ', + 'Ǽ' => 'ǽ', + 'Ǿ' => 'ǿ', + 'Ȁ' => 'ȁ', + 'Ȃ' => 'ȃ', + 'Ȅ' => 'ȅ', + 'Ȇ' => 'ȇ', + 'Ȉ' => 'ȉ', + 'Ȋ' => 'ȋ', + 'Ȍ' => 'ȍ', + 'Ȏ' => 'ȏ', + 'Ȑ' => 'ȑ', + 'Ȓ' => 'ȓ', + 'Ȕ' => 'ȕ', + 'Ȗ' => 'ȗ', + 'Ș' => 'ș', + 'Ț' => 'ț', + 'Ȝ' => 'ȝ', + 'Ȟ' => 'ȟ', + 'Ƞ' => 'ƞ', + 'Ȣ' => 'ȣ', + 'Ȥ' => 'ȥ', + 'Ȧ' => 'ȧ', + 'Ȩ' => 'ȩ', + 'Ȫ' => 'ȫ', + 'Ȭ' => 'ȭ', + 'Ȯ' => 'ȯ', + 'Ȱ' => 'ȱ', + 'Ȳ' => 'ȳ', + 'Ⱥ' => 'ⱥ', + 'Ȼ' => 'ȼ', + 'Ƚ' => 'ƚ', + 'Ⱦ' => 'ⱦ', + 'Ɂ' => 'ɂ', + 'Ƀ' => 'ƀ', + 'Ʉ' => 'ʉ', + 'Ʌ' => 'ʌ', + 'Ɇ' => 'ɇ', + 'Ɉ' => 'ɉ', + 'Ɋ' => 'ɋ', + 'Ɍ' => 'ɍ', + 'Ɏ' => 'ɏ', + 'Ͱ' => 'ͱ', + 'Ͳ' => 'ͳ', + 'Ͷ' => 'ͷ', + 'Ϳ' => 'ϳ', + 'Ά' => 'ά', + 'Έ' => 'έ', + 'Ή' => 'ή', + 'Ί' => 'ί', + 'Ό' => 'ό', + 'Ύ' => 'ύ', + 'Ώ' => 'ώ', + 'Α' => 'α', + 'Β' => 'β', + 'Γ' => 'γ', + 'Δ' => 'δ', + 'Ε' => 'ε', + 'Ζ' => 'ζ', + 'Η' => 'η', + 'Θ' => 'θ', + 'Ι' => 'ι', + 'Κ' => 'κ', + 'Λ' => 'λ', + 'Μ' => 'μ', + 'Ν' => 'ν', + 'Ξ' => 'ξ', + 'Ο' => 'ο', + 'Π' => 'π', + 'Ρ' => 'ρ', + 'Σ' => 'σ', + 'Τ' => 'τ', + 'Υ' => 'υ', + 'Φ' => 'φ', + 'Χ' => 'χ', + 'Ψ' => 'ψ', + 'Ω' => 'ω', + 'Ϊ' => 'ϊ', + 'Ϋ' => 'ϋ', + 'Ϗ' => 'ϗ', + 'Ϙ' => 'ϙ', + 'Ϛ' => 'ϛ', + 'Ϝ' => 'ϝ', + 'Ϟ' => 'ϟ', + 'Ϡ' => 'ϡ', + 'Ϣ' => 'ϣ', + 'Ϥ' => 'ϥ', + 'Ϧ' => 'ϧ', + 'Ϩ' => 'ϩ', + 'Ϫ' => 'ϫ', + 'Ϭ' => 'ϭ', + 'Ϯ' => 'ϯ', + 'ϴ' => 'θ', + 'Ϸ' => 'ϸ', + 'Ϲ' => 'ϲ', + 'Ϻ' => 'ϻ', + 'Ͻ' => 'ͻ', + 'Ͼ' => 'ͼ', + 'Ͽ' => 'ͽ', + 'Ѐ' => 'ѐ', + 'Ё' => 'ё', + 'Ђ' => 'ђ', + 'Ѓ' => 'ѓ', + 'Є' => 'є', + 'Ѕ' => 'ѕ', + 'І' => 'і', + 'Ї' => 'ї', + 'Ј' => 'ј', + 'Љ' => 'љ', + 'Њ' => 'њ', + 'Ћ' => 'ћ', + 'Ќ' => 'ќ', + 'Ѝ' => 'ѝ', + 'Ў' => 'ў', + 'Џ' => 'џ', + 'А' => 'а', + 'Б' => 'б', + 'В' => 'в', + 'Г' => 'г', + 'Д' => 'д', + 'Е' => 'е', + 'Ж' => 'ж', + 'З' => 'з', + 'И' => 'и', + 'Й' => 'й', + 'К' => 'к', + 'Л' => 'л', + 'М' => 'м', + 'Н' => 'н', + 'О' => 'о', + 'П' => 'п', + 'Р' => 'р', + 'С' => 'с', + 'Т' => 'т', + 'У' => 'у', + 'Ф' => 'ф', + 'Х' => 'х', + 'Ц' => 'ц', + 'Ч' => 'ч', + 'Ш' => 'ш', + 'Щ' => 'щ', + 'Ъ' => 'ъ', + 'Ы' => 'ы', + 'Ь' => 'ь', + 'Э' => 'э', + 'Ю' => 'ю', + 'Я' => 'я', + 'Ѡ' => 'ѡ', + 'Ѣ' => 'ѣ', + 'Ѥ' => 'ѥ', + 'Ѧ' => 'ѧ', + 'Ѩ' => 'ѩ', + 'Ѫ' => 'ѫ', + 'Ѭ' => 'ѭ', + 'Ѯ' => 'ѯ', + 'Ѱ' => 'ѱ', + 'Ѳ' => 'ѳ', + 'Ѵ' => 'ѵ', + 'Ѷ' => 'ѷ', + 'Ѹ' => 'ѹ', + 'Ѻ' => 'ѻ', + 'Ѽ' => 'ѽ', + 'Ѿ' => 'ѿ', + 'Ҁ' => 'ҁ', + 'Ҋ' => 'ҋ', + 'Ҍ' => 'ҍ', + 'Ҏ' => 'ҏ', + 'Ґ' => 'ґ', + 'Ғ' => 'ғ', + 'Ҕ' => 'ҕ', + 'Җ' => 'җ', + 'Ҙ' => 'ҙ', + 'Қ' => 'қ', + 'Ҝ' => 'ҝ', + 'Ҟ' => 'ҟ', + 'Ҡ' => 'ҡ', + 'Ң' => 'ң', + 'Ҥ' => 'ҥ', + 'Ҧ' => 'ҧ', + 'Ҩ' => 'ҩ', + 'Ҫ' => 'ҫ', + 'Ҭ' => 'ҭ', + 'Ү' => 'ү', + 'Ұ' => 'ұ', + 'Ҳ' => 'ҳ', + 'Ҵ' => 'ҵ', + 'Ҷ' => 'ҷ', + 'Ҹ' => 'ҹ', + 'Һ' => 'һ', + 'Ҽ' => 'ҽ', + 'Ҿ' => 'ҿ', + 'Ӏ' => 'ӏ', + 'Ӂ' => 'ӂ', + 'Ӄ' => 'ӄ', + 'Ӆ' => 'ӆ', + 'Ӈ' => 'ӈ', + 'Ӊ' => 'ӊ', + 'Ӌ' => 'ӌ', + 'Ӎ' => 'ӎ', + 'Ӑ' => 'ӑ', + 'Ӓ' => 'ӓ', + 'Ӕ' => 'ӕ', + 'Ӗ' => 'ӗ', + 'Ә' => 'ә', + 'Ӛ' => 'ӛ', + 'Ӝ' => 'ӝ', + 'Ӟ' => 'ӟ', + 'Ӡ' => 'ӡ', + 'Ӣ' => 'ӣ', + 'Ӥ' => 'ӥ', + 'Ӧ' => 'ӧ', + 'Ө' => 'ө', + 'Ӫ' => 'ӫ', + 'Ӭ' => 'ӭ', + 'Ӯ' => 'ӯ', + 'Ӱ' => 'ӱ', + 'Ӳ' => 'ӳ', + 'Ӵ' => 'ӵ', + 'Ӷ' => 'ӷ', + 'Ӹ' => 'ӹ', + 'Ӻ' => 'ӻ', + 'Ӽ' => 'ӽ', + 'Ӿ' => 'ӿ', + 'Ԁ' => 'ԁ', + 'Ԃ' => 'ԃ', + 'Ԅ' => 'ԅ', + 'Ԇ' => 'ԇ', + 'Ԉ' => 'ԉ', + 'Ԋ' => 'ԋ', + 'Ԍ' => 'ԍ', + 'Ԏ' => 'ԏ', + 'Ԑ' => 'ԑ', + 'Ԓ' => 'ԓ', + 'Ԕ' => 'ԕ', + 'Ԗ' => 'ԗ', + 'Ԙ' => 'ԙ', + 'Ԛ' => 'ԛ', + 'Ԝ' => 'ԝ', + 'Ԟ' => 'ԟ', + 'Ԡ' => 'ԡ', + 'Ԣ' => 'ԣ', + 'Ԥ' => 'ԥ', + 'Ԧ' => 'ԧ', + 'Ԩ' => 'ԩ', + 'Ԫ' => 'ԫ', + 'Ԭ' => 'ԭ', + 'Ԯ' => 'ԯ', + 'Ա' => 'ա', + 'Բ' => 'բ', + 'Գ' => 'գ', + 'Դ' => 'դ', + 'Ե' => 'ե', + 'Զ' => 'զ', + 'Է' => 'է', + 'Ը' => 'ը', + 'Թ' => 'թ', + 'Ժ' => 'ժ', + 'Ի' => 'ի', + 'Լ' => 'լ', + 'Խ' => 'խ', + 'Ծ' => 'ծ', + 'Կ' => 'կ', + 'Հ' => 'հ', + 'Ձ' => 'ձ', + 'Ղ' => 'ղ', + 'Ճ' => 'ճ', + 'Մ' => 'մ', + 'Յ' => 'յ', + 'Ն' => 'ն', + 'Շ' => 'շ', + 'Ո' => 'ո', + 'Չ' => 'չ', + 'Պ' => 'պ', + 'Ջ' => 'ջ', + 'Ռ' => 'ռ', + 'Ս' => 'ս', + 'Վ' => 'վ', + 'Տ' => 'տ', + 'Ր' => 'ր', + 'Ց' => 'ց', + 'Ւ' => 'ւ', + 'Փ' => 'փ', + 'Ք' => 'ք', + 'Օ' => 'օ', + 'Ֆ' => 'ֆ', + 'Ⴀ' => 'ⴀ', + 'Ⴁ' => 'ⴁ', + 'Ⴂ' => 'ⴂ', + 'Ⴃ' => 'ⴃ', + 'Ⴄ' => 'ⴄ', + 'Ⴅ' => 'ⴅ', + 'Ⴆ' => 'ⴆ', + 'Ⴇ' => 'ⴇ', + 'Ⴈ' => 'ⴈ', + 'Ⴉ' => 'ⴉ', + 'Ⴊ' => 'ⴊ', + 'Ⴋ' => 'ⴋ', + 'Ⴌ' => 'ⴌ', + 'Ⴍ' => 'ⴍ', + 'Ⴎ' => 'ⴎ', + 'Ⴏ' => 'ⴏ', + 'Ⴐ' => 'ⴐ', + 'Ⴑ' => 'ⴑ', + 'Ⴒ' => 'ⴒ', + 'Ⴓ' => 'ⴓ', + 'Ⴔ' => 'ⴔ', + 'Ⴕ' => 'ⴕ', + 'Ⴖ' => 'ⴖ', + 'Ⴗ' => 'ⴗ', + 'Ⴘ' => 'ⴘ', + 'Ⴙ' => 'ⴙ', + 'Ⴚ' => 'ⴚ', + 'Ⴛ' => 'ⴛ', + 'Ⴜ' => 'ⴜ', + 'Ⴝ' => 'ⴝ', + 'Ⴞ' => 'ⴞ', + 'Ⴟ' => 'ⴟ', + 'Ⴠ' => 'ⴠ', + 'Ⴡ' => 'ⴡ', + 'Ⴢ' => 'ⴢ', + 'Ⴣ' => 'ⴣ', + 'Ⴤ' => 'ⴤ', + 'Ⴥ' => 'ⴥ', + 'Ⴧ' => 'ⴧ', + 'Ⴭ' => 'ⴭ', + 'Ꭰ' => 'ꭰ', + 'Ꭱ' => 'ꭱ', + 'Ꭲ' => 'ꭲ', + 'Ꭳ' => 'ꭳ', + 'Ꭴ' => 'ꭴ', + 'Ꭵ' => 'ꭵ', + 'Ꭶ' => 'ꭶ', + 'Ꭷ' => 'ꭷ', + 'Ꭸ' => 'ꭸ', + 'Ꭹ' => 'ꭹ', + 'Ꭺ' => 'ꭺ', + 'Ꭻ' => 'ꭻ', + 'Ꭼ' => 'ꭼ', + 'Ꭽ' => 'ꭽ', + 'Ꭾ' => 'ꭾ', + 'Ꭿ' => 'ꭿ', + 'Ꮀ' => 'ꮀ', + 'Ꮁ' => 'ꮁ', + 'Ꮂ' => 'ꮂ', + 'Ꮃ' => 'ꮃ', + 'Ꮄ' => 'ꮄ', + 'Ꮅ' => 'ꮅ', + 'Ꮆ' => 'ꮆ', + 'Ꮇ' => 'ꮇ', + 'Ꮈ' => 'ꮈ', + 'Ꮉ' => 'ꮉ', + 'Ꮊ' => 'ꮊ', + 'Ꮋ' => 'ꮋ', + 'Ꮌ' => 'ꮌ', + 'Ꮍ' => 'ꮍ', + 'Ꮎ' => 'ꮎ', + 'Ꮏ' => 'ꮏ', + 'Ꮐ' => 'ꮐ', + 'Ꮑ' => 'ꮑ', + 'Ꮒ' => 'ꮒ', + 'Ꮓ' => 'ꮓ', + 'Ꮔ' => 'ꮔ', + 'Ꮕ' => 'ꮕ', + 'Ꮖ' => 'ꮖ', + 'Ꮗ' => 'ꮗ', + 'Ꮘ' => 'ꮘ', + 'Ꮙ' => 'ꮙ', + 'Ꮚ' => 'ꮚ', + 'Ꮛ' => 'ꮛ', + 'Ꮜ' => 'ꮜ', + 'Ꮝ' => 'ꮝ', + 'Ꮞ' => 'ꮞ', + 'Ꮟ' => 'ꮟ', + 'Ꮠ' => 'ꮠ', + 'Ꮡ' => 'ꮡ', + 'Ꮢ' => 'ꮢ', + 'Ꮣ' => 'ꮣ', + 'Ꮤ' => 'ꮤ', + 'Ꮥ' => 'ꮥ', + 'Ꮦ' => 'ꮦ', + 'Ꮧ' => 'ꮧ', + 'Ꮨ' => 'ꮨ', + 'Ꮩ' => 'ꮩ', + 'Ꮪ' => 'ꮪ', + 'Ꮫ' => 'ꮫ', + 'Ꮬ' => 'ꮬ', + 'Ꮭ' => 'ꮭ', + 'Ꮮ' => 'ꮮ', + 'Ꮯ' => 'ꮯ', + 'Ꮰ' => 'ꮰ', + 'Ꮱ' => 'ꮱ', + 'Ꮲ' => 'ꮲ', + 'Ꮳ' => 'ꮳ', + 'Ꮴ' => 'ꮴ', + 'Ꮵ' => 'ꮵ', + 'Ꮶ' => 'ꮶ', + 'Ꮷ' => 'ꮷ', + 'Ꮸ' => 'ꮸ', + 'Ꮹ' => 'ꮹ', + 'Ꮺ' => 'ꮺ', + 'Ꮻ' => 'ꮻ', + 'Ꮼ' => 'ꮼ', + 'Ꮽ' => 'ꮽ', + 'Ꮾ' => 'ꮾ', + 'Ꮿ' => 'ꮿ', + 'Ᏸ' => 'ᏸ', + 'Ᏹ' => 'ᏹ', + 'Ᏺ' => 'ᏺ', + 'Ᏻ' => 'ᏻ', + 'Ᏼ' => 'ᏼ', + 'Ᏽ' => 'ᏽ', + 'Ა' => 'ა', + 'Ბ' => 'ბ', + 'Გ' => 'გ', + 'Დ' => 'დ', + 'Ე' => 'ე', + 'Ვ' => 'ვ', + 'Ზ' => 'ზ', + 'Თ' => 'თ', + 'Ი' => 'ი', + 'Კ' => 'კ', + 'Ლ' => 'ლ', + 'Მ' => 'მ', + 'Ნ' => 'ნ', + 'Ო' => 'ო', + 'Პ' => 'პ', + 'Ჟ' => 'ჟ', + 'Რ' => 'რ', + 'Ს' => 'ს', + 'Ტ' => 'ტ', + 'Უ' => 'უ', + 'Ფ' => 'ფ', + 'Ქ' => 'ქ', + 'Ღ' => 'ღ', + 'Ყ' => 'ყ', + 'Შ' => 'შ', + 'Ჩ' => 'ჩ', + 'Ც' => 'ც', + 'Ძ' => 'ძ', + 'Წ' => 'წ', + 'Ჭ' => 'ჭ', + 'Ხ' => 'ხ', + 'Ჯ' => 'ჯ', + 'Ჰ' => 'ჰ', + 'Ჱ' => 'ჱ', + 'Ჲ' => 'ჲ', + 'Ჳ' => 'ჳ', + 'Ჴ' => 'ჴ', + 'Ჵ' => 'ჵ', + 'Ჶ' => 'ჶ', + 'Ჷ' => 'ჷ', + 'Ჸ' => 'ჸ', + 'Ჹ' => 'ჹ', + 'Ჺ' => 'ჺ', + 'Ჽ' => 'ჽ', + 'Ჾ' => 'ჾ', + 'Ჿ' => 'ჿ', + 'Ḁ' => 'ḁ', + 'Ḃ' => 'ḃ', + 'Ḅ' => 'ḅ', + 'Ḇ' => 'ḇ', + 'Ḉ' => 'ḉ', + 'Ḋ' => 'ḋ', + 'Ḍ' => 'ḍ', + 'Ḏ' => 'ḏ', + 'Ḑ' => 'ḑ', + 'Ḓ' => 'ḓ', + 'Ḕ' => 'ḕ', + 'Ḗ' => 'ḗ', + 'Ḙ' => 'ḙ', + 'Ḛ' => 'ḛ', + 'Ḝ' => 'ḝ', + 'Ḟ' => 'ḟ', + 'Ḡ' => 'ḡ', + 'Ḣ' => 'ḣ', + 'Ḥ' => 'ḥ', + 'Ḧ' => 'ḧ', + 'Ḩ' => 'ḩ', + 'Ḫ' => 'ḫ', + 'Ḭ' => 'ḭ', + 'Ḯ' => 'ḯ', + 'Ḱ' => 'ḱ', + 'Ḳ' => 'ḳ', + 'Ḵ' => 'ḵ', + 'Ḷ' => 'ḷ', + 'Ḹ' => 'ḹ', + 'Ḻ' => 'ḻ', + 'Ḽ' => 'ḽ', + 'Ḿ' => 'ḿ', + 'Ṁ' => 'ṁ', + 'Ṃ' => 'ṃ', + 'Ṅ' => 'ṅ', + 'Ṇ' => 'ṇ', + 'Ṉ' => 'ṉ', + 'Ṋ' => 'ṋ', + 'Ṍ' => 'ṍ', + 'Ṏ' => 'ṏ', + 'Ṑ' => 'ṑ', + 'Ṓ' => 'ṓ', + 'Ṕ' => 'ṕ', + 'Ṗ' => 'ṗ', + 'Ṙ' => 'ṙ', + 'Ṛ' => 'ṛ', + 'Ṝ' => 'ṝ', + 'Ṟ' => 'ṟ', + 'Ṡ' => 'ṡ', + 'Ṣ' => 'ṣ', + 'Ṥ' => 'ṥ', + 'Ṧ' => 'ṧ', + 'Ṩ' => 'ṩ', + 'Ṫ' => 'ṫ', + 'Ṭ' => 'ṭ', + 'Ṯ' => 'ṯ', + 'Ṱ' => 'ṱ', + 'Ṳ' => 'ṳ', + 'Ṵ' => 'ṵ', + 'Ṷ' => 'ṷ', + 'Ṹ' => 'ṹ', + 'Ṻ' => 'ṻ', + 'Ṽ' => 'ṽ', + 'Ṿ' => 'ṿ', + 'Ẁ' => 'ẁ', + 'Ẃ' => 'ẃ', + 'Ẅ' => 'ẅ', + 'Ẇ' => 'ẇ', + 'Ẉ' => 'ẉ', + 'Ẋ' => 'ẋ', + 'Ẍ' => 'ẍ', + 'Ẏ' => 'ẏ', + 'Ẑ' => 'ẑ', + 'Ẓ' => 'ẓ', + 'Ẕ' => 'ẕ', + 'ẞ' => 'ß', + 'Ạ' => 'ạ', + 'Ả' => 'ả', + 'Ấ' => 'ấ', + 'Ầ' => 'ầ', + 'Ẩ' => 'ẩ', + 'Ẫ' => 'ẫ', + 'Ậ' => 'ậ', + 'Ắ' => 'ắ', + 'Ằ' => 'ằ', + 'Ẳ' => 'ẳ', + 'Ẵ' => 'ẵ', + 'Ặ' => 'ặ', + 'Ẹ' => 'ẹ', + 'Ẻ' => 'ẻ', + 'Ẽ' => 'ẽ', + 'Ế' => 'ế', + 'Ề' => 'ề', + 'Ể' => 'ể', + 'Ễ' => 'ễ', + 'Ệ' => 'ệ', + 'Ỉ' => 'ỉ', + 'Ị' => 'ị', + 'Ọ' => 'ọ', + 'Ỏ' => 'ỏ', + 'Ố' => 'ố', + 'Ồ' => 'ồ', + 'Ổ' => 'ổ', + 'Ỗ' => 'ỗ', + 'Ộ' => 'ộ', + 'Ớ' => 'ớ', + 'Ờ' => 'ờ', + 'Ở' => 'ở', + 'Ỡ' => 'ỡ', + 'Ợ' => 'ợ', + 'Ụ' => 'ụ', + 'Ủ' => 'ủ', + 'Ứ' => 'ứ', + 'Ừ' => 'ừ', + 'Ử' => 'ử', + 'Ữ' => 'ữ', + 'Ự' => 'ự', + 'Ỳ' => 'ỳ', + 'Ỵ' => 'ỵ', + 'Ỷ' => 'ỷ', + 'Ỹ' => 'ỹ', + 'Ỻ' => 'ỻ', + 'Ỽ' => 'ỽ', + 'Ỿ' => 'ỿ', + 'Ἀ' => 'ἀ', + 'Ἁ' => 'ἁ', + 'Ἂ' => 'ἂ', + 'Ἃ' => 'ἃ', + 'Ἄ' => 'ἄ', + 'Ἅ' => 'ἅ', + 'Ἆ' => 'ἆ', + 'Ἇ' => 'ἇ', + 'Ἐ' => 'ἐ', + 'Ἑ' => 'ἑ', + 'Ἒ' => 'ἒ', + 'Ἓ' => 'ἓ', + 'Ἔ' => 'ἔ', + 'Ἕ' => 'ἕ', + 'Ἠ' => 'ἠ', + 'Ἡ' => 'ἡ', + 'Ἢ' => 'ἢ', + 'Ἣ' => 'ἣ', + 'Ἤ' => 'ἤ', + 'Ἥ' => 'ἥ', + 'Ἦ' => 'ἦ', + 'Ἧ' => 'ἧ', + 'Ἰ' => 'ἰ', + 'Ἱ' => 'ἱ', + 'Ἲ' => 'ἲ', + 'Ἳ' => 'ἳ', + 'Ἴ' => 'ἴ', + 'Ἵ' => 'ἵ', + 'Ἶ' => 'ἶ', + 'Ἷ' => 'ἷ', + 'Ὀ' => 'ὀ', + 'Ὁ' => 'ὁ', + 'Ὂ' => 'ὂ', + 'Ὃ' => 'ὃ', + 'Ὄ' => 'ὄ', + 'Ὅ' => 'ὅ', + 'Ὑ' => 'ὑ', + 'Ὓ' => 'ὓ', + 'Ὕ' => 'ὕ', + 'Ὗ' => 'ὗ', + 'Ὠ' => 'ὠ', + 'Ὡ' => 'ὡ', + 'Ὢ' => 'ὢ', + 'Ὣ' => 'ὣ', + 'Ὤ' => 'ὤ', + 'Ὥ' => 'ὥ', + 'Ὦ' => 'ὦ', + 'Ὧ' => 'ὧ', + 'ᾈ' => 'ᾀ', + 'ᾉ' => 'ᾁ', + 'ᾊ' => 'ᾂ', + 'ᾋ' => 'ᾃ', + 'ᾌ' => 'ᾄ', + 'ᾍ' => 'ᾅ', + 'ᾎ' => 'ᾆ', + 'ᾏ' => 'ᾇ', + 'ᾘ' => 'ᾐ', + 'ᾙ' => 'ᾑ', + 'ᾚ' => 'ᾒ', + 'ᾛ' => 'ᾓ', + 'ᾜ' => 'ᾔ', + 'ᾝ' => 'ᾕ', + 'ᾞ' => 'ᾖ', + 'ᾟ' => 'ᾗ', + 'ᾨ' => 'ᾠ', + 'ᾩ' => 'ᾡ', + 'ᾪ' => 'ᾢ', + 'ᾫ' => 'ᾣ', + 'ᾬ' => 'ᾤ', + 'ᾭ' => 'ᾥ', + 'ᾮ' => 'ᾦ', + 'ᾯ' => 'ᾧ', + 'Ᾰ' => 'ᾰ', + 'Ᾱ' => 'ᾱ', + 'Ὰ' => 'ὰ', + 'Ά' => 'ά', + 'ᾼ' => 'ᾳ', + 'Ὲ' => 'ὲ', + 'Έ' => 'έ', + 'Ὴ' => 'ὴ', + 'Ή' => 'ή', + 'ῌ' => 'ῃ', + 'Ῐ' => 'ῐ', + 'Ῑ' => 'ῑ', + 'Ὶ' => 'ὶ', + 'Ί' => 'ί', + 'Ῠ' => 'ῠ', + 'Ῡ' => 'ῡ', + 'Ὺ' => 'ὺ', + 'Ύ' => 'ύ', + 'Ῥ' => 'ῥ', + 'Ὸ' => 'ὸ', + 'Ό' => 'ό', + 'Ὼ' => 'ὼ', + 'Ώ' => 'ώ', + 'ῼ' => 'ῳ', + 'Ω' => 'ω', + 'K' => 'k', + 'Å' => 'å', + 'Ⅎ' => 'ⅎ', + 'Ⅰ' => 'ⅰ', + 'Ⅱ' => 'ⅱ', + 'Ⅲ' => 'ⅲ', + 'Ⅳ' => 'ⅳ', + 'Ⅴ' => 'ⅴ', + 'Ⅵ' => 'ⅵ', + 'Ⅶ' => 'ⅶ', + 'Ⅷ' => 'ⅷ', + 'Ⅸ' => 'ⅸ', + 'Ⅹ' => 'ⅹ', + 'Ⅺ' => 'ⅺ', + 'Ⅻ' => 'ⅻ', + 'Ⅼ' => 'ⅼ', + 'Ⅽ' => 'ⅽ', + 'Ⅾ' => 'ⅾ', + 'Ⅿ' => 'ⅿ', + 'Ↄ' => 'ↄ', + 'Ⓐ' => 'ⓐ', + 'Ⓑ' => 'ⓑ', + 'Ⓒ' => 'ⓒ', + 'Ⓓ' => 'ⓓ', + 'Ⓔ' => 'ⓔ', + 'Ⓕ' => 'ⓕ', + 'Ⓖ' => 'ⓖ', + 'Ⓗ' => 'ⓗ', + 'Ⓘ' => 'ⓘ', + 'Ⓙ' => 'ⓙ', + 'Ⓚ' => 'ⓚ', + 'Ⓛ' => 'ⓛ', + 'Ⓜ' => 'ⓜ', + 'Ⓝ' => 'ⓝ', + 'Ⓞ' => 'ⓞ', + 'Ⓟ' => 'ⓟ', + 'Ⓠ' => 'ⓠ', + 'Ⓡ' => 'ⓡ', + 'Ⓢ' => 'ⓢ', + 'Ⓣ' => 'ⓣ', + 'Ⓤ' => 'ⓤ', + 'Ⓥ' => 'ⓥ', + 'Ⓦ' => 'ⓦ', + 'Ⓧ' => 'ⓧ', + 'Ⓨ' => 'ⓨ', + 'Ⓩ' => 'ⓩ', + 'Ⰰ' => 'ⰰ', + 'Ⰱ' => 'ⰱ', + 'Ⰲ' => 'ⰲ', + 'Ⰳ' => 'ⰳ', + 'Ⰴ' => 'ⰴ', + 'Ⰵ' => 'ⰵ', + 'Ⰶ' => 'ⰶ', + 'Ⰷ' => 'ⰷ', + 'Ⰸ' => 'ⰸ', + 'Ⰹ' => 'ⰹ', + 'Ⰺ' => 'ⰺ', + 'Ⰻ' => 'ⰻ', + 'Ⰼ' => 'ⰼ', + 'Ⰽ' => 'ⰽ', + 'Ⰾ' => 'ⰾ', + 'Ⰿ' => 'ⰿ', + 'Ⱀ' => 'ⱀ', + 'Ⱁ' => 'ⱁ', + 'Ⱂ' => 'ⱂ', + 'Ⱃ' => 'ⱃ', + 'Ⱄ' => 'ⱄ', + 'Ⱅ' => 'ⱅ', + 'Ⱆ' => 'ⱆ', + 'Ⱇ' => 'ⱇ', + 'Ⱈ' => 'ⱈ', + 'Ⱉ' => 'ⱉ', + 'Ⱊ' => 'ⱊ', + 'Ⱋ' => 'ⱋ', + 'Ⱌ' => 'ⱌ', + 'Ⱍ' => 'ⱍ', + 'Ⱎ' => 'ⱎ', + 'Ⱏ' => 'ⱏ', + 'Ⱐ' => 'ⱐ', + 'Ⱑ' => 'ⱑ', + 'Ⱒ' => 'ⱒ', + 'Ⱓ' => 'ⱓ', + 'Ⱔ' => 'ⱔ', + 'Ⱕ' => 'ⱕ', + 'Ⱖ' => 'ⱖ', + 'Ⱗ' => 'ⱗ', + 'Ⱘ' => 'ⱘ', + 'Ⱙ' => 'ⱙ', + 'Ⱚ' => 'ⱚ', + 'Ⱛ' => 'ⱛ', + 'Ⱜ' => 'ⱜ', + 'Ⱝ' => 'ⱝ', + 'Ⱞ' => 'ⱞ', + 'Ⱡ' => 'ⱡ', + 'Ɫ' => 'ɫ', + 'Ᵽ' => 'ᵽ', + 'Ɽ' => 'ɽ', + 'Ⱨ' => 'ⱨ', + 'Ⱪ' => 'ⱪ', + 'Ⱬ' => 'ⱬ', + 'Ɑ' => 'ɑ', + 'Ɱ' => 'ɱ', + 'Ɐ' => 'ɐ', + 'Ɒ' => 'ɒ', + 'Ⱳ' => 'ⱳ', + 'Ⱶ' => 'ⱶ', + 'Ȿ' => 'ȿ', + 'Ɀ' => 'ɀ', + 'Ⲁ' => 'ⲁ', + 'Ⲃ' => 'ⲃ', + 'Ⲅ' => 'ⲅ', + 'Ⲇ' => 'ⲇ', + 'Ⲉ' => 'ⲉ', + 'Ⲋ' => 'ⲋ', + 'Ⲍ' => 'ⲍ', + 'Ⲏ' => 'ⲏ', + 'Ⲑ' => 'ⲑ', + 'Ⲓ' => 'ⲓ', + 'Ⲕ' => 'ⲕ', + 'Ⲗ' => 'ⲗ', + 'Ⲙ' => 'ⲙ', + 'Ⲛ' => 'ⲛ', + 'Ⲝ' => 'ⲝ', + 'Ⲟ' => 'ⲟ', + 'Ⲡ' => 'ⲡ', + 'Ⲣ' => 'ⲣ', + 'Ⲥ' => 'ⲥ', + 'Ⲧ' => 'ⲧ', + 'Ⲩ' => 'ⲩ', + 'Ⲫ' => 'ⲫ', + 'Ⲭ' => 'ⲭ', + 'Ⲯ' => 'ⲯ', + 'Ⲱ' => 'ⲱ', + 'Ⲳ' => 'ⲳ', + 'Ⲵ' => 'ⲵ', + 'Ⲷ' => 'ⲷ', + 'Ⲹ' => 'ⲹ', + 'Ⲻ' => 'ⲻ', + 'Ⲽ' => 'ⲽ', + 'Ⲿ' => 'ⲿ', + 'Ⳁ' => 'ⳁ', + 'Ⳃ' => 'ⳃ', + 'Ⳅ' => 'ⳅ', + 'Ⳇ' => 'ⳇ', + 'Ⳉ' => 'ⳉ', + 'Ⳋ' => 'ⳋ', + 'Ⳍ' => 'ⳍ', + 'Ⳏ' => 'ⳏ', + 'Ⳑ' => 'ⳑ', + 'Ⳓ' => 'ⳓ', + 'Ⳕ' => 'ⳕ', + 'Ⳗ' => 'ⳗ', + 'Ⳙ' => 'ⳙ', + 'Ⳛ' => 'ⳛ', + 'Ⳝ' => 'ⳝ', + 'Ⳟ' => 'ⳟ', + 'Ⳡ' => 'ⳡ', + 'Ⳣ' => 'ⳣ', + 'Ⳬ' => 'ⳬ', + 'Ⳮ' => 'ⳮ', + 'Ⳳ' => 'ⳳ', + 'Ꙁ' => 'ꙁ', + 'Ꙃ' => 'ꙃ', + 'Ꙅ' => 'ꙅ', + 'Ꙇ' => 'ꙇ', + 'Ꙉ' => 'ꙉ', + 'Ꙋ' => 'ꙋ', + 'Ꙍ' => 'ꙍ', + 'Ꙏ' => 'ꙏ', + 'Ꙑ' => 'ꙑ', + 'Ꙓ' => 'ꙓ', + 'Ꙕ' => 'ꙕ', + 'Ꙗ' => 'ꙗ', + 'Ꙙ' => 'ꙙ', + 'Ꙛ' => 'ꙛ', + 'Ꙝ' => 'ꙝ', + 'Ꙟ' => 'ꙟ', + 'Ꙡ' => 'ꙡ', + 'Ꙣ' => 'ꙣ', + 'Ꙥ' => 'ꙥ', + 'Ꙧ' => 'ꙧ', + 'Ꙩ' => 'ꙩ', + 'Ꙫ' => 'ꙫ', + 'Ꙭ' => 'ꙭ', + 'Ꚁ' => 'ꚁ', + 'Ꚃ' => 'ꚃ', + 'Ꚅ' => 'ꚅ', + 'Ꚇ' => 'ꚇ', + 'Ꚉ' => 'ꚉ', + 'Ꚋ' => 'ꚋ', + 'Ꚍ' => 'ꚍ', + 'Ꚏ' => 'ꚏ', + 'Ꚑ' => 'ꚑ', + 'Ꚓ' => 'ꚓ', + 'Ꚕ' => 'ꚕ', + 'Ꚗ' => 'ꚗ', + 'Ꚙ' => 'ꚙ', + 'Ꚛ' => 'ꚛ', + 'Ꜣ' => 'ꜣ', + 'Ꜥ' => 'ꜥ', + 'Ꜧ' => 'ꜧ', + 'Ꜩ' => 'ꜩ', + 'Ꜫ' => 'ꜫ', + 'Ꜭ' => 'ꜭ', + 'Ꜯ' => 'ꜯ', + 'Ꜳ' => 'ꜳ', + 'Ꜵ' => 'ꜵ', + 'Ꜷ' => 'ꜷ', + 'Ꜹ' => 'ꜹ', + 'Ꜻ' => 'ꜻ', + 'Ꜽ' => 'ꜽ', + 'Ꜿ' => 'ꜿ', + 'Ꝁ' => 'ꝁ', + 'Ꝃ' => 'ꝃ', + 'Ꝅ' => 'ꝅ', + 'Ꝇ' => 'ꝇ', + 'Ꝉ' => 'ꝉ', + 'Ꝋ' => 'ꝋ', + 'Ꝍ' => 'ꝍ', + 'Ꝏ' => 'ꝏ', + 'Ꝑ' => 'ꝑ', + 'Ꝓ' => 'ꝓ', + 'Ꝕ' => 'ꝕ', + 'Ꝗ' => 'ꝗ', + 'Ꝙ' => 'ꝙ', + 'Ꝛ' => 'ꝛ', + 'Ꝝ' => 'ꝝ', + 'Ꝟ' => 'ꝟ', + 'Ꝡ' => 'ꝡ', + 'Ꝣ' => 'ꝣ', + 'Ꝥ' => 'ꝥ', + 'Ꝧ' => 'ꝧ', + 'Ꝩ' => 'ꝩ', + 'Ꝫ' => 'ꝫ', + 'Ꝭ' => 'ꝭ', + 'Ꝯ' => 'ꝯ', + 'Ꝺ' => 'ꝺ', + 'Ꝼ' => 'ꝼ', + 'Ᵹ' => 'ᵹ', + 'Ꝿ' => 'ꝿ', + 'Ꞁ' => 'ꞁ', + 'Ꞃ' => 'ꞃ', + 'Ꞅ' => 'ꞅ', + 'Ꞇ' => 'ꞇ', + 'Ꞌ' => 'ꞌ', + 'Ɥ' => 'ɥ', + 'Ꞑ' => 'ꞑ', + 'Ꞓ' => 'ꞓ', + 'Ꞗ' => 'ꞗ', + 'Ꞙ' => 'ꞙ', + 'Ꞛ' => 'ꞛ', + 'Ꞝ' => 'ꞝ', + 'Ꞟ' => 'ꞟ', + 'Ꞡ' => 'ꞡ', + 'Ꞣ' => 'ꞣ', + 'Ꞥ' => 'ꞥ', + 'Ꞧ' => 'ꞧ', + 'Ꞩ' => 'ꞩ', + 'Ɦ' => 'ɦ', + 'Ɜ' => 'ɜ', + 'Ɡ' => 'ɡ', + 'Ɬ' => 'ɬ', + 'Ɪ' => 'ɪ', + 'Ʞ' => 'ʞ', + 'Ʇ' => 'ʇ', + 'Ʝ' => 'ʝ', + 'Ꭓ' => 'ꭓ', + 'Ꞵ' => 'ꞵ', + 'Ꞷ' => 'ꞷ', + 'Ꞹ' => 'ꞹ', + 'Ꞻ' => 'ꞻ', + 'Ꞽ' => 'ꞽ', + 'Ꞿ' => 'ꞿ', + 'Ꟃ' => 'ꟃ', + 'Ꞔ' => 'ꞔ', + 'Ʂ' => 'ʂ', + 'Ᶎ' => 'ᶎ', + 'Ꟈ' => 'ꟈ', + 'Ꟊ' => 'ꟊ', + 'Ꟶ' => 'ꟶ', + 'A' => 'a', + 'B' => 'b', + 'C' => 'c', + 'D' => 'd', + 'E' => 'e', + 'F' => 'f', + 'G' => 'g', + 'H' => 'h', + 'I' => 'i', + 'J' => 'j', + 'K' => 'k', + 'L' => 'l', + 'M' => 'm', + 'N' => 'n', + 'O' => 'o', + 'P' => 'p', + 'Q' => 'q', + 'R' => 'r', + 'S' => 's', + 'T' => 't', + 'U' => 'u', + 'V' => 'v', + 'W' => 'w', + 'X' => 'x', + 'Y' => 'y', + 'Z' => 'z', + '𐐀' => '𐐨', + '𐐁' => '𐐩', + '𐐂' => '𐐪', + '𐐃' => '𐐫', + '𐐄' => '𐐬', + '𐐅' => '𐐭', + '𐐆' => '𐐮', + '𐐇' => '𐐯', + '𐐈' => '𐐰', + '𐐉' => '𐐱', + '𐐊' => '𐐲', + '𐐋' => '𐐳', + '𐐌' => '𐐴', + '𐐍' => '𐐵', + '𐐎' => '𐐶', + '𐐏' => '𐐷', + '𐐐' => '𐐸', + '𐐑' => '𐐹', + '𐐒' => '𐐺', + '𐐓' => '𐐻', + '𐐔' => '𐐼', + '𐐕' => '𐐽', + '𐐖' => '𐐾', + '𐐗' => '𐐿', + '𐐘' => '𐑀', + '𐐙' => '𐑁', + '𐐚' => '𐑂', + '𐐛' => '𐑃', + '𐐜' => '𐑄', + '𐐝' => '𐑅', + '𐐞' => '𐑆', + '𐐟' => '𐑇', + '𐐠' => '𐑈', + '𐐡' => '𐑉', + '𐐢' => '𐑊', + '𐐣' => '𐑋', + '𐐤' => '𐑌', + '𐐥' => '𐑍', + '𐐦' => '𐑎', + '𐐧' => '𐑏', + '𐒰' => '𐓘', + '𐒱' => '𐓙', + '𐒲' => '𐓚', + '𐒳' => '𐓛', + '𐒴' => '𐓜', + '𐒵' => '𐓝', + '𐒶' => '𐓞', + '𐒷' => '𐓟', + '𐒸' => '𐓠', + '𐒹' => '𐓡', + '𐒺' => '𐓢', + '𐒻' => '𐓣', + '𐒼' => '𐓤', + '𐒽' => '𐓥', + '𐒾' => '𐓦', + '𐒿' => '𐓧', + '𐓀' => '𐓨', + '𐓁' => '𐓩', + '𐓂' => '𐓪', + '𐓃' => '𐓫', + '𐓄' => '𐓬', + '𐓅' => '𐓭', + '𐓆' => '𐓮', + '𐓇' => '𐓯', + '𐓈' => '𐓰', + '𐓉' => '𐓱', + '𐓊' => '𐓲', + '𐓋' => '𐓳', + '𐓌' => '𐓴', + '𐓍' => '𐓵', + '𐓎' => '𐓶', + '𐓏' => '𐓷', + '𐓐' => '𐓸', + '𐓑' => '𐓹', + '𐓒' => '𐓺', + '𐓓' => '𐓻', + '𐲀' => '𐳀', + '𐲁' => '𐳁', + '𐲂' => '𐳂', + '𐲃' => '𐳃', + '𐲄' => '𐳄', + '𐲅' => '𐳅', + '𐲆' => '𐳆', + '𐲇' => '𐳇', + '𐲈' => '𐳈', + '𐲉' => '𐳉', + '𐲊' => '𐳊', + '𐲋' => '𐳋', + '𐲌' => '𐳌', + '𐲍' => '𐳍', + '𐲎' => '𐳎', + '𐲏' => '𐳏', + '𐲐' => '𐳐', + '𐲑' => '𐳑', + '𐲒' => '𐳒', + '𐲓' => '𐳓', + '𐲔' => '𐳔', + '𐲕' => '𐳕', + '𐲖' => '𐳖', + '𐲗' => '𐳗', + '𐲘' => '𐳘', + '𐲙' => '𐳙', + '𐲚' => '𐳚', + '𐲛' => '𐳛', + '𐲜' => '𐳜', + '𐲝' => '𐳝', + '𐲞' => '𐳞', + '𐲟' => '𐳟', + '𐲠' => '𐳠', + '𐲡' => '𐳡', + '𐲢' => '𐳢', + '𐲣' => '𐳣', + '𐲤' => '𐳤', + '𐲥' => '𐳥', + '𐲦' => '𐳦', + '𐲧' => '𐳧', + '𐲨' => '𐳨', + '𐲩' => '𐳩', + '𐲪' => '𐳪', + '𐲫' => '𐳫', + '𐲬' => '𐳬', + '𐲭' => '𐳭', + '𐲮' => '𐳮', + '𐲯' => '𐳯', + '𐲰' => '𐳰', + '𐲱' => '𐳱', + '𐲲' => '𐳲', + '𑢠' => '𑣀', + '𑢡' => '𑣁', + '𑢢' => '𑣂', + '𑢣' => '𑣃', + '𑢤' => '𑣄', + '𑢥' => '𑣅', + '𑢦' => '𑣆', + '𑢧' => '𑣇', + '𑢨' => '𑣈', + '𑢩' => '𑣉', + '𑢪' => '𑣊', + '𑢫' => '𑣋', + '𑢬' => '𑣌', + '𑢭' => '𑣍', + '𑢮' => '𑣎', + '𑢯' => '𑣏', + '𑢰' => '𑣐', + '𑢱' => '𑣑', + '𑢲' => '𑣒', + '𑢳' => '𑣓', + '𑢴' => '𑣔', + '𑢵' => '𑣕', + '𑢶' => '𑣖', + '𑢷' => '𑣗', + '𑢸' => '𑣘', + '𑢹' => '𑣙', + '𑢺' => '𑣚', + '𑢻' => '𑣛', + '𑢼' => '𑣜', + '𑢽' => '𑣝', + '𑢾' => '𑣞', + '𑢿' => '𑣟', + '𖹀' => '𖹠', + '𖹁' => '𖹡', + '𖹂' => '𖹢', + '𖹃' => '𖹣', + '𖹄' => '𖹤', + '𖹅' => '𖹥', + '𖹆' => '𖹦', + '𖹇' => '𖹧', + '𖹈' => '𖹨', + '𖹉' => '𖹩', + '𖹊' => '𖹪', + '𖹋' => '𖹫', + '𖹌' => '𖹬', + '𖹍' => '𖹭', + '𖹎' => '𖹮', + '𖹏' => '𖹯', + '𖹐' => '𖹰', + '𖹑' => '𖹱', + '𖹒' => '𖹲', + '𖹓' => '𖹳', + '𖹔' => '𖹴', + '𖹕' => '𖹵', + '𖹖' => '𖹶', + '𖹗' => '𖹷', + '𖹘' => '𖹸', + '𖹙' => '𖹹', + '𖹚' => '𖹺', + '𖹛' => '𖹻', + '𖹜' => '𖹼', + '𖹝' => '𖹽', + '𖹞' => '𖹾', + '𖹟' => '𖹿', + '𞤀' => '𞤢', + '𞤁' => '𞤣', + '𞤂' => '𞤤', + '𞤃' => '𞤥', + '𞤄' => '𞤦', + '𞤅' => '𞤧', + '𞤆' => '𞤨', + '𞤇' => '𞤩', + '𞤈' => '𞤪', + '𞤉' => '𞤫', + '𞤊' => '𞤬', + '𞤋' => '𞤭', + '𞤌' => '𞤮', + '𞤍' => '𞤯', + '𞤎' => '𞤰', + '𞤏' => '𞤱', + '𞤐' => '𞤲', + '𞤑' => '𞤳', + '𞤒' => '𞤴', + '𞤓' => '𞤵', + '𞤔' => '𞤶', + '𞤕' => '𞤷', + '𞤖' => '𞤸', + '𞤗' => '𞤹', + '𞤘' => '𞤺', + '𞤙' => '𞤻', + '𞤚' => '𞤼', + '𞤛' => '𞤽', + '𞤜' => '𞤾', + '𞤝' => '𞤿', + '𞤞' => '𞥀', + '𞤟' => '𞥁', + '𞤠' => '𞥂', + '𞤡' => '𞥃', +); diff --git a/lib/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php b/lib/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php new file mode 100644 index 00000000..2a8f6e73 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php @@ -0,0 +1,5 @@ + 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + 'µ' => 'Μ', + 'à' => 'À', + 'á' => 'Á', + 'â' => 'Â', + 'ã' => 'Ã', + 'ä' => 'Ä', + 'å' => 'Å', + 'æ' => 'Æ', + 'ç' => 'Ç', + 'è' => 'È', + 'é' => 'É', + 'ê' => 'Ê', + 'ë' => 'Ë', + 'ì' => 'Ì', + 'í' => 'Í', + 'î' => 'Î', + 'ï' => 'Ï', + 'ð' => 'Ð', + 'ñ' => 'Ñ', + 'ò' => 'Ò', + 'ó' => 'Ó', + 'ô' => 'Ô', + 'õ' => 'Õ', + 'ö' => 'Ö', + 'ø' => 'Ø', + 'ù' => 'Ù', + 'ú' => 'Ú', + 'û' => 'Û', + 'ü' => 'Ü', + 'ý' => 'Ý', + 'þ' => 'Þ', + 'ÿ' => 'Ÿ', + 'ā' => 'Ā', + 'ă' => 'Ă', + 'ą' => 'Ą', + 'ć' => 'Ć', + 'ĉ' => 'Ĉ', + 'ċ' => 'Ċ', + 'č' => 'Č', + 'ď' => 'Ď', + 'đ' => 'Đ', + 'ē' => 'Ē', + 'ĕ' => 'Ĕ', + 'ė' => 'Ė', + 'ę' => 'Ę', + 'ě' => 'Ě', + 'ĝ' => 'Ĝ', + 'ğ' => 'Ğ', + 'ġ' => 'Ġ', + 'ģ' => 'Ģ', + 'ĥ' => 'Ĥ', + 'ħ' => 'Ħ', + 'ĩ' => 'Ĩ', + 'ī' => 'Ī', + 'ĭ' => 'Ĭ', + 'į' => 'Į', + 'ı' => 'I', + 'ij' => 'IJ', + 'ĵ' => 'Ĵ', + 'ķ' => 'Ķ', + 'ĺ' => 'Ĺ', + 'ļ' => 'Ļ', + 'ľ' => 'Ľ', + 'ŀ' => 'Ŀ', + 'ł' => 'Ł', + 'ń' => 'Ń', + 'ņ' => 'Ņ', + 'ň' => 'Ň', + 'ŋ' => 'Ŋ', + 'ō' => 'Ō', + 'ŏ' => 'Ŏ', + 'ő' => 'Ő', + 'œ' => 'Œ', + 'ŕ' => 'Ŕ', + 'ŗ' => 'Ŗ', + 'ř' => 'Ř', + 'ś' => 'Ś', + 'ŝ' => 'Ŝ', + 'ş' => 'Ş', + 'š' => 'Š', + 'ţ' => 'Ţ', + 'ť' => 'Ť', + 'ŧ' => 'Ŧ', + 'ũ' => 'Ũ', + 'ū' => 'Ū', + 'ŭ' => 'Ŭ', + 'ů' => 'Ů', + 'ű' => 'Ű', + 'ų' => 'Ų', + 'ŵ' => 'Ŵ', + 'ŷ' => 'Ŷ', + 'ź' => 'Ź', + 'ż' => 'Ż', + 'ž' => 'Ž', + 'ſ' => 'S', + 'ƀ' => 'Ƀ', + 'ƃ' => 'Ƃ', + 'ƅ' => 'Ƅ', + 'ƈ' => 'Ƈ', + 'ƌ' => 'Ƌ', + 'ƒ' => 'Ƒ', + 'ƕ' => 'Ƕ', + 'ƙ' => 'Ƙ', + 'ƚ' => 'Ƚ', + 'ƞ' => 'Ƞ', + 'ơ' => 'Ơ', + 'ƣ' => 'Ƣ', + 'ƥ' => 'Ƥ', + 'ƨ' => 'Ƨ', + 'ƭ' => 'Ƭ', + 'ư' => 'Ư', + 'ƴ' => 'Ƴ', + 'ƶ' => 'Ƶ', + 'ƹ' => 'Ƹ', + 'ƽ' => 'Ƽ', + 'ƿ' => 'Ƿ', + 'Dž' => 'DŽ', + 'dž' => 'DŽ', + 'Lj' => 'LJ', + 'lj' => 'LJ', + 'Nj' => 'NJ', + 'nj' => 'NJ', + 'ǎ' => 'Ǎ', + 'ǐ' => 'Ǐ', + 'ǒ' => 'Ǒ', + 'ǔ' => 'Ǔ', + 'ǖ' => 'Ǖ', + 'ǘ' => 'Ǘ', + 'ǚ' => 'Ǚ', + 'ǜ' => 'Ǜ', + 'ǝ' => 'Ǝ', + 'ǟ' => 'Ǟ', + 'ǡ' => 'Ǡ', + 'ǣ' => 'Ǣ', + 'ǥ' => 'Ǥ', + 'ǧ' => 'Ǧ', + 'ǩ' => 'Ǩ', + 'ǫ' => 'Ǫ', + 'ǭ' => 'Ǭ', + 'ǯ' => 'Ǯ', + 'Dz' => 'DZ', + 'dz' => 'DZ', + 'ǵ' => 'Ǵ', + 'ǹ' => 'Ǹ', + 'ǻ' => 'Ǻ', + 'ǽ' => 'Ǽ', + 'ǿ' => 'Ǿ', + 'ȁ' => 'Ȁ', + 'ȃ' => 'Ȃ', + 'ȅ' => 'Ȅ', + 'ȇ' => 'Ȇ', + 'ȉ' => 'Ȉ', + 'ȋ' => 'Ȋ', + 'ȍ' => 'Ȍ', + 'ȏ' => 'Ȏ', + 'ȑ' => 'Ȑ', + 'ȓ' => 'Ȓ', + 'ȕ' => 'Ȕ', + 'ȗ' => 'Ȗ', + 'ș' => 'Ș', + 'ț' => 'Ț', + 'ȝ' => 'Ȝ', + 'ȟ' => 'Ȟ', + 'ȣ' => 'Ȣ', + 'ȥ' => 'Ȥ', + 'ȧ' => 'Ȧ', + 'ȩ' => 'Ȩ', + 'ȫ' => 'Ȫ', + 'ȭ' => 'Ȭ', + 'ȯ' => 'Ȯ', + 'ȱ' => 'Ȱ', + 'ȳ' => 'Ȳ', + 'ȼ' => 'Ȼ', + 'ȿ' => 'Ȿ', + 'ɀ' => 'Ɀ', + 'ɂ' => 'Ɂ', + 'ɇ' => 'Ɇ', + 'ɉ' => 'Ɉ', + 'ɋ' => 'Ɋ', + 'ɍ' => 'Ɍ', + 'ɏ' => 'Ɏ', + 'ɐ' => 'Ɐ', + 'ɑ' => 'Ɑ', + 'ɒ' => 'Ɒ', + 'ɓ' => 'Ɓ', + 'ɔ' => 'Ɔ', + 'ɖ' => 'Ɖ', + 'ɗ' => 'Ɗ', + 'ə' => 'Ə', + 'ɛ' => 'Ɛ', + 'ɜ' => 'Ɜ', + 'ɠ' => 'Ɠ', + 'ɡ' => 'Ɡ', + 'ɣ' => 'Ɣ', + 'ɥ' => 'Ɥ', + 'ɦ' => 'Ɦ', + 'ɨ' => 'Ɨ', + 'ɩ' => 'Ɩ', + 'ɪ' => 'Ɪ', + 'ɫ' => 'Ɫ', + 'ɬ' => 'Ɬ', + 'ɯ' => 'Ɯ', + 'ɱ' => 'Ɱ', + 'ɲ' => 'Ɲ', + 'ɵ' => 'Ɵ', + 'ɽ' => 'Ɽ', + 'ʀ' => 'Ʀ', + 'ʂ' => 'Ʂ', + 'ʃ' => 'Ʃ', + 'ʇ' => 'Ʇ', + 'ʈ' => 'Ʈ', + 'ʉ' => 'Ʉ', + 'ʊ' => 'Ʊ', + 'ʋ' => 'Ʋ', + 'ʌ' => 'Ʌ', + 'ʒ' => 'Ʒ', + 'ʝ' => 'Ʝ', + 'ʞ' => 'Ʞ', + 'ͅ' => 'Ι', + 'ͱ' => 'Ͱ', + 'ͳ' => 'Ͳ', + 'ͷ' => 'Ͷ', + 'ͻ' => 'Ͻ', + 'ͼ' => 'Ͼ', + 'ͽ' => 'Ͽ', + 'ά' => 'Ά', + 'έ' => 'Έ', + 'ή' => 'Ή', + 'ί' => 'Ί', + 'α' => 'Α', + 'β' => 'Β', + 'γ' => 'Γ', + 'δ' => 'Δ', + 'ε' => 'Ε', + 'ζ' => 'Ζ', + 'η' => 'Η', + 'θ' => 'Θ', + 'ι' => 'Ι', + 'κ' => 'Κ', + 'λ' => 'Λ', + 'μ' => 'Μ', + 'ν' => 'Ν', + 'ξ' => 'Ξ', + 'ο' => 'Ο', + 'π' => 'Π', + 'ρ' => 'Ρ', + 'ς' => 'Σ', + 'σ' => 'Σ', + 'τ' => 'Τ', + 'υ' => 'Υ', + 'φ' => 'Φ', + 'χ' => 'Χ', + 'ψ' => 'Ψ', + 'ω' => 'Ω', + 'ϊ' => 'Ϊ', + 'ϋ' => 'Ϋ', + 'ό' => 'Ό', + 'ύ' => 'Ύ', + 'ώ' => 'Ώ', + 'ϐ' => 'Β', + 'ϑ' => 'Θ', + 'ϕ' => 'Φ', + 'ϖ' => 'Π', + 'ϗ' => 'Ϗ', + 'ϙ' => 'Ϙ', + 'ϛ' => 'Ϛ', + 'ϝ' => 'Ϝ', + 'ϟ' => 'Ϟ', + 'ϡ' => 'Ϡ', + 'ϣ' => 'Ϣ', + 'ϥ' => 'Ϥ', + 'ϧ' => 'Ϧ', + 'ϩ' => 'Ϩ', + 'ϫ' => 'Ϫ', + 'ϭ' => 'Ϭ', + 'ϯ' => 'Ϯ', + 'ϰ' => 'Κ', + 'ϱ' => 'Ρ', + 'ϲ' => 'Ϲ', + 'ϳ' => 'Ϳ', + 'ϵ' => 'Ε', + 'ϸ' => 'Ϸ', + 'ϻ' => 'Ϻ', + 'а' => 'А', + 'б' => 'Б', + 'в' => 'В', + 'г' => 'Г', + 'д' => 'Д', + 'е' => 'Е', + 'ж' => 'Ж', + 'з' => 'З', + 'и' => 'И', + 'й' => 'Й', + 'к' => 'К', + 'л' => 'Л', + 'м' => 'М', + 'н' => 'Н', + 'о' => 'О', + 'п' => 'П', + 'р' => 'Р', + 'с' => 'С', + 'т' => 'Т', + 'у' => 'У', + 'ф' => 'Ф', + 'х' => 'Х', + 'ц' => 'Ц', + 'ч' => 'Ч', + 'ш' => 'Ш', + 'щ' => 'Щ', + 'ъ' => 'Ъ', + 'ы' => 'Ы', + 'ь' => 'Ь', + 'э' => 'Э', + 'ю' => 'Ю', + 'я' => 'Я', + 'ѐ' => 'Ѐ', + 'ё' => 'Ё', + 'ђ' => 'Ђ', + 'ѓ' => 'Ѓ', + 'є' => 'Є', + 'ѕ' => 'Ѕ', + 'і' => 'І', + 'ї' => 'Ї', + 'ј' => 'Ј', + 'љ' => 'Љ', + 'њ' => 'Њ', + 'ћ' => 'Ћ', + 'ќ' => 'Ќ', + 'ѝ' => 'Ѝ', + 'ў' => 'Ў', + 'џ' => 'Џ', + 'ѡ' => 'Ѡ', + 'ѣ' => 'Ѣ', + 'ѥ' => 'Ѥ', + 'ѧ' => 'Ѧ', + 'ѩ' => 'Ѩ', + 'ѫ' => 'Ѫ', + 'ѭ' => 'Ѭ', + 'ѯ' => 'Ѯ', + 'ѱ' => 'Ѱ', + 'ѳ' => 'Ѳ', + 'ѵ' => 'Ѵ', + 'ѷ' => 'Ѷ', + 'ѹ' => 'Ѹ', + 'ѻ' => 'Ѻ', + 'ѽ' => 'Ѽ', + 'ѿ' => 'Ѿ', + 'ҁ' => 'Ҁ', + 'ҋ' => 'Ҋ', + 'ҍ' => 'Ҍ', + 'ҏ' => 'Ҏ', + 'ґ' => 'Ґ', + 'ғ' => 'Ғ', + 'ҕ' => 'Ҕ', + 'җ' => 'Җ', + 'ҙ' => 'Ҙ', + 'қ' => 'Қ', + 'ҝ' => 'Ҝ', + 'ҟ' => 'Ҟ', + 'ҡ' => 'Ҡ', + 'ң' => 'Ң', + 'ҥ' => 'Ҥ', + 'ҧ' => 'Ҧ', + 'ҩ' => 'Ҩ', + 'ҫ' => 'Ҫ', + 'ҭ' => 'Ҭ', + 'ү' => 'Ү', + 'ұ' => 'Ұ', + 'ҳ' => 'Ҳ', + 'ҵ' => 'Ҵ', + 'ҷ' => 'Ҷ', + 'ҹ' => 'Ҹ', + 'һ' => 'Һ', + 'ҽ' => 'Ҽ', + 'ҿ' => 'Ҿ', + 'ӂ' => 'Ӂ', + 'ӄ' => 'Ӄ', + 'ӆ' => 'Ӆ', + 'ӈ' => 'Ӈ', + 'ӊ' => 'Ӊ', + 'ӌ' => 'Ӌ', + 'ӎ' => 'Ӎ', + 'ӏ' => 'Ӏ', + 'ӑ' => 'Ӑ', + 'ӓ' => 'Ӓ', + 'ӕ' => 'Ӕ', + 'ӗ' => 'Ӗ', + 'ә' => 'Ә', + 'ӛ' => 'Ӛ', + 'ӝ' => 'Ӝ', + 'ӟ' => 'Ӟ', + 'ӡ' => 'Ӡ', + 'ӣ' => 'Ӣ', + 'ӥ' => 'Ӥ', + 'ӧ' => 'Ӧ', + 'ө' => 'Ө', + 'ӫ' => 'Ӫ', + 'ӭ' => 'Ӭ', + 'ӯ' => 'Ӯ', + 'ӱ' => 'Ӱ', + 'ӳ' => 'Ӳ', + 'ӵ' => 'Ӵ', + 'ӷ' => 'Ӷ', + 'ӹ' => 'Ӹ', + 'ӻ' => 'Ӻ', + 'ӽ' => 'Ӽ', + 'ӿ' => 'Ӿ', + 'ԁ' => 'Ԁ', + 'ԃ' => 'Ԃ', + 'ԅ' => 'Ԅ', + 'ԇ' => 'Ԇ', + 'ԉ' => 'Ԉ', + 'ԋ' => 'Ԋ', + 'ԍ' => 'Ԍ', + 'ԏ' => 'Ԏ', + 'ԑ' => 'Ԑ', + 'ԓ' => 'Ԓ', + 'ԕ' => 'Ԕ', + 'ԗ' => 'Ԗ', + 'ԙ' => 'Ԙ', + 'ԛ' => 'Ԛ', + 'ԝ' => 'Ԝ', + 'ԟ' => 'Ԟ', + 'ԡ' => 'Ԡ', + 'ԣ' => 'Ԣ', + 'ԥ' => 'Ԥ', + 'ԧ' => 'Ԧ', + 'ԩ' => 'Ԩ', + 'ԫ' => 'Ԫ', + 'ԭ' => 'Ԭ', + 'ԯ' => 'Ԯ', + 'ա' => 'Ա', + 'բ' => 'Բ', + 'գ' => 'Գ', + 'դ' => 'Դ', + 'ե' => 'Ե', + 'զ' => 'Զ', + 'է' => 'Է', + 'ը' => 'Ը', + 'թ' => 'Թ', + 'ժ' => 'Ժ', + 'ի' => 'Ի', + 'լ' => 'Լ', + 'խ' => 'Խ', + 'ծ' => 'Ծ', + 'կ' => 'Կ', + 'հ' => 'Հ', + 'ձ' => 'Ձ', + 'ղ' => 'Ղ', + 'ճ' => 'Ճ', + 'մ' => 'Մ', + 'յ' => 'Յ', + 'ն' => 'Ն', + 'շ' => 'Շ', + 'ո' => 'Ո', + 'չ' => 'Չ', + 'պ' => 'Պ', + 'ջ' => 'Ջ', + 'ռ' => 'Ռ', + 'ս' => 'Ս', + 'վ' => 'Վ', + 'տ' => 'Տ', + 'ր' => 'Ր', + 'ց' => 'Ց', + 'ւ' => 'Ւ', + 'փ' => 'Փ', + 'ք' => 'Ք', + 'օ' => 'Օ', + 'ֆ' => 'Ֆ', + 'ა' => 'Ა', + 'ბ' => 'Ბ', + 'გ' => 'Გ', + 'დ' => 'Დ', + 'ე' => 'Ე', + 'ვ' => 'Ვ', + 'ზ' => 'Ზ', + 'თ' => 'Თ', + 'ი' => 'Ი', + 'კ' => 'Კ', + 'ლ' => 'Ლ', + 'მ' => 'Მ', + 'ნ' => 'Ნ', + 'ო' => 'Ო', + 'პ' => 'Პ', + 'ჟ' => 'Ჟ', + 'რ' => 'Რ', + 'ს' => 'Ს', + 'ტ' => 'Ტ', + 'უ' => 'Უ', + 'ფ' => 'Ფ', + 'ქ' => 'Ქ', + 'ღ' => 'Ღ', + 'ყ' => 'Ყ', + 'შ' => 'Შ', + 'ჩ' => 'Ჩ', + 'ც' => 'Ც', + 'ძ' => 'Ძ', + 'წ' => 'Წ', + 'ჭ' => 'Ჭ', + 'ხ' => 'Ხ', + 'ჯ' => 'Ჯ', + 'ჰ' => 'Ჰ', + 'ჱ' => 'Ჱ', + 'ჲ' => 'Ჲ', + 'ჳ' => 'Ჳ', + 'ჴ' => 'Ჴ', + 'ჵ' => 'Ჵ', + 'ჶ' => 'Ჶ', + 'ჷ' => 'Ჷ', + 'ჸ' => 'Ჸ', + 'ჹ' => 'Ჹ', + 'ჺ' => 'Ჺ', + 'ჽ' => 'Ჽ', + 'ჾ' => 'Ჾ', + 'ჿ' => 'Ჿ', + 'ᏸ' => 'Ᏸ', + 'ᏹ' => 'Ᏹ', + 'ᏺ' => 'Ᏺ', + 'ᏻ' => 'Ᏻ', + 'ᏼ' => 'Ᏼ', + 'ᏽ' => 'Ᏽ', + 'ᲀ' => 'В', + 'ᲁ' => 'Д', + 'ᲂ' => 'О', + 'ᲃ' => 'С', + 'ᲄ' => 'Т', + 'ᲅ' => 'Т', + 'ᲆ' => 'Ъ', + 'ᲇ' => 'Ѣ', + 'ᲈ' => 'Ꙋ', + 'ᵹ' => 'Ᵹ', + 'ᵽ' => 'Ᵽ', + 'ᶎ' => 'Ᶎ', + 'ḁ' => 'Ḁ', + 'ḃ' => 'Ḃ', + 'ḅ' => 'Ḅ', + 'ḇ' => 'Ḇ', + 'ḉ' => 'Ḉ', + 'ḋ' => 'Ḋ', + 'ḍ' => 'Ḍ', + 'ḏ' => 'Ḏ', + 'ḑ' => 'Ḑ', + 'ḓ' => 'Ḓ', + 'ḕ' => 'Ḕ', + 'ḗ' => 'Ḗ', + 'ḙ' => 'Ḙ', + 'ḛ' => 'Ḛ', + 'ḝ' => 'Ḝ', + 'ḟ' => 'Ḟ', + 'ḡ' => 'Ḡ', + 'ḣ' => 'Ḣ', + 'ḥ' => 'Ḥ', + 'ḧ' => 'Ḧ', + 'ḩ' => 'Ḩ', + 'ḫ' => 'Ḫ', + 'ḭ' => 'Ḭ', + 'ḯ' => 'Ḯ', + 'ḱ' => 'Ḱ', + 'ḳ' => 'Ḳ', + 'ḵ' => 'Ḵ', + 'ḷ' => 'Ḷ', + 'ḹ' => 'Ḹ', + 'ḻ' => 'Ḻ', + 'ḽ' => 'Ḽ', + 'ḿ' => 'Ḿ', + 'ṁ' => 'Ṁ', + 'ṃ' => 'Ṃ', + 'ṅ' => 'Ṅ', + 'ṇ' => 'Ṇ', + 'ṉ' => 'Ṉ', + 'ṋ' => 'Ṋ', + 'ṍ' => 'Ṍ', + 'ṏ' => 'Ṏ', + 'ṑ' => 'Ṑ', + 'ṓ' => 'Ṓ', + 'ṕ' => 'Ṕ', + 'ṗ' => 'Ṗ', + 'ṙ' => 'Ṙ', + 'ṛ' => 'Ṛ', + 'ṝ' => 'Ṝ', + 'ṟ' => 'Ṟ', + 'ṡ' => 'Ṡ', + 'ṣ' => 'Ṣ', + 'ṥ' => 'Ṥ', + 'ṧ' => 'Ṧ', + 'ṩ' => 'Ṩ', + 'ṫ' => 'Ṫ', + 'ṭ' => 'Ṭ', + 'ṯ' => 'Ṯ', + 'ṱ' => 'Ṱ', + 'ṳ' => 'Ṳ', + 'ṵ' => 'Ṵ', + 'ṷ' => 'Ṷ', + 'ṹ' => 'Ṹ', + 'ṻ' => 'Ṻ', + 'ṽ' => 'Ṽ', + 'ṿ' => 'Ṿ', + 'ẁ' => 'Ẁ', + 'ẃ' => 'Ẃ', + 'ẅ' => 'Ẅ', + 'ẇ' => 'Ẇ', + 'ẉ' => 'Ẉ', + 'ẋ' => 'Ẋ', + 'ẍ' => 'Ẍ', + 'ẏ' => 'Ẏ', + 'ẑ' => 'Ẑ', + 'ẓ' => 'Ẓ', + 'ẕ' => 'Ẕ', + 'ẛ' => 'Ṡ', + 'ạ' => 'Ạ', + 'ả' => 'Ả', + 'ấ' => 'Ấ', + 'ầ' => 'Ầ', + 'ẩ' => 'Ẩ', + 'ẫ' => 'Ẫ', + 'ậ' => 'Ậ', + 'ắ' => 'Ắ', + 'ằ' => 'Ằ', + 'ẳ' => 'Ẳ', + 'ẵ' => 'Ẵ', + 'ặ' => 'Ặ', + 'ẹ' => 'Ẹ', + 'ẻ' => 'Ẻ', + 'ẽ' => 'Ẽ', + 'ế' => 'Ế', + 'ề' => 'Ề', + 'ể' => 'Ể', + 'ễ' => 'Ễ', + 'ệ' => 'Ệ', + 'ỉ' => 'Ỉ', + 'ị' => 'Ị', + 'ọ' => 'Ọ', + 'ỏ' => 'Ỏ', + 'ố' => 'Ố', + 'ồ' => 'Ồ', + 'ổ' => 'Ổ', + 'ỗ' => 'Ỗ', + 'ộ' => 'Ộ', + 'ớ' => 'Ớ', + 'ờ' => 'Ờ', + 'ở' => 'Ở', + 'ỡ' => 'Ỡ', + 'ợ' => 'Ợ', + 'ụ' => 'Ụ', + 'ủ' => 'Ủ', + 'ứ' => 'Ứ', + 'ừ' => 'Ừ', + 'ử' => 'Ử', + 'ữ' => 'Ữ', + 'ự' => 'Ự', + 'ỳ' => 'Ỳ', + 'ỵ' => 'Ỵ', + 'ỷ' => 'Ỷ', + 'ỹ' => 'Ỹ', + 'ỻ' => 'Ỻ', + 'ỽ' => 'Ỽ', + 'ỿ' => 'Ỿ', + 'ἀ' => 'Ἀ', + 'ἁ' => 'Ἁ', + 'ἂ' => 'Ἂ', + 'ἃ' => 'Ἃ', + 'ἄ' => 'Ἄ', + 'ἅ' => 'Ἅ', + 'ἆ' => 'Ἆ', + 'ἇ' => 'Ἇ', + 'ἐ' => 'Ἐ', + 'ἑ' => 'Ἑ', + 'ἒ' => 'Ἒ', + 'ἓ' => 'Ἓ', + 'ἔ' => 'Ἔ', + 'ἕ' => 'Ἕ', + 'ἠ' => 'Ἠ', + 'ἡ' => 'Ἡ', + 'ἢ' => 'Ἢ', + 'ἣ' => 'Ἣ', + 'ἤ' => 'Ἤ', + 'ἥ' => 'Ἥ', + 'ἦ' => 'Ἦ', + 'ἧ' => 'Ἧ', + 'ἰ' => 'Ἰ', + 'ἱ' => 'Ἱ', + 'ἲ' => 'Ἲ', + 'ἳ' => 'Ἳ', + 'ἴ' => 'Ἴ', + 'ἵ' => 'Ἵ', + 'ἶ' => 'Ἶ', + 'ἷ' => 'Ἷ', + 'ὀ' => 'Ὀ', + 'ὁ' => 'Ὁ', + 'ὂ' => 'Ὂ', + 'ὃ' => 'Ὃ', + 'ὄ' => 'Ὄ', + 'ὅ' => 'Ὅ', + 'ὑ' => 'Ὑ', + 'ὓ' => 'Ὓ', + 'ὕ' => 'Ὕ', + 'ὗ' => 'Ὗ', + 'ὠ' => 'Ὠ', + 'ὡ' => 'Ὡ', + 'ὢ' => 'Ὢ', + 'ὣ' => 'Ὣ', + 'ὤ' => 'Ὤ', + 'ὥ' => 'Ὥ', + 'ὦ' => 'Ὦ', + 'ὧ' => 'Ὧ', + 'ὰ' => 'Ὰ', + 'ά' => 'Ά', + 'ὲ' => 'Ὲ', + 'έ' => 'Έ', + 'ὴ' => 'Ὴ', + 'ή' => 'Ή', + 'ὶ' => 'Ὶ', + 'ί' => 'Ί', + 'ὸ' => 'Ὸ', + 'ό' => 'Ό', + 'ὺ' => 'Ὺ', + 'ύ' => 'Ύ', + 'ὼ' => 'Ὼ', + 'ώ' => 'Ώ', + 'ᾀ' => 'ἈΙ', + 'ᾁ' => 'ἉΙ', + 'ᾂ' => 'ἊΙ', + 'ᾃ' => 'ἋΙ', + 'ᾄ' => 'ἌΙ', + 'ᾅ' => 'ἍΙ', + 'ᾆ' => 'ἎΙ', + 'ᾇ' => 'ἏΙ', + 'ᾐ' => 'ἨΙ', + 'ᾑ' => 'ἩΙ', + 'ᾒ' => 'ἪΙ', + 'ᾓ' => 'ἫΙ', + 'ᾔ' => 'ἬΙ', + 'ᾕ' => 'ἭΙ', + 'ᾖ' => 'ἮΙ', + 'ᾗ' => 'ἯΙ', + 'ᾠ' => 'ὨΙ', + 'ᾡ' => 'ὩΙ', + 'ᾢ' => 'ὪΙ', + 'ᾣ' => 'ὫΙ', + 'ᾤ' => 'ὬΙ', + 'ᾥ' => 'ὭΙ', + 'ᾦ' => 'ὮΙ', + 'ᾧ' => 'ὯΙ', + 'ᾰ' => 'Ᾰ', + 'ᾱ' => 'Ᾱ', + 'ᾳ' => 'ΑΙ', + 'ι' => 'Ι', + 'ῃ' => 'ΗΙ', + 'ῐ' => 'Ῐ', + 'ῑ' => 'Ῑ', + 'ῠ' => 'Ῠ', + 'ῡ' => 'Ῡ', + 'ῥ' => 'Ῥ', + 'ῳ' => 'ΩΙ', + 'ⅎ' => 'Ⅎ', + 'ⅰ' => 'Ⅰ', + 'ⅱ' => 'Ⅱ', + 'ⅲ' => 'Ⅲ', + 'ⅳ' => 'Ⅳ', + 'ⅴ' => 'Ⅴ', + 'ⅵ' => 'Ⅵ', + 'ⅶ' => 'Ⅶ', + 'ⅷ' => 'Ⅷ', + 'ⅸ' => 'Ⅸ', + 'ⅹ' => 'Ⅹ', + 'ⅺ' => 'Ⅺ', + 'ⅻ' => 'Ⅻ', + 'ⅼ' => 'Ⅼ', + 'ⅽ' => 'Ⅽ', + 'ⅾ' => 'Ⅾ', + 'ⅿ' => 'Ⅿ', + 'ↄ' => 'Ↄ', + 'ⓐ' => 'Ⓐ', + 'ⓑ' => 'Ⓑ', + 'ⓒ' => 'Ⓒ', + 'ⓓ' => 'Ⓓ', + 'ⓔ' => 'Ⓔ', + 'ⓕ' => 'Ⓕ', + 'ⓖ' => 'Ⓖ', + 'ⓗ' => 'Ⓗ', + 'ⓘ' => 'Ⓘ', + 'ⓙ' => 'Ⓙ', + 'ⓚ' => 'Ⓚ', + 'ⓛ' => 'Ⓛ', + 'ⓜ' => 'Ⓜ', + 'ⓝ' => 'Ⓝ', + 'ⓞ' => 'Ⓞ', + 'ⓟ' => 'Ⓟ', + 'ⓠ' => 'Ⓠ', + 'ⓡ' => 'Ⓡ', + 'ⓢ' => 'Ⓢ', + 'ⓣ' => 'Ⓣ', + 'ⓤ' => 'Ⓤ', + 'ⓥ' => 'Ⓥ', + 'ⓦ' => 'Ⓦ', + 'ⓧ' => 'Ⓧ', + 'ⓨ' => 'Ⓨ', + 'ⓩ' => 'Ⓩ', + 'ⰰ' => 'Ⰰ', + 'ⰱ' => 'Ⰱ', + 'ⰲ' => 'Ⰲ', + 'ⰳ' => 'Ⰳ', + 'ⰴ' => 'Ⰴ', + 'ⰵ' => 'Ⰵ', + 'ⰶ' => 'Ⰶ', + 'ⰷ' => 'Ⰷ', + 'ⰸ' => 'Ⰸ', + 'ⰹ' => 'Ⰹ', + 'ⰺ' => 'Ⰺ', + 'ⰻ' => 'Ⰻ', + 'ⰼ' => 'Ⰼ', + 'ⰽ' => 'Ⰽ', + 'ⰾ' => 'Ⰾ', + 'ⰿ' => 'Ⰿ', + 'ⱀ' => 'Ⱀ', + 'ⱁ' => 'Ⱁ', + 'ⱂ' => 'Ⱂ', + 'ⱃ' => 'Ⱃ', + 'ⱄ' => 'Ⱄ', + 'ⱅ' => 'Ⱅ', + 'ⱆ' => 'Ⱆ', + 'ⱇ' => 'Ⱇ', + 'ⱈ' => 'Ⱈ', + 'ⱉ' => 'Ⱉ', + 'ⱊ' => 'Ⱊ', + 'ⱋ' => 'Ⱋ', + 'ⱌ' => 'Ⱌ', + 'ⱍ' => 'Ⱍ', + 'ⱎ' => 'Ⱎ', + 'ⱏ' => 'Ⱏ', + 'ⱐ' => 'Ⱐ', + 'ⱑ' => 'Ⱑ', + 'ⱒ' => 'Ⱒ', + 'ⱓ' => 'Ⱓ', + 'ⱔ' => 'Ⱔ', + 'ⱕ' => 'Ⱕ', + 'ⱖ' => 'Ⱖ', + 'ⱗ' => 'Ⱗ', + 'ⱘ' => 'Ⱘ', + 'ⱙ' => 'Ⱙ', + 'ⱚ' => 'Ⱚ', + 'ⱛ' => 'Ⱛ', + 'ⱜ' => 'Ⱜ', + 'ⱝ' => 'Ⱝ', + 'ⱞ' => 'Ⱞ', + 'ⱡ' => 'Ⱡ', + 'ⱥ' => 'Ⱥ', + 'ⱦ' => 'Ⱦ', + 'ⱨ' => 'Ⱨ', + 'ⱪ' => 'Ⱪ', + 'ⱬ' => 'Ⱬ', + 'ⱳ' => 'Ⱳ', + 'ⱶ' => 'Ⱶ', + 'ⲁ' => 'Ⲁ', + 'ⲃ' => 'Ⲃ', + 'ⲅ' => 'Ⲅ', + 'ⲇ' => 'Ⲇ', + 'ⲉ' => 'Ⲉ', + 'ⲋ' => 'Ⲋ', + 'ⲍ' => 'Ⲍ', + 'ⲏ' => 'Ⲏ', + 'ⲑ' => 'Ⲑ', + 'ⲓ' => 'Ⲓ', + 'ⲕ' => 'Ⲕ', + 'ⲗ' => 'Ⲗ', + 'ⲙ' => 'Ⲙ', + 'ⲛ' => 'Ⲛ', + 'ⲝ' => 'Ⲝ', + 'ⲟ' => 'Ⲟ', + 'ⲡ' => 'Ⲡ', + 'ⲣ' => 'Ⲣ', + 'ⲥ' => 'Ⲥ', + 'ⲧ' => 'Ⲧ', + 'ⲩ' => 'Ⲩ', + 'ⲫ' => 'Ⲫ', + 'ⲭ' => 'Ⲭ', + 'ⲯ' => 'Ⲯ', + 'ⲱ' => 'Ⲱ', + 'ⲳ' => 'Ⲳ', + 'ⲵ' => 'Ⲵ', + 'ⲷ' => 'Ⲷ', + 'ⲹ' => 'Ⲹ', + 'ⲻ' => 'Ⲻ', + 'ⲽ' => 'Ⲽ', + 'ⲿ' => 'Ⲿ', + 'ⳁ' => 'Ⳁ', + 'ⳃ' => 'Ⳃ', + 'ⳅ' => 'Ⳅ', + 'ⳇ' => 'Ⳇ', + 'ⳉ' => 'Ⳉ', + 'ⳋ' => 'Ⳋ', + 'ⳍ' => 'Ⳍ', + 'ⳏ' => 'Ⳏ', + 'ⳑ' => 'Ⳑ', + 'ⳓ' => 'Ⳓ', + 'ⳕ' => 'Ⳕ', + 'ⳗ' => 'Ⳗ', + 'ⳙ' => 'Ⳙ', + 'ⳛ' => 'Ⳛ', + 'ⳝ' => 'Ⳝ', + 'ⳟ' => 'Ⳟ', + 'ⳡ' => 'Ⳡ', + 'ⳣ' => 'Ⳣ', + 'ⳬ' => 'Ⳬ', + 'ⳮ' => 'Ⳮ', + 'ⳳ' => 'Ⳳ', + 'ⴀ' => 'Ⴀ', + 'ⴁ' => 'Ⴁ', + 'ⴂ' => 'Ⴂ', + 'ⴃ' => 'Ⴃ', + 'ⴄ' => 'Ⴄ', + 'ⴅ' => 'Ⴅ', + 'ⴆ' => 'Ⴆ', + 'ⴇ' => 'Ⴇ', + 'ⴈ' => 'Ⴈ', + 'ⴉ' => 'Ⴉ', + 'ⴊ' => 'Ⴊ', + 'ⴋ' => 'Ⴋ', + 'ⴌ' => 'Ⴌ', + 'ⴍ' => 'Ⴍ', + 'ⴎ' => 'Ⴎ', + 'ⴏ' => 'Ⴏ', + 'ⴐ' => 'Ⴐ', + 'ⴑ' => 'Ⴑ', + 'ⴒ' => 'Ⴒ', + 'ⴓ' => 'Ⴓ', + 'ⴔ' => 'Ⴔ', + 'ⴕ' => 'Ⴕ', + 'ⴖ' => 'Ⴖ', + 'ⴗ' => 'Ⴗ', + 'ⴘ' => 'Ⴘ', + 'ⴙ' => 'Ⴙ', + 'ⴚ' => 'Ⴚ', + 'ⴛ' => 'Ⴛ', + 'ⴜ' => 'Ⴜ', + 'ⴝ' => 'Ⴝ', + 'ⴞ' => 'Ⴞ', + 'ⴟ' => 'Ⴟ', + 'ⴠ' => 'Ⴠ', + 'ⴡ' => 'Ⴡ', + 'ⴢ' => 'Ⴢ', + 'ⴣ' => 'Ⴣ', + 'ⴤ' => 'Ⴤ', + 'ⴥ' => 'Ⴥ', + 'ⴧ' => 'Ⴧ', + 'ⴭ' => 'Ⴭ', + 'ꙁ' => 'Ꙁ', + 'ꙃ' => 'Ꙃ', + 'ꙅ' => 'Ꙅ', + 'ꙇ' => 'Ꙇ', + 'ꙉ' => 'Ꙉ', + 'ꙋ' => 'Ꙋ', + 'ꙍ' => 'Ꙍ', + 'ꙏ' => 'Ꙏ', + 'ꙑ' => 'Ꙑ', + 'ꙓ' => 'Ꙓ', + 'ꙕ' => 'Ꙕ', + 'ꙗ' => 'Ꙗ', + 'ꙙ' => 'Ꙙ', + 'ꙛ' => 'Ꙛ', + 'ꙝ' => 'Ꙝ', + 'ꙟ' => 'Ꙟ', + 'ꙡ' => 'Ꙡ', + 'ꙣ' => 'Ꙣ', + 'ꙥ' => 'Ꙥ', + 'ꙧ' => 'Ꙧ', + 'ꙩ' => 'Ꙩ', + 'ꙫ' => 'Ꙫ', + 'ꙭ' => 'Ꙭ', + 'ꚁ' => 'Ꚁ', + 'ꚃ' => 'Ꚃ', + 'ꚅ' => 'Ꚅ', + 'ꚇ' => 'Ꚇ', + 'ꚉ' => 'Ꚉ', + 'ꚋ' => 'Ꚋ', + 'ꚍ' => 'Ꚍ', + 'ꚏ' => 'Ꚏ', + 'ꚑ' => 'Ꚑ', + 'ꚓ' => 'Ꚓ', + 'ꚕ' => 'Ꚕ', + 'ꚗ' => 'Ꚗ', + 'ꚙ' => 'Ꚙ', + 'ꚛ' => 'Ꚛ', + 'ꜣ' => 'Ꜣ', + 'ꜥ' => 'Ꜥ', + 'ꜧ' => 'Ꜧ', + 'ꜩ' => 'Ꜩ', + 'ꜫ' => 'Ꜫ', + 'ꜭ' => 'Ꜭ', + 'ꜯ' => 'Ꜯ', + 'ꜳ' => 'Ꜳ', + 'ꜵ' => 'Ꜵ', + 'ꜷ' => 'Ꜷ', + 'ꜹ' => 'Ꜹ', + 'ꜻ' => 'Ꜻ', + 'ꜽ' => 'Ꜽ', + 'ꜿ' => 'Ꜿ', + 'ꝁ' => 'Ꝁ', + 'ꝃ' => 'Ꝃ', + 'ꝅ' => 'Ꝅ', + 'ꝇ' => 'Ꝇ', + 'ꝉ' => 'Ꝉ', + 'ꝋ' => 'Ꝋ', + 'ꝍ' => 'Ꝍ', + 'ꝏ' => 'Ꝏ', + 'ꝑ' => 'Ꝑ', + 'ꝓ' => 'Ꝓ', + 'ꝕ' => 'Ꝕ', + 'ꝗ' => 'Ꝗ', + 'ꝙ' => 'Ꝙ', + 'ꝛ' => 'Ꝛ', + 'ꝝ' => 'Ꝝ', + 'ꝟ' => 'Ꝟ', + 'ꝡ' => 'Ꝡ', + 'ꝣ' => 'Ꝣ', + 'ꝥ' => 'Ꝥ', + 'ꝧ' => 'Ꝧ', + 'ꝩ' => 'Ꝩ', + 'ꝫ' => 'Ꝫ', + 'ꝭ' => 'Ꝭ', + 'ꝯ' => 'Ꝯ', + 'ꝺ' => 'Ꝺ', + 'ꝼ' => 'Ꝼ', + 'ꝿ' => 'Ꝿ', + 'ꞁ' => 'Ꞁ', + 'ꞃ' => 'Ꞃ', + 'ꞅ' => 'Ꞅ', + 'ꞇ' => 'Ꞇ', + 'ꞌ' => 'Ꞌ', + 'ꞑ' => 'Ꞑ', + 'ꞓ' => 'Ꞓ', + 'ꞔ' => 'Ꞔ', + 'ꞗ' => 'Ꞗ', + 'ꞙ' => 'Ꞙ', + 'ꞛ' => 'Ꞛ', + 'ꞝ' => 'Ꞝ', + 'ꞟ' => 'Ꞟ', + 'ꞡ' => 'Ꞡ', + 'ꞣ' => 'Ꞣ', + 'ꞥ' => 'Ꞥ', + 'ꞧ' => 'Ꞧ', + 'ꞩ' => 'Ꞩ', + 'ꞵ' => 'Ꞵ', + 'ꞷ' => 'Ꞷ', + 'ꞹ' => 'Ꞹ', + 'ꞻ' => 'Ꞻ', + 'ꞽ' => 'Ꞽ', + 'ꞿ' => 'Ꞿ', + 'ꟃ' => 'Ꟃ', + 'ꟈ' => 'Ꟈ', + 'ꟊ' => 'Ꟊ', + 'ꟶ' => 'Ꟶ', + 'ꭓ' => 'Ꭓ', + 'ꭰ' => 'Ꭰ', + 'ꭱ' => 'Ꭱ', + 'ꭲ' => 'Ꭲ', + 'ꭳ' => 'Ꭳ', + 'ꭴ' => 'Ꭴ', + 'ꭵ' => 'Ꭵ', + 'ꭶ' => 'Ꭶ', + 'ꭷ' => 'Ꭷ', + 'ꭸ' => 'Ꭸ', + 'ꭹ' => 'Ꭹ', + 'ꭺ' => 'Ꭺ', + 'ꭻ' => 'Ꭻ', + 'ꭼ' => 'Ꭼ', + 'ꭽ' => 'Ꭽ', + 'ꭾ' => 'Ꭾ', + 'ꭿ' => 'Ꭿ', + 'ꮀ' => 'Ꮀ', + 'ꮁ' => 'Ꮁ', + 'ꮂ' => 'Ꮂ', + 'ꮃ' => 'Ꮃ', + 'ꮄ' => 'Ꮄ', + 'ꮅ' => 'Ꮅ', + 'ꮆ' => 'Ꮆ', + 'ꮇ' => 'Ꮇ', + 'ꮈ' => 'Ꮈ', + 'ꮉ' => 'Ꮉ', + 'ꮊ' => 'Ꮊ', + 'ꮋ' => 'Ꮋ', + 'ꮌ' => 'Ꮌ', + 'ꮍ' => 'Ꮍ', + 'ꮎ' => 'Ꮎ', + 'ꮏ' => 'Ꮏ', + 'ꮐ' => 'Ꮐ', + 'ꮑ' => 'Ꮑ', + 'ꮒ' => 'Ꮒ', + 'ꮓ' => 'Ꮓ', + 'ꮔ' => 'Ꮔ', + 'ꮕ' => 'Ꮕ', + 'ꮖ' => 'Ꮖ', + 'ꮗ' => 'Ꮗ', + 'ꮘ' => 'Ꮘ', + 'ꮙ' => 'Ꮙ', + 'ꮚ' => 'Ꮚ', + 'ꮛ' => 'Ꮛ', + 'ꮜ' => 'Ꮜ', + 'ꮝ' => 'Ꮝ', + 'ꮞ' => 'Ꮞ', + 'ꮟ' => 'Ꮟ', + 'ꮠ' => 'Ꮠ', + 'ꮡ' => 'Ꮡ', + 'ꮢ' => 'Ꮢ', + 'ꮣ' => 'Ꮣ', + 'ꮤ' => 'Ꮤ', + 'ꮥ' => 'Ꮥ', + 'ꮦ' => 'Ꮦ', + 'ꮧ' => 'Ꮧ', + 'ꮨ' => 'Ꮨ', + 'ꮩ' => 'Ꮩ', + 'ꮪ' => 'Ꮪ', + 'ꮫ' => 'Ꮫ', + 'ꮬ' => 'Ꮬ', + 'ꮭ' => 'Ꮭ', + 'ꮮ' => 'Ꮮ', + 'ꮯ' => 'Ꮯ', + 'ꮰ' => 'Ꮰ', + 'ꮱ' => 'Ꮱ', + 'ꮲ' => 'Ꮲ', + 'ꮳ' => 'Ꮳ', + 'ꮴ' => 'Ꮴ', + 'ꮵ' => 'Ꮵ', + 'ꮶ' => 'Ꮶ', + 'ꮷ' => 'Ꮷ', + 'ꮸ' => 'Ꮸ', + 'ꮹ' => 'Ꮹ', + 'ꮺ' => 'Ꮺ', + 'ꮻ' => 'Ꮻ', + 'ꮼ' => 'Ꮼ', + 'ꮽ' => 'Ꮽ', + 'ꮾ' => 'Ꮾ', + 'ꮿ' => 'Ꮿ', + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', + 'f' => 'F', + 'g' => 'G', + 'h' => 'H', + 'i' => 'I', + 'j' => 'J', + 'k' => 'K', + 'l' => 'L', + 'm' => 'M', + 'n' => 'N', + 'o' => 'O', + 'p' => 'P', + 'q' => 'Q', + 'r' => 'R', + 's' => 'S', + 't' => 'T', + 'u' => 'U', + 'v' => 'V', + 'w' => 'W', + 'x' => 'X', + 'y' => 'Y', + 'z' => 'Z', + '𐐨' => '𐐀', + '𐐩' => '𐐁', + '𐐪' => '𐐂', + '𐐫' => '𐐃', + '𐐬' => '𐐄', + '𐐭' => '𐐅', + '𐐮' => '𐐆', + '𐐯' => '𐐇', + '𐐰' => '𐐈', + '𐐱' => '𐐉', + '𐐲' => '𐐊', + '𐐳' => '𐐋', + '𐐴' => '𐐌', + '𐐵' => '𐐍', + '𐐶' => '𐐎', + '𐐷' => '𐐏', + '𐐸' => '𐐐', + '𐐹' => '𐐑', + '𐐺' => '𐐒', + '𐐻' => '𐐓', + '𐐼' => '𐐔', + '𐐽' => '𐐕', + '𐐾' => '𐐖', + '𐐿' => '𐐗', + '𐑀' => '𐐘', + '𐑁' => '𐐙', + '𐑂' => '𐐚', + '𐑃' => '𐐛', + '𐑄' => '𐐜', + '𐑅' => '𐐝', + '𐑆' => '𐐞', + '𐑇' => '𐐟', + '𐑈' => '𐐠', + '𐑉' => '𐐡', + '𐑊' => '𐐢', + '𐑋' => '𐐣', + '𐑌' => '𐐤', + '𐑍' => '𐐥', + '𐑎' => '𐐦', + '𐑏' => '𐐧', + '𐓘' => '𐒰', + '𐓙' => '𐒱', + '𐓚' => '𐒲', + '𐓛' => '𐒳', + '𐓜' => '𐒴', + '𐓝' => '𐒵', + '𐓞' => '𐒶', + '𐓟' => '𐒷', + '𐓠' => '𐒸', + '𐓡' => '𐒹', + '𐓢' => '𐒺', + '𐓣' => '𐒻', + '𐓤' => '𐒼', + '𐓥' => '𐒽', + '𐓦' => '𐒾', + '𐓧' => '𐒿', + '𐓨' => '𐓀', + '𐓩' => '𐓁', + '𐓪' => '𐓂', + '𐓫' => '𐓃', + '𐓬' => '𐓄', + '𐓭' => '𐓅', + '𐓮' => '𐓆', + '𐓯' => '𐓇', + '𐓰' => '𐓈', + '𐓱' => '𐓉', + '𐓲' => '𐓊', + '𐓳' => '𐓋', + '𐓴' => '𐓌', + '𐓵' => '𐓍', + '𐓶' => '𐓎', + '𐓷' => '𐓏', + '𐓸' => '𐓐', + '𐓹' => '𐓑', + '𐓺' => '𐓒', + '𐓻' => '𐓓', + '𐳀' => '𐲀', + '𐳁' => '𐲁', + '𐳂' => '𐲂', + '𐳃' => '𐲃', + '𐳄' => '𐲄', + '𐳅' => '𐲅', + '𐳆' => '𐲆', + '𐳇' => '𐲇', + '𐳈' => '𐲈', + '𐳉' => '𐲉', + '𐳊' => '𐲊', + '𐳋' => '𐲋', + '𐳌' => '𐲌', + '𐳍' => '𐲍', + '𐳎' => '𐲎', + '𐳏' => '𐲏', + '𐳐' => '𐲐', + '𐳑' => '𐲑', + '𐳒' => '𐲒', + '𐳓' => '𐲓', + '𐳔' => '𐲔', + '𐳕' => '𐲕', + '𐳖' => '𐲖', + '𐳗' => '𐲗', + '𐳘' => '𐲘', + '𐳙' => '𐲙', + '𐳚' => '𐲚', + '𐳛' => '𐲛', + '𐳜' => '𐲜', + '𐳝' => '𐲝', + '𐳞' => '𐲞', + '𐳟' => '𐲟', + '𐳠' => '𐲠', + '𐳡' => '𐲡', + '𐳢' => '𐲢', + '𐳣' => '𐲣', + '𐳤' => '𐲤', + '𐳥' => '𐲥', + '𐳦' => '𐲦', + '𐳧' => '𐲧', + '𐳨' => '𐲨', + '𐳩' => '𐲩', + '𐳪' => '𐲪', + '𐳫' => '𐲫', + '𐳬' => '𐲬', + '𐳭' => '𐲭', + '𐳮' => '𐲮', + '𐳯' => '𐲯', + '𐳰' => '𐲰', + '𐳱' => '𐲱', + '𐳲' => '𐲲', + '𑣀' => '𑢠', + '𑣁' => '𑢡', + '𑣂' => '𑢢', + '𑣃' => '𑢣', + '𑣄' => '𑢤', + '𑣅' => '𑢥', + '𑣆' => '𑢦', + '𑣇' => '𑢧', + '𑣈' => '𑢨', + '𑣉' => '𑢩', + '𑣊' => '𑢪', + '𑣋' => '𑢫', + '𑣌' => '𑢬', + '𑣍' => '𑢭', + '𑣎' => '𑢮', + '𑣏' => '𑢯', + '𑣐' => '𑢰', + '𑣑' => '𑢱', + '𑣒' => '𑢲', + '𑣓' => '𑢳', + '𑣔' => '𑢴', + '𑣕' => '𑢵', + '𑣖' => '𑢶', + '𑣗' => '𑢷', + '𑣘' => '𑢸', + '𑣙' => '𑢹', + '𑣚' => '𑢺', + '𑣛' => '𑢻', + '𑣜' => '𑢼', + '𑣝' => '𑢽', + '𑣞' => '𑢾', + '𑣟' => '𑢿', + '𖹠' => '𖹀', + '𖹡' => '𖹁', + '𖹢' => '𖹂', + '𖹣' => '𖹃', + '𖹤' => '𖹄', + '𖹥' => '𖹅', + '𖹦' => '𖹆', + '𖹧' => '𖹇', + '𖹨' => '𖹈', + '𖹩' => '𖹉', + '𖹪' => '𖹊', + '𖹫' => '𖹋', + '𖹬' => '𖹌', + '𖹭' => '𖹍', + '𖹮' => '𖹎', + '𖹯' => '𖹏', + '𖹰' => '𖹐', + '𖹱' => '𖹑', + '𖹲' => '𖹒', + '𖹳' => '𖹓', + '𖹴' => '𖹔', + '𖹵' => '𖹕', + '𖹶' => '𖹖', + '𖹷' => '𖹗', + '𖹸' => '𖹘', + '𖹹' => '𖹙', + '𖹺' => '𖹚', + '𖹻' => '𖹛', + '𖹼' => '𖹜', + '𖹽' => '𖹝', + '𖹾' => '𖹞', + '𖹿' => '𖹟', + '𞤢' => '𞤀', + '𞤣' => '𞤁', + '𞤤' => '𞤂', + '𞤥' => '𞤃', + '𞤦' => '𞤄', + '𞤧' => '𞤅', + '𞤨' => '𞤆', + '𞤩' => '𞤇', + '𞤪' => '𞤈', + '𞤫' => '𞤉', + '𞤬' => '𞤊', + '𞤭' => '𞤋', + '𞤮' => '𞤌', + '𞤯' => '𞤍', + '𞤰' => '𞤎', + '𞤱' => '𞤏', + '𞤲' => '𞤐', + '𞤳' => '𞤑', + '𞤴' => '𞤒', + '𞤵' => '𞤓', + '𞤶' => '𞤔', + '𞤷' => '𞤕', + '𞤸' => '𞤖', + '𞤹' => '𞤗', + '𞤺' => '𞤘', + '𞤻' => '𞤙', + '𞤼' => '𞤚', + '𞤽' => '𞤛', + '𞤾' => '𞤜', + '𞤿' => '𞤝', + '𞥀' => '𞤞', + '𞥁' => '𞤟', + '𞥂' => '𞤠', + '𞥃' => '𞤡', + 'ß' => 'SS', + 'ff' => 'FF', + 'fi' => 'FI', + 'fl' => 'FL', + 'ffi' => 'FFI', + 'ffl' => 'FFL', + 'ſt' => 'ST', + 'st' => 'ST', + 'և' => 'ԵՒ', + 'ﬓ' => 'ՄՆ', + 'ﬔ' => 'ՄԵ', + 'ﬕ' => 'ՄԻ', + 'ﬖ' => 'ՎՆ', + 'ﬗ' => 'ՄԽ', + 'ʼn' => 'ʼN', + 'ΐ' => 'Ϊ́', + 'ΰ' => 'Ϋ́', + 'ǰ' => 'J̌', + 'ẖ' => 'H̱', + 'ẗ' => 'T̈', + 'ẘ' => 'W̊', + 'ẙ' => 'Y̊', + 'ẚ' => 'Aʾ', + 'ὐ' => 'Υ̓', + 'ὒ' => 'Υ̓̀', + 'ὔ' => 'Υ̓́', + 'ὖ' => 'Υ̓͂', + 'ᾶ' => 'Α͂', + 'ῆ' => 'Η͂', + 'ῒ' => 'Ϊ̀', + 'ΐ' => 'Ϊ́', + 'ῖ' => 'Ι͂', + 'ῗ' => 'Ϊ͂', + 'ῢ' => 'Ϋ̀', + 'ΰ' => 'Ϋ́', + 'ῤ' => 'Ρ̓', + 'ῦ' => 'Υ͂', + 'ῧ' => 'Ϋ͂', + 'ῶ' => 'Ω͂', + 'ᾈ' => 'ἈΙ', + 'ᾉ' => 'ἉΙ', + 'ᾊ' => 'ἊΙ', + 'ᾋ' => 'ἋΙ', + 'ᾌ' => 'ἌΙ', + 'ᾍ' => 'ἍΙ', + 'ᾎ' => 'ἎΙ', + 'ᾏ' => 'ἏΙ', + 'ᾘ' => 'ἨΙ', + 'ᾙ' => 'ἩΙ', + 'ᾚ' => 'ἪΙ', + 'ᾛ' => 'ἫΙ', + 'ᾜ' => 'ἬΙ', + 'ᾝ' => 'ἭΙ', + 'ᾞ' => 'ἮΙ', + 'ᾟ' => 'ἯΙ', + 'ᾨ' => 'ὨΙ', + 'ᾩ' => 'ὩΙ', + 'ᾪ' => 'ὪΙ', + 'ᾫ' => 'ὫΙ', + 'ᾬ' => 'ὬΙ', + 'ᾭ' => 'ὭΙ', + 'ᾮ' => 'ὮΙ', + 'ᾯ' => 'ὯΙ', + 'ᾼ' => 'ΑΙ', + 'ῌ' => 'ΗΙ', + 'ῼ' => 'ΩΙ', + 'ᾲ' => 'ᾺΙ', + 'ᾴ' => 'ΆΙ', + 'ῂ' => 'ῊΙ', + 'ῄ' => 'ΉΙ', + 'ῲ' => 'ῺΙ', + 'ῴ' => 'ΏΙ', + 'ᾷ' => 'Α͂Ι', + 'ῇ' => 'Η͂Ι', + 'ῷ' => 'Ω͂Ι', +); diff --git a/lib/symfony/polyfill-mbstring/bootstrap.php b/lib/symfony/polyfill-mbstring/bootstrap.php new file mode 100644 index 00000000..1fedd1f7 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/bootstrap.php @@ -0,0 +1,147 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (\PHP_VERSION_ID >= 80000) { + return require __DIR__.'/bootstrap80.php'; +} + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language($language = null) { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/lib/symfony/polyfill-mbstring/bootstrap80.php b/lib/symfony/polyfill-mbstring/bootstrap80.php new file mode 100644 index 00000000..82f5ac4d --- /dev/null +++ b/lib/symfony/polyfill-mbstring/bootstrap80.php @@ -0,0 +1,143 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Mbstring as p; + +if (!function_exists('mb_convert_encoding')) { + function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); } +} +if (!function_exists('mb_decode_mimeheader')) { + function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); } +} +if (!function_exists('mb_encode_mimeheader')) { + function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); } +} +if (!function_exists('mb_decode_numericentity')) { + function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); } +} +if (!function_exists('mb_encode_numericentity')) { + function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); } +} +if (!function_exists('mb_convert_case')) { + function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); } +} +if (!function_exists('mb_internal_encoding')) { + function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); } +} +if (!function_exists('mb_language')) { + function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); } +} +if (!function_exists('mb_list_encodings')) { + function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); } +} +if (!function_exists('mb_encoding_aliases')) { + function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); } +} +if (!function_exists('mb_check_encoding')) { + function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); } +} +if (!function_exists('mb_detect_encoding')) { + function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); } +} +if (!function_exists('mb_detect_order')) { + function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); } +} +if (!function_exists('mb_parse_str')) { + function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; } +} +if (!function_exists('mb_strlen')) { + function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); } +} +if (!function_exists('mb_strpos')) { + function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strtolower')) { + function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); } +} +if (!function_exists('mb_strtoupper')) { + function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); } +} +if (!function_exists('mb_substitute_character')) { + function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); } +} +if (!function_exists('mb_substr')) { + function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); } +} +if (!function_exists('mb_stripos')) { + function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_stristr')) { + function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrchr')) { + function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strrichr')) { + function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_strripos')) { + function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strrpos')) { + function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); } +} +if (!function_exists('mb_strstr')) { + function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); } +} +if (!function_exists('mb_get_info')) { + function mb_get_info(?string $type = 'all'): array|string|int|false { return p\Mbstring::mb_get_info((string) $type); } +} +if (!function_exists('mb_http_output')) { + function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); } +} +if (!function_exists('mb_strwidth')) { + function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); } +} +if (!function_exists('mb_substr_count')) { + function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); } +} +if (!function_exists('mb_output_handler')) { + function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); } +} +if (!function_exists('mb_http_input')) { + function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); } +} + +if (!function_exists('mb_convert_variables')) { + function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); } +} + +if (!function_exists('mb_ord')) { + function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); } +} +if (!function_exists('mb_chr')) { + function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); } +} +if (!function_exists('mb_str_split')) { + function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); } +} + +if (extension_loaded('mbstring')) { + return; +} + +if (!defined('MB_CASE_UPPER')) { + define('MB_CASE_UPPER', 0); +} +if (!defined('MB_CASE_LOWER')) { + define('MB_CASE_LOWER', 1); +} +if (!defined('MB_CASE_TITLE')) { + define('MB_CASE_TITLE', 2); +} diff --git a/lib/symfony/polyfill-mbstring/composer.json b/lib/symfony/polyfill-mbstring/composer.json new file mode 100644 index 00000000..9cd2e924 --- /dev/null +++ b/lib/symfony/polyfill-mbstring/composer.json @@ -0,0 +1,41 @@ +{ + "name": "symfony/polyfill-mbstring", + "type": "library", + "description": "Symfony polyfill for the Mbstring extension", + "keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-main": "1.26-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/lib/utility.inc.php b/lib/utility.inc.php index 84f35a7c..95d3f01d 100755 --- a/lib/utility.inc.php +++ b/lib/utility.inc.php @@ -1,667 +1,670 @@ -'."\n"; - echo 'alert("'.$str_message.'")'."\n"; - echo ''."\n"; - } - - /** - * Static Method to send out toastr notification - * - * @param string $type [info, success, warning, error] - * @param string $str_message - * @return void - */ - public static function jsToastr($title, $str_message, $type = 'info') - { - if (!$str_message) { - return; - } - - $options = [ - 'closeButton' => true, - 'debug' => false, - 'newestOnTop' => false, - 'progressBar' => false, - 'positionClass' => 'toast-top-right', - 'preventDuplicates' => false, - 'onclick' => null, - 'showDuration' => 300, - 'hideDuration' => 1000, - 'timeOut' => 5000, - 'extendedTimeOut' => 1000, - 'showEasing' => 'swing', - 'hideEasing' => 'linear', - 'showMethod' => 'fadeIn', - 'hideMethod' => 'fadeOut' - ]; - - // replace newline with javascripts newline - $str_message = str_replace("\n", '\n', addslashes($str_message)); - echo ''."\n"; - } - - - /** - * Static Method to create random string - * - * @param int $int_num_string: number of randowm string to created - * @return void - */ - public static function createRandomString($int_num_string = 32) - { - $_random = ''; - $_salt = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $_saltlength = strlen($_salt); - for ($r = 0; $r < $int_num_string; $r++) { - $_random .= $_salt[rand(0, $_saltlength - 1)]; - } - - return $_random; - } - - - /** - * Static Method to load application settings from database - * - * @param object $obj_db - * @return void - */ - public static function loadSettings($obj_db) - { - global $sysconf; - $_setting_query = $obj_db->query('SELECT * FROM setting'); - if (!$obj_db->errno) { - while ($_setting_data = $_setting_query->fetch_assoc()) { - $_value = @unserialize($_setting_data['setting_value']); - if (is_array($_value)) { - foreach ($_value as $_idx=>$_curr_value) { - if (is_array($_curr_value)) { - $sysconf[$_setting_data['setting_name']][$_idx] = $_curr_value; - } else { - $sysconf[$_setting_data['setting_name']][$_idx] = stripslashes($_curr_value); - } - } - } else { - $sysconf[$_setting_data['setting_name']] = stripslashes($_value); - } - } - } - } - - - /** - * Static Method to check privileges of application module form current user - * - * @param string $str_module_name - * @param string $str_privilege_type - * @return boolean - */ - public static function havePrivilege($str_module_name, $str_privilege_type = 'r') - { - global $sysconf; - // checking checksum - if ($sysconf['load_balanced_env']) { - $server_addr = $_SERVER['REMOTE_ADDR']; - } else { - $server_addr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : (isset($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR'] : gethostbyname($_SERVER['SERVER_NAME'])); - } - - - $_checksum = defined('UCS_BASE_DIR')?md5($server_addr.UCS_BASE_DIR.'admin'):md5($server_addr.SB.'admin'); - if ($_SESSION['checksum'] != $_checksum) { - return false; - } - // check privilege type - if (!in_array($str_privilege_type, array('r', 'w'))) { - return false; - } - if (isset($_SESSION['priv'][$str_module_name][$str_privilege_type]) AND $_SESSION['priv'][$str_module_name][$str_privilege_type]) { - return true; - } - return false; - } - - - /** - * Static Method to write application activities logs - * - * @param object $obj_db - * @param string $str_log_type - * @param string $str_value_id - * @param string $str_location - * @param string $str_log_msg - * @return void - */ - public static function writeLogs($obj_db, $str_log_type, $str_value_id, $str_location, $str_log_msg, $str_log_submod=NULL, $str_log_action=NULL) - { - if (!$obj_db->error) { - // log table - $_log_date = date('Y-m-d H:i:s'); - $_log_table = 'system_log'; - // filter input - $str_log_type = $obj_db->escape_string(trim($str_log_type)); - $str_value_id = $obj_db->escape_string(trim($str_value_id)); - $str_location = $obj_db->escape_string(trim($str_location)); - $str_log_msg = $obj_db->escape_string(trim($str_log_msg)); - $str_log_submod = $obj_db->escape_string(trim($str_log_submod)); - $str_log_action = $obj_db->escape_string(trim($str_log_action)); - // insert log data to database - @$obj_db->query('INSERT INTO '.$_log_table.' - VALUES (NULL, \''.$str_log_type.'\', \''.$str_value_id.'\', \''.$str_location.'\','. - ' \''.$str_log_submod.'\''. - ', \''.$str_log_action.'\''. - ', \''.$str_log_msg.'\', \''.$_log_date.'\')'); - } - } - - - /** - * Static Method to get an ID of database table record - * - * @param object $obj_db - * @param string $str_table_name - * @param string $str_id_field - * @param string $str_value_field - * @param string $str_value - * @param array $arr_cache - * @return mixed - */ - public static function getID($obj_db, $str_table_name, $str_id_field, $str_value_field, $str_value, &$arr_cache = false) - { - $str_value = trim($str_value); - if ($arr_cache) { - if (isset($arr_cache[$str_value])) { - return $arr_cache[$str_value]; - } - } - if (!$obj_db->error) { - $id_q = $obj_db->query('SELECT '.$str_id_field.' FROM '.$str_table_name.' WHERE '.$str_value_field.'=\''.$obj_db->escape_string($str_value).'\''); - if ($id_q->num_rows > 0) { - $id_d = $id_q->fetch_row(); - unset($id_q); - // cache - if ($arr_cache) { - $arr_cache[$str_value] = $id_d[0]; - } - return $id_d[0]; - } else { - $_curr_date = date('Y-m-d'); - // if not found then we insert it as new value - $obj_db->query('INSERT IGNORE INTO '.$str_table_name.' ('.$str_value_field.', input_date, last_update) - VALUES (\''.$obj_db->escape_string($str_value).'\', \''.$_curr_date.'\', \''.$_curr_date.'\')'); - if (!$obj_db->error) { - // cache - if ($arr_cache) { - $arr_cache[$str_value] = $obj_db->insert_id; - } - return $obj_db->insert_id; - } - } - } - } - - - /** - * Static method to detect mobile browser - * - * @return boolean - * this script is taken from http://detectmobilebrowsers.com/ - **/ - public static function isMobileBrowser() - { - $_is_mobile_browser = false; - - if(preg_match('/android.+mobile|avantgo|bada\/|blackberry| - blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)| - iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i| - palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian| - treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)| - xda|xiino/i', - @$_SERVER['HTTP_USER_AGENT']) - || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s| - a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)| - amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw| - au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)| - br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc| - cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob| - do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8| - ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo| - go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)| - hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)| - i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno| - ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt | - kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])| - libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr| - me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do| - t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]| - n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)| - nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg| - pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox| - psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600| - raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)| - sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)| - sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)| - so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)| - ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)| - ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri| - vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc| - vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit| - wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i', - substr(@$_SERVER['HTTP_USER_AGENT'],0,4))) - $_is_mobile_browser = true; - - return $_is_mobile_browser; - } - - - /** - * Static method to check if member already logged in or not - * - * @return boolean - **/ - public static function isMemberLogin() - { - $_logged_in = false; - $_logged_in = isset($_SESSION['mid']) && isset($_SESSION['m_name']); - return $_logged_in; - } - - - /** - * Static method to filter data - * - * @param mixed $mix_input: input data - * @param string $str_input_type: input type - * @param boolean $bool_trim: are input string trimmed - * - * @return mixed - **/ - public static function filterData($mix_input, $str_input_type = 'get', $bool_escape_sql = true, $bool_trim = true, $bool_strip_html = false) { - global $dbs; - - if (extension_loaded('filter')) { - if ($str_input_type == 'var') { - $mix_input = filter_var($mix_input, FILTER_SANITIZE_STRING); - } else if ($str_input_type == 'post') { - $mix_input = filter_input(INPUT_POST, $mix_input); - } else if ($str_input_type == 'cookie') { - $mix_input = filter_input(INPUT_COOKIE, $mix_input); - } else if ($str_input_type == 'session') { - $mix_input = filter_input(INPUT_SESSION, $mix_input); - } else { - $mix_input = filter_input(INPUT_GET, $mix_input); - } - } else { - if ($str_input_type == 'get') { - $mix_input = $_GET[$mix_input]; - } else if ($str_input_type == 'post') { - $mix_input = $_POST[$mix_input]; - } else if ($str_input_type == 'cookie') { - $mix_input = $_COOKIE[$mix_input]; - } else if ($str_input_type == 'session') { - $mix_input = $_SESSION[$mix_input]; - } - } - - // trim whitespace on string - if ($bool_trim) { $mix_input = trim($mix_input); } - // strip html - if ($bool_strip_html) { $mix_input = strip_tags($mix_input); } - // escape SQL string - if ($bool_escape_sql) { $mix_input = $dbs->escape_string($mix_input); } - - return $mix_input; - } - - - /** - * Static method to convert XML entities - * Code taken and modified from: - * Matt Robinson at http://inanimatt.com/php-convert-entities.html - * - * @param string $str_xml_data: string of xml data to check - * - * @return string - **/ - public static function convertXMLentities($str_xml_data) { - static $_ent_table = array('quot' => '"', - 'amp' => '&', - 'lt' => '<', - 'gt' => '>', - 'OElig' => 'Œ', - 'oelig' => 'œ', - 'Scaron' => 'Š', - 'scaron' => 'š', - 'Yuml' => 'Ÿ', - 'circ' => 'ˆ', - 'tilde' => '˜', - 'ensp' => ' ', - 'emsp' => ' ', - 'thinsp' => ' ', - 'zwnj' => '‌', - 'zwj' => '‍', - 'lrm' => '‎', - 'rlm' => '‏', - 'ndash' => '–', - 'mdash' => '—', - 'lsquo' => '‘', - 'rsquo' => '’', - 'sbquo' => '‚', - 'ldquo' => '“', - 'rdquo' => '”', - 'bdquo' => '„', - 'dagger' => '†', - 'Dagger' => '‡', - 'permil' => '‰', - 'lsaquo' => '‹', - 'rsaquo' => '›', - 'euro' => '€', - 'fnof' => 'ƒ', - 'Alpha' => 'Α', - 'Beta' => 'Β', - 'Gamma' => 'Γ', - 'Delta' => 'Δ', - 'Epsilon' => 'Ε', - 'Zeta' => 'Ζ', - 'Eta' => 'Η', - 'Theta' => 'Θ', - 'Iota' => 'Ι', - 'Kappa' => 'Κ', - 'Lambda' => 'Λ', - 'Mu' => 'Μ', - 'Nu' => 'Ν', - 'Xi' => 'Ξ', - 'Omicron' => 'Ο', - 'Pi' => 'Π', - 'Rho' => 'Ρ', - 'Sigma' => 'Σ', - 'Tau' => 'Τ', - 'Upsilon' => 'Υ', - 'Phi' => 'Φ', - 'Chi' => 'Χ', - 'Psi' => 'Ψ', - 'Omega' => 'Ω', - 'alpha' => 'α', - 'beta' => 'β', - 'gamma' => 'γ', - 'delta' => 'δ', - 'epsilon' => 'ε', - 'zeta' => 'ζ', - 'eta' => 'η', - 'theta' => 'θ', - 'iota' => 'ι', - 'kappa' => 'κ', - 'lambda' => 'λ', - 'mu' => 'μ', - 'nu' => 'ν', - 'xi' => 'ξ', - 'omicron' => 'ο', - 'pi' => 'π', - 'rho' => 'ρ', - 'sigmaf' => 'ς', - 'sigma' => 'σ', - 'tau' => 'τ', - 'upsilon' => 'υ', - 'phi' => 'φ', - 'chi' => 'χ', - 'psi' => 'ψ', - 'omega' => 'ω', - 'thetasym' => 'ϑ', - 'upsih' => 'ϒ', - 'piv' => 'ϖ', - 'bull' => '•', - 'hellip' => '…', - 'prime' => '′', - 'Prime' => '″', - 'oline' => '‾', - 'frasl' => '⁄', - 'weierp' => '℘', - 'image' => 'ℑ', - 'real' => 'ℜ', - 'trade' => '™', - 'alefsym' => 'ℵ', - 'larr' => '←', - 'uarr' => '↑', - 'rarr' => '→', - 'darr' => '↓', - 'harr' => '↔', - 'crarr' => '↵', - 'lArr' => '⇐', - 'uArr' => '⇑', - 'rArr' => '⇒', - 'dArr' => '⇓', - 'hArr' => '⇔', - 'forall' => '∀', - 'part' => '∂', - 'exist' => '∃', - 'empty' => '∅', - 'nabla' => '∇', - 'isin' => '∈', - 'notin' => '∉', - 'ni' => '∋', - 'prod' => '∏', - 'sum' => '∑', - 'minus' => '−', - 'lowast' => '∗', - 'radic' => '√', - 'prop' => '∝', - 'infin' => '∞', - 'ang' => '∠', - 'and' => '∧', - 'or' => '∨', - 'cap' => '∩', - 'cup' => '∪', - 'int' => '∫', - 'there4' => '∴', - 'sim' => '∼', - 'cong' => '≅', - 'asymp' => '≈', - 'ne' => '≠', - 'equiv' => '≡', - 'le' => '≤', - 'ge' => '≥', - 'sub' => '⊂', - 'sup' => '⊃', - 'nsub' => '⊄', - 'sube' => '⊆', - 'supe' => '⊇', - 'oplus' => '⊕', - 'otimes' => '⊗', - 'perp' => '⊥', - 'sdot' => '⋅', - 'lceil' => '⌈', - 'rceil' => '⌉', - 'lfloor' => '⌊', - 'rfloor' => '⌋', - 'lang' => '〈', - 'rang' => '〉', - 'loz' => '◊', - 'spades' => '♠', - 'clubs' => '♣', - 'hearts' => '♥', - 'diams' => '♦', - 'nbsp' => ' ', - 'iexcl' => '¡', - 'cent' => '¢', - 'pound' => '£', - 'curren' => '¤', - 'yen' => '¥', - 'brvbar' => '¦', - 'sect' => '§', - 'uml' => '¨', - 'copy' => '©', - 'ordf' => 'ª', - 'laquo' => '«', - 'not' => '¬', - 'shy' => '­', - 'reg' => '®', - 'macr' => '¯', - 'deg' => '°', - 'plusmn' => '±', - 'sup2' => '²', - 'sup3' => '³', - 'acute' => '´', - 'micro' => 'µ', - 'para' => '¶', - 'middot' => '·', - 'cedil' => '¸', - 'sup1' => '¹', - 'ordm' => 'º', - 'raquo' => '»', - 'frac14' => '¼', - 'frac12' => '½', - 'frac34' => '¾', - 'iquest' => '¿', - 'Agrave' => 'À', - 'Aacute' => 'Á', - 'Acirc' => 'Â', - 'Atilde' => 'Ã', - 'Auml' => 'Ä', - 'Aring' => 'Å', - 'AElig' => 'Æ', - 'Ccedil' => 'Ç', - 'Egrave' => 'È', - 'Eacute' => 'É', - 'Ecirc' => 'Ê', - 'Euml' => 'Ë', - 'Igrave' => 'Ì', - 'Iacute' => 'Í', - 'Icirc' => 'Î', - 'Iuml' => 'Ï', - 'ETH' => 'Ð', - 'Ntilde' => 'Ñ', - 'Ograve' => 'Ò', - 'Oacute' => 'Ó', - 'Ocirc' => 'Ô', - 'Otilde' => 'Õ', - 'Ouml' => 'Ö', - 'times' => '×', - 'Oslash' => 'Ø', - 'Ugrave' => 'Ù', - 'Uacute' => 'Ú', - 'Ucirc' => 'Û', - 'Uuml' => 'Ü', - 'Yacute' => 'Ý', - 'THORN' => 'Þ', - 'szlig' => 'ß', - 'agrave' => 'à', - 'aacute' => 'á', - 'acirc' => 'â', - 'atilde' => 'ã', - 'auml' => 'ä', - 'aring' => 'å', - 'aelig' => 'æ', - 'ccedil' => 'ç', - 'egrave' => 'è', - 'eacute' => 'é', - 'ecirc' => 'ê', - 'euml' => 'ë', - 'igrave' => 'ì', - 'iacute' => 'í', - 'icirc' => 'î', - 'iuml' => 'ï', - 'eth' => 'ð', - 'ntilde' => 'ñ', - 'ograve' => 'ò', - 'oacute' => 'ó', - 'ocirc' => 'ô', - 'otilde' => 'õ', - 'ouml' => 'ö', - 'divide' => '÷', - 'oslash' => 'ø', - 'ugrave' => 'ù', - 'uacute' => 'ú', - 'ucirc' => 'û', - 'uuml' => 'ü', - 'yacute' => 'ý', - 'thorn' => 'þ', - 'yuml' => 'ÿ' - ); - - // Entity not found? Destroy it. - return isset($_ent_table[$str_xml_data[1]]) ? $_ent_table[$str_xml_data[1]] : ''; - } - - /** - * Static Method to load admin template - * - * @param object $obj_db - * @return void - */ - public static function loadUserTemplate($obj_db,$uid) - { - global $sysconf; - // load user template settings for override setting - $_q = $obj_db->query("SELECT admin_template FROM user WHERE user_id=$uid AND (admin_template!=NULL OR admin_template !='')"); - if($_q->num_rows>0){ - $template_settings = unserialize($_q->fetch_row()[0]); - foreach ($template_settings as $setting_name => $setting_value) { - $sysconf['admin_template'][$setting_name] = $setting_value; - } - } - } - - public static function dlCount($obj_db, $str_file_id, $str_member_id, $str_user_id) - { - if (!$obj_db->error) { - // log table - $_log_date = date('Y-m-d H:i:s'); - $_log_table = 'files_read'; - // filter input - $str_log_type = $obj_db->escape_string(trim($str_file_id)); - $str_value_id = $obj_db->escape_string(trim($str_member_id)); - $str_user_id = $obj_db->escape_string(trim($str_user_id)); - // insert log data to database - @$obj_db->query('INSERT INTO '.$_log_table.' - VALUES (NULL, \''.$str_file_id.'\', \''.$_log_date.'\', \''.$str_value_id.'\', \''.$str_user_id.'\', \''.$_SERVER[ - 'REMOTE_ADDR'].'\')'); - } - } -} +'."\n"; + echo 'alert("'.$str_message.'")'."\n"; + echo ''."\n"; + } + + /** + * Static Method to send out toastr notification + * + * @param string $type [info, success, warning, error] + * @param string $str_message + * @return void + */ + public static function jsToastr($title, $str_message, $type = 'info') + { + if (!$str_message) { + return; + } + + $options = [ + 'closeButton' => true, + 'debug' => false, + 'newestOnTop' => false, + 'progressBar' => false, + 'positionClass' => 'toast-top-right', + 'preventDuplicates' => false, + 'onclick' => null, + 'showDuration' => 300, + 'hideDuration' => 1000, + 'timeOut' => 5000, + 'extendedTimeOut' => 1000, + 'showEasing' => 'swing', + 'hideEasing' => 'linear', + 'showMethod' => 'fadeIn', + 'hideMethod' => 'fadeOut' + ]; + + // replace newline with javascripts newline + $str_message = str_replace("\n", '\n', addslashes($str_message)); + echo ''."\n"; + } + + + /** + * Static Method to create random string + * + * @param int $int_num_string: number of randowm string to created + * @return void + */ + public static function createRandomString($int_num_string = 32) + { + $_random = ''; + $_salt = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $_saltlength = strlen($_salt); + for ($r = 0; $r < $int_num_string; $r++) { + $_random .= $_salt[rand(0, $_saltlength - 1)]; + } + + return $_random; + } + + + /** + * Static Method to load application settings from database + * + * @param object $obj_db + * @return void + */ + public static function loadSettings($obj_db) + { + global $sysconf; + $_setting_query = $obj_db->query('SELECT * FROM setting'); + if (!$obj_db->errno) { + while ($_setting_data = $_setting_query->fetch_assoc()) { + $_value = @unserialize($_setting_data['setting_value']); + if (is_array($_value)) { + // make sure setting is available before + if (!isset($sysconf[$_setting_data['setting_name']])) + $sysconf[$_setting_data['setting_name']] = []; + + foreach ($_value as $_idx => $_curr_value) { + // convert default setting value into array + if (!is_array($sysconf[$_setting_data['setting_name']])) + $sysconf[$_setting_data['setting_name']] = [$sysconf[$_setting_data['setting_name']]]; + $sysconf[$_setting_data['setting_name']][$_idx] = $_curr_value; + } + } else { + $sysconf[$_setting_data['setting_name']] = stripcslashes($_value??''); + } + } + } + } + + + /** + * Static Method to check privileges of application module form current user + * + * @param string $str_module_name + * @param string $str_privilege_type + * @return boolean + */ + public static function havePrivilege($str_module_name, $str_privilege_type = 'r') + { + global $sysconf; + // checking checksum + if ($sysconf['load_balanced_env']) { + $server_addr = $_SERVER['REMOTE_ADDR']; + } else { + $server_addr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : (isset($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR'] : gethostbyname($_SERVER['SERVER_NAME'])); + } + + + $_checksum = defined('UCS_BASE_DIR')?md5($server_addr.UCS_BASE_DIR.'admin'):md5($server_addr.SB.'admin'); + if ($_SESSION['checksum'] != $_checksum) { + return false; + } + // check privilege type + if (!in_array($str_privilege_type, array('r', 'w'))) { + return false; + } + if (isset($_SESSION['priv'][$str_module_name][$str_privilege_type]) AND $_SESSION['priv'][$str_module_name][$str_privilege_type]) { + return true; + } + return false; + } + + + /** + * Static Method to write application activities logs + * + * @param object $obj_db + * @param string $str_log_type + * @param string $str_value_id + * @param string $str_location + * @param string $str_log_msg + * @return void + */ + public static function writeLogs($obj_db, $str_log_type, $str_value_id, $str_location, $str_log_msg, $str_log_submod='', $str_log_action='') + { + if (!$obj_db->error) { + // log table + $_log_date = date('Y-m-d H:i:s'); + $_log_table = 'system_log'; + // filter input + $str_log_type = $obj_db->escape_string(trim($str_log_type)); + $str_value_id = $obj_db->escape_string(trim($str_value_id)); + $str_location = $obj_db->escape_string(trim($str_location)); + $str_log_msg = $obj_db->escape_string(trim($str_log_msg)); + $str_log_submod = $obj_db->escape_string(trim($str_log_submod)); + $str_log_action = $obj_db->escape_string(trim($str_log_action)); + // insert log data to database + @$obj_db->query('INSERT INTO '.$_log_table.' + VALUES (NULL, \''.$str_log_type.'\', \''.$str_value_id.'\', \''.$str_location.'\','. + ' \''.$str_log_submod.'\''. + ', \''.$str_log_action.'\''. + ', \''.$str_log_msg.'\', \''.$_log_date.'\')'); + } + } + + + /** + * Static Method to get an ID of database table record + * + * @param object $obj_db + * @param string $str_table_name + * @param string $str_id_field + * @param string $str_value_field + * @param string $str_value + * @param array $arr_cache + * @return mixed + */ + public static function getID($obj_db, $str_table_name, $str_id_field, $str_value_field, $str_value, &$arr_cache = false) + { + $str_value = trim($str_value); + if ($arr_cache) { + if (isset($arr_cache[$str_value])) { + return $arr_cache[$str_value]; + } + } + if (!$obj_db->error) { + $id_q = $obj_db->query('SELECT '.$str_id_field.' FROM '.$str_table_name.' WHERE '.$str_value_field.'=\''.$obj_db->escape_string($str_value).'\''); + if ($id_q->num_rows > 0) { + $id_d = $id_q->fetch_row(); + unset($id_q); + // cache + if ($arr_cache) { + $arr_cache[$str_value] = $id_d[0]; + } + return $id_d[0]; + } else { + $_curr_date = date('Y-m-d'); + // if not found then we insert it as new value + $obj_db->query('INSERT IGNORE INTO '.$str_table_name.' ('.$str_value_field.', input_date, last_update) + VALUES (\''.$obj_db->escape_string($str_value).'\', \''.$_curr_date.'\', \''.$_curr_date.'\')'); + if (!$obj_db->error) { + // cache + if ($arr_cache) { + $arr_cache[$str_value] = $obj_db->insert_id; + } + return $obj_db->insert_id; + } + } + } + } + + + /** + * Static method to detect mobile browser + * + * @return boolean + * this script is taken from http://detectmobilebrowsers.com/ + **/ + public static function isMobileBrowser() + { + $_is_mobile_browser = false; + + if(preg_match('/android.+mobile|avantgo|bada\/|blackberry| + blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)| + iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i| + palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian| + treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)| + xda|xiino/i', + @$_SERVER['HTTP_USER_AGENT']) + || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s| + a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)| + amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw| + au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)| + br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc| + cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob| + do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8| + ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo| + go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)| + hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)| + i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno| + ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt | + kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])| + libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr| + me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do| + t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]| + n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)| + nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg| + pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox| + psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600| + raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)| + sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)| + sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)| + so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)| + ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)| + ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri| + vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc| + vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit| + wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i', + substr(@$_SERVER['HTTP_USER_AGENT'],0,4))) + $_is_mobile_browser = true; + + return $_is_mobile_browser; + } + + + /** + * Static method to check if member already logged in or not + * + * @return boolean + **/ + public static function isMemberLogin() + { + $_logged_in = false; + $_logged_in = isset($_SESSION['mid']) && isset($_SESSION['m_name']); + return $_logged_in; + } + + + /** + * Static method to filter data + * + * @param mixed $mix_input: input data + * @param string $str_input_type: input type + * @param boolean $bool_trim: are input string trimmed + * + * @return mixed + **/ + public static function filterData($mix_input, $str_input_type = 'get', $bool_escape_sql = true, $bool_trim = true, $bool_strip_html = false) { + global $dbs; + + if (extension_loaded('filter')) { + if ($str_input_type == 'var') { + $mix_input = filter_var($mix_input, FILTER_SANITIZE_STRING); + } else if ($str_input_type == 'post') { + $mix_input = filter_input(INPUT_POST, $mix_input); + } else if ($str_input_type == 'cookie') { + $mix_input = filter_input(INPUT_COOKIE, $mix_input); + } else if ($str_input_type == 'session') { + $mix_input = filter_input(INPUT_SESSION, $mix_input); + } else { + $mix_input = filter_input(INPUT_GET, $mix_input); + } + } else { + if ($str_input_type == 'get') { + $mix_input = $_GET[$mix_input]; + } else if ($str_input_type == 'post') { + $mix_input = $_POST[$mix_input]; + } else if ($str_input_type == 'cookie') { + $mix_input = $_COOKIE[$mix_input]; + } else if ($str_input_type == 'session') { + $mix_input = $_SESSION[$mix_input]; + } + } + + // trim whitespace on string + if ($bool_trim) { $mix_input = trim($mix_input); } + // strip html + if ($bool_strip_html) { $mix_input = strip_tags($mix_input); } + // escape SQL string + if ($bool_escape_sql) { $mix_input = $dbs->escape_string($mix_input); } + + return $mix_input; + } + + + /** + * Static method to convert XML entities + * Code taken and modified from: + * Matt Robinson at http://inanimatt.com/php-convert-entities.html + * + * @param string $str_xml_data: string of xml data to check + * + * @return string + **/ + public static function convertXMLentities($str_xml_data) { + static $_ent_table = array('quot' => '"', + 'amp' => '&', + 'lt' => '<', + 'gt' => '>', + 'OElig' => 'Œ', + 'oelig' => 'œ', + 'Scaron' => 'Š', + 'scaron' => 'š', + 'Yuml' => 'Ÿ', + 'circ' => 'ˆ', + 'tilde' => '˜', + 'ensp' => ' ', + 'emsp' => ' ', + 'thinsp' => ' ', + 'zwnj' => '‌', + 'zwj' => '‍', + 'lrm' => '‎', + 'rlm' => '‏', + 'ndash' => '–', + 'mdash' => '—', + 'lsquo' => '‘', + 'rsquo' => '’', + 'sbquo' => '‚', + 'ldquo' => '“', + 'rdquo' => '”', + 'bdquo' => '„', + 'dagger' => '†', + 'Dagger' => '‡', + 'permil' => '‰', + 'lsaquo' => '‹', + 'rsaquo' => '›', + 'euro' => '€', + 'fnof' => 'ƒ', + 'Alpha' => 'Α', + 'Beta' => 'Β', + 'Gamma' => 'Γ', + 'Delta' => 'Δ', + 'Epsilon' => 'Ε', + 'Zeta' => 'Ζ', + 'Eta' => 'Η', + 'Theta' => 'Θ', + 'Iota' => 'Ι', + 'Kappa' => 'Κ', + 'Lambda' => 'Λ', + 'Mu' => 'Μ', + 'Nu' => 'Ν', + 'Xi' => 'Ξ', + 'Omicron' => 'Ο', + 'Pi' => 'Π', + 'Rho' => 'Ρ', + 'Sigma' => 'Σ', + 'Tau' => 'Τ', + 'Upsilon' => 'Υ', + 'Phi' => 'Φ', + 'Chi' => 'Χ', + 'Psi' => 'Ψ', + 'Omega' => 'Ω', + 'alpha' => 'α', + 'beta' => 'β', + 'gamma' => 'γ', + 'delta' => 'δ', + 'epsilon' => 'ε', + 'zeta' => 'ζ', + 'eta' => 'η', + 'theta' => 'θ', + 'iota' => 'ι', + 'kappa' => 'κ', + 'lambda' => 'λ', + 'mu' => 'μ', + 'nu' => 'ν', + 'xi' => 'ξ', + 'omicron' => 'ο', + 'pi' => 'π', + 'rho' => 'ρ', + 'sigmaf' => 'ς', + 'sigma' => 'σ', + 'tau' => 'τ', + 'upsilon' => 'υ', + 'phi' => 'φ', + 'chi' => 'χ', + 'psi' => 'ψ', + 'omega' => 'ω', + 'thetasym' => 'ϑ', + 'upsih' => 'ϒ', + 'piv' => 'ϖ', + 'bull' => '•', + 'hellip' => '…', + 'prime' => '′', + 'Prime' => '″', + 'oline' => '‾', + 'frasl' => '⁄', + 'weierp' => '℘', + 'image' => 'ℑ', + 'real' => 'ℜ', + 'trade' => '™', + 'alefsym' => 'ℵ', + 'larr' => '←', + 'uarr' => '↑', + 'rarr' => '→', + 'darr' => '↓', + 'harr' => '↔', + 'crarr' => '↵', + 'lArr' => '⇐', + 'uArr' => '⇑', + 'rArr' => '⇒', + 'dArr' => '⇓', + 'hArr' => '⇔', + 'forall' => '∀', + 'part' => '∂', + 'exist' => '∃', + 'empty' => '∅', + 'nabla' => '∇', + 'isin' => '∈', + 'notin' => '∉', + 'ni' => '∋', + 'prod' => '∏', + 'sum' => '∑', + 'minus' => '−', + 'lowast' => '∗', + 'radic' => '√', + 'prop' => '∝', + 'infin' => '∞', + 'ang' => '∠', + 'and' => '∧', + 'or' => '∨', + 'cap' => '∩', + 'cup' => '∪', + 'int' => '∫', + 'there4' => '∴', + 'sim' => '∼', + 'cong' => '≅', + 'asymp' => '≈', + 'ne' => '≠', + 'equiv' => '≡', + 'le' => '≤', + 'ge' => '≥', + 'sub' => '⊂', + 'sup' => '⊃', + 'nsub' => '⊄', + 'sube' => '⊆', + 'supe' => '⊇', + 'oplus' => '⊕', + 'otimes' => '⊗', + 'perp' => '⊥', + 'sdot' => '⋅', + 'lceil' => '⌈', + 'rceil' => '⌉', + 'lfloor' => '⌊', + 'rfloor' => '⌋', + 'lang' => '〈', + 'rang' => '〉', + 'loz' => '◊', + 'spades' => '♠', + 'clubs' => '♣', + 'hearts' => '♥', + 'diams' => '♦', + 'nbsp' => ' ', + 'iexcl' => '¡', + 'cent' => '¢', + 'pound' => '£', + 'curren' => '¤', + 'yen' => '¥', + 'brvbar' => '¦', + 'sect' => '§', + 'uml' => '¨', + 'copy' => '©', + 'ordf' => 'ª', + 'laquo' => '«', + 'not' => '¬', + 'shy' => '­', + 'reg' => '®', + 'macr' => '¯', + 'deg' => '°', + 'plusmn' => '±', + 'sup2' => '²', + 'sup3' => '³', + 'acute' => '´', + 'micro' => 'µ', + 'para' => '¶', + 'middot' => '·', + 'cedil' => '¸', + 'sup1' => '¹', + 'ordm' => 'º', + 'raquo' => '»', + 'frac14' => '¼', + 'frac12' => '½', + 'frac34' => '¾', + 'iquest' => '¿', + 'Agrave' => 'À', + 'Aacute' => 'Á', + 'Acirc' => 'Â', + 'Atilde' => 'Ã', + 'Auml' => 'Ä', + 'Aring' => 'Å', + 'AElig' => 'Æ', + 'Ccedil' => 'Ç', + 'Egrave' => 'È', + 'Eacute' => 'É', + 'Ecirc' => 'Ê', + 'Euml' => 'Ë', + 'Igrave' => 'Ì', + 'Iacute' => 'Í', + 'Icirc' => 'Î', + 'Iuml' => 'Ï', + 'ETH' => 'Ð', + 'Ntilde' => 'Ñ', + 'Ograve' => 'Ò', + 'Oacute' => 'Ó', + 'Ocirc' => 'Ô', + 'Otilde' => 'Õ', + 'Ouml' => 'Ö', + 'times' => '×', + 'Oslash' => 'Ø', + 'Ugrave' => 'Ù', + 'Uacute' => 'Ú', + 'Ucirc' => 'Û', + 'Uuml' => 'Ü', + 'Yacute' => 'Ý', + 'THORN' => 'Þ', + 'szlig' => 'ß', + 'agrave' => 'à', + 'aacute' => 'á', + 'acirc' => 'â', + 'atilde' => 'ã', + 'auml' => 'ä', + 'aring' => 'å', + 'aelig' => 'æ', + 'ccedil' => 'ç', + 'egrave' => 'è', + 'eacute' => 'é', + 'ecirc' => 'ê', + 'euml' => 'ë', + 'igrave' => 'ì', + 'iacute' => 'í', + 'icirc' => 'î', + 'iuml' => 'ï', + 'eth' => 'ð', + 'ntilde' => 'ñ', + 'ograve' => 'ò', + 'oacute' => 'ó', + 'ocirc' => 'ô', + 'otilde' => 'õ', + 'ouml' => 'ö', + 'divide' => '÷', + 'oslash' => 'ø', + 'ugrave' => 'ù', + 'uacute' => 'ú', + 'ucirc' => 'û', + 'uuml' => 'ü', + 'yacute' => 'ý', + 'thorn' => 'þ', + 'yuml' => 'ÿ' + ); + + // Entity not found? Destroy it. + return isset($_ent_table[$str_xml_data[1]]) ? $_ent_table[$str_xml_data[1]] : ''; + } + + /** + * Static Method to load admin template + * + * @param object $obj_db + * @return void + */ + public static function loadUserTemplate($obj_db,$uid) + { + global $sysconf; + // load user template settings for override setting + $_q = $obj_db->query("SELECT admin_template FROM user WHERE user_id=$uid AND (admin_template!=NULL OR admin_template !='')"); + if($_q->num_rows>0){ + $template_settings = unserialize($_q->fetch_row()[0]); + foreach ($template_settings as $setting_name => $setting_value) { + $sysconf['admin_template'][$setting_name] = $setting_value; + } + } + } + + public static function dlCount($obj_db, $str_file_id, $str_member_id, $str_user_id) + { + if (!$obj_db->error) { + // log table + $_log_date = date('Y-m-d H:i:s'); + $_log_table = 'files_read'; + // filter input + $str_log_type = $obj_db->escape_string(trim($str_file_id)); + $str_value_id = $obj_db->escape_string(trim($str_member_id)); + $str_user_id = $obj_db->escape_string(trim($str_user_id)); + // insert log data to database + @$obj_db->query('INSERT INTO '.$_log_table.' + VALUES (NULL, \''.$str_file_id.'\', \''.$_log_date.'\', \''.$str_value_id.'\', \''.$str_user_id.'\', \''.$_SERVER[ + 'REMOTE_ADDR'].'\')'); + } + } +} diff --git a/lib/uuid/CHANGELOG.md b/lib/uuid/CHANGELOG.md deleted file mode 100644 index e6596055..00000000 --- a/lib/uuid/CHANGELOG.md +++ /dev/null @@ -1,1262 +0,0 @@ -# ramsey/uuid Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). - - -## [Unreleased] - -### Added - -### Changed - -### Deprecated - -### Removed - -### Fixed - -### Security - - -## [4.1.1] - 2020-08-18 - -### Fixed - -* Allow use of brick/math version 0.9 - - -## [4.1.0] - 2020-07-28 - -### Changed - -* Improve performance of `Uuid::fromString()`, `Uuid::fromBytes()`, - `UuidInterface#toString()`, and `UuidInterface#getBytes()`. See PR - [#324](https://github.com/ramsey/uuid/pull/324) for more information. - - -## [4.0.1] - 2020-03-29 - -### Fixed - -* Fix collection deserialization errors due to upstream `allowed_classes` being - set to `false`. For details, see [ramsey/uuid#303](https://github.com/ramsey/uuid/issues/303) - and [ramsey/collection#47](https://github.com/ramsey/collection/issues/47). - - -## [4.0.0] - 2020-03-22 - -### Added - -* Add support for version 6 UUIDs, as defined by , - including the static method `Uuid::uuid6()`, which returns a - `Nonstandard\UuidV6` instance. -* Add ability to generate version 2 (DCE Security) UUIDs, including the static - method `Uuid::uuid2()`, which returns an `Rfc4122\UuidV2` instance. -* Add classes to represent each version of RFC 4122 UUID. When generating new - UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID - is an RFC 4122 variant, one of these instances will be returned: - * `Rfc4122\UuidV1` - * `Rfc4122\UuidV2` - * `Rfc4122\UuidV3` - * `Rfc4122\UuidV4` - * `Rfc4122\UuidV5` - * `Rfc4122\NilUuid` -* Add classes to represent version 6 UUIDs, GUIDs, and nonstandard - (non-RFC 4122 variant) UUIDs: - * `Nonstandard\UuidV6` - * `Guid\Guid` - * `Nonstandard\Uuid` -* Add `Uuid::fromDateTime()` to create version 1 UUIDs from instances of - `\DateTimeInterface`. -* The `\DateTimeInterface` instance returned by `UuidInterface::getDateTime()` - (and now `Rfc4122\UuidV1::getDateTime()`) now includes microseconds, as - specified by the version 1 UUID. -* Add `Validator\ValidatorInterface` and `Validator\GenericValidator` to allow - flexibility in validating UUIDs/GUIDs. - * The default validator continues to validate UUID strings using the same - relaxed validation pattern found in the 3.x series of ramsey/uuid. - * Introduce `Rfc4122\Validator` that may be used for strict validation of - RFC 4122 UUID strings. - * Add ability to change the default validator used by `Uuid` through - `FeatureSet::setValidator()`. - * Add `getValidator()` and `setValidator()` to `UuidFactory`. -* Add `Provider\Node\StaticNodeProvider` to assist in setting a custom static - node value with the multicast bit set for version 1 UUIDs. -* Add the following new exceptions: - * `Exception\BuilderNotFoundException` - - Thrown to indicate that no suitable UUID builder could be found. - * `Exception\DateTimeException` - - Thrown to indicate that the PHP DateTime extension encountered an - exception/error. - * `Exception\DceSecurityException` - - Thrown to indicate an exception occurred while dealing with DCE Security - (version 2) UUIDs. - * `Exception\InvalidArgumentException` - - Thrown to indicate that the argument received is not valid. This extends the - built-in PHP `\InvalidArgumentException`, so there should be no BC breaks - with ramsey/uuid throwing this exception, if you are catching the PHP - exception. - * `Exception\InvalidBytesException` - - Thrown to indicate that the bytes being operated on are invalid in some way. - * `Exception\NameException` - - Thrown to indicate that an error occurred while attempting to hash a - namespace and name. - * `Exception\NodeException` - - Throw to indicate that attempting to fetch or create a node ID encountered - an error. - * `Exception\RandomSourceException` - - Thrown to indicate that the source of random data encountered an error. - * `Exception\TimeSourceException` - - Thrown to indicate that the source of time encountered an error. - * `Exception\UnableToBuildUuidException` - - Thrown to indicate a builder is unable to build a UUID. -* Introduce a `Builder\FallbackBuilder`, used by `FeatureSet` to help decide - whether to return a `Uuid` or `Nonstandard\Uuid` when decoding a - UUID string or bytes. -* Add `Rfc4122\UuidInterface` to specifically represent RFC 4122 variant UUIDs. -* Add `Rfc4122\UuidBuilder` to build RFC 4122 variant UUIDs. This replaces the - existing `Builder\DefaultUuidBuilder`, which is now deprecated. -* Introduce `Math\CalculatorInterface` for representing calculators to perform - arithmetic operations on integers. -* Depend on [brick/math](https://github.com/brick/math) for the - `Math\BrickMathCalculator`, which is the default calculator used by this - library when math cannot be performed in native PHP due to integer size - limitations. The calculator is configurable and may be changed, if desired. -* Add `Converter\Number\GenericNumberConverter` and - `Converter\Time\GenericTimeConverter` which will use the calculator provided - to convert numbers and time to values for UUIDs. -* Introduce `Type\Hexadecimal`, `Type\Integer`, `Type\Decimal`, and `Type\Time` - for improved type-safety when dealing with arbitrary string values. -* Add a `Type\TypeInterface` that each of the ramsey/uuid types implements. -* Add `Fields\FieldsInterface` and `Rfc4122\FieldsInterface` to define - field layouts for UUID variants. The implementations `Rfc4122\Fields`, - `Guid\Fields`, and `Nonstandard\Fields` store the 16-byte, - binary string representation of the UUID internally, and these manage - conversion of the binary string into the hexadecimal field values. -* Introduce `Builder\BuilderCollection` and `Provider\Node\NodeProviderCollection`. - These are typed collections for providing builders and node providers to - `Builder\FallbackBuilder` and `Provider\Node\FallbackNodeProvider`, respectively. -* Add `Generator\NameGeneratorInterface` to support alternate methods of - generating bytes for version 3 and version 5 name-based UUID. By default, - ramsey/uuid uses the `Generator\DefaultNameGenerator`, which uses the standard - algorithm this library has used since the beginning. You may choose to use the - new `Generator\PeclUuidNameGenerator` to make use of the new - `uuid_generate_md5()` and `uuid_generate_sha1()` functions in - [ext-uuid version 1.1.0](https://pecl.php.net/package/uuid). - -### Changed - -* Set minimum required PHP version to 7.2. -* This library now works on 32-bit and 64-bit systems, with no degradation in - functionality. -* By default, the following static methods will now return specific instance - types. This should not cause any BC breaks if typehints target `UuidInterface`: - * `Uuid::uuid1` returns `Rfc4122\UuidV1` - * `Uuid::uuid3` returns `Rfc4122\UuidV3` - * `Uuid::uuid4` returns `Rfc4122\UuidV4` - * `Uuid::uuid5` returns `Rfc4122\UuidV5` -* Accept `Type\Hexadecimal` for the `$node` parameter for - `UuidFactoryInterface::uuid1()`. This is in addition to the `int|string` types - already accepted, so there are no BC breaks. `Type\Hexadecimal` is now the - recommended type to pass for `$node`. -* Out of the box, `Uuid::fromString()`, `Uuid::fromBytes()`, and - `Uuid::fromInteger()` will now return either an `Rfc4122\UuidInterface` - instance or an instance of `Nonstandard\Uuid`, depending on whether the input - contains an RFC 4122 variant UUID with a valid version identifier. Both - implement `UuidInterface`, so BC breaks should not occur if typehints use the - interface. -* Change `Uuid::getFields()` to return an instance of `Fields\FieldsInterface`. - Previously, it returned an array of integer values (on 64-bit systems only). -* `Uuid::getDateTime()` now returns an instance of `\DateTimeImmutable` instead - of `\DateTime`. -* Make the following changes to `UuidInterface`: - * `getHex()` now returns a `Type\Hexadecimal` instance. - * `getInteger()` now returns a `Type\Integer` instance. The `Type\Integer` - instance holds a string representation of a 128-bit integer. You may then - use a math library of your choice (bcmath, gmp, etc.) to operate on the - string integer. - * `getDateTime()` now returns `\DateTimeInterface` instead of `\DateTime`. - * Add `__toString()` method. - * Add `getFields()` method. It returns an instance of `Fields\FieldsInterface`. -* Add the following new methods to `UuidFactoryInterface`: - * `uuid2()` - * `uuid6()` - * `fromDateTime()` - * `fromInteger()` - * `getValidator()` -* This library no longer throws generic exceptions. However, this should not - result in BC breaks, since the new exceptions extend from built-in PHP - exceptions that this library previously threw. - * `Exception\UnsupportedOperationException` is now descended from - `\LogicException`. Previously, it descended from `\RuntimeException`. -* Change required constructor parameters for `Uuid`: - * Change the first required constructor parameter for `Uuid` from - `array $fields` to `Rfc4122\FieldsInterface $fields`. - * Add `Converter\TimeConverterInterface $timeConverter` as the fourth - required constructor parameter for `Uuid`. -* Change the second required parameter of `Builder\UuidBuilderInterface::build()` - from `array $fields` to `string $bytes`. Rather than accepting an array of - hexadecimal strings as UUID fields, the `build()` method now expects a byte - string. -* Add `Converter\TimeConverterInterface $timeConverter` as the second required - constructor parameter for `Rfc4122\UuidBuilder`. This also affects the - now-deprecated `Builder\DefaultUuidBuilder`, since this class now inherits - from `Rfc4122\UuidBuilder`. -* Add `convertTime()` method to `Converter\TimeConverterInterface`. -* Add `getTime()` method to `Provider\TimeProviderInterface`. It replaces the - `currentTime()` method. -* `Provider\Node\FallbackNodeProvider` now accepts only a - `Provider\Node\NodeProviderCollection` as its constructor parameter. -* `Provider\Time\FixedTimeProvider` no longer accepts an array but accepts only - `Type\Time` instances. -* `Provider\NodeProviderInterface::getNode()` now returns `Type\Hexadecimal` - instead of `string|false|null`. -* `Converter/TimeConverterInterface::calculateTime()` now returns - `Type\Hexadecimal` instead of `array`. The value is the full UUID timestamp - value (count of 100-nanosecond intervals since the Gregorian calendar epoch) - in hexadecimal format. -* Change methods in `NumberConverterInterface` to accept and return string values - instead of `mixed`; this simplifies the interface and makes it consistent. -* `Generator\DefaultTimeGenerator` no longer adds the variant and version bits - to the bytes it returns. These must be applied to the bytes afterwards. -* When encoding to bytes or decoding from bytes, `OrderedTimeCodec` now checks - whether the UUID is an RFC 4122 variant, version 1 UUID. If not, it will throw - an exception—`InvalidArgumentException` when using - `OrderedTimeCodec::encodeBinary()` and `UnsupportedOperationException` when - using `OrderedTimeCodec::decodeBytes()`. - -### Deprecated - -The following functionality is deprecated and will be removed in ramsey/uuid -5.0.0. - -* The following methods from `UuidInterface` and `Uuid` are deprecated. Use their - counterparts on the `Rfc4122\FieldsInterface` returned by `Uuid::getFields()`. - * `getClockSeqHiAndReservedHex()` - * `getClockSeqLowHex()` - * `getClockSequenceHex()` - * `getFieldsHex()` - * `getNodeHex()` - * `getTimeHiAndVersionHex()` - * `getTimeLowHex()` - * `getTimeMidHex()` - * `getTimestampHex()` - * `getVariant()` - * `getVersion()` -* The following methods from `Uuid` are deprecated. Use the `Rfc4122\FieldsInterface` - instance returned by `Uuid::getFields()` to get the `Type\Hexadecimal` value - for these fields. You may use the new `Math\CalculatorInterface::toIntegerValue()` - method to convert the `Type\Hexadecimal` instances to instances of - `Type\Integer`. This library provides `Math\BrickMathCalculator`, which may be - used for this purpose, or you may use the arbitrary-precision arithemetic - library of your choice. - * `getClockSeqHiAndReserved()` - * `getClockSeqLow()` - * `getClockSequence()` - * `getNode()` - * `getTimeHiAndVersion()` - * `getTimeLow()` - * `getTimeMid()` - * `getTimestamp()` -* `getDateTime()` on `UuidInterface` and `Uuid` is deprecated. Use this method - only on instances of `Rfc4122\UuidV1` or `Nonstandard\UuidV6`. -* `getUrn()` on `UuidInterface` and `Uuid` is deprecated. It is available on - `Rfc4122\UuidInterface` and classes that implement it. -* The following methods are deprecated and have no direct replacements. However, - you may obtain the same information by calling `UuidInterface::getHex()` and - splitting the return value in half. - * `UuidInterface::getLeastSignificantBitsHex()` - * `UuidInterface::getMostSignificantBitsHex()` - * `Uuid::getLeastSignificantBitsHex()` - * `Uuid::getMostSignificantBitsHex()` - * `Uuid::getLeastSignificantBits()` - * `Uuid::getMostSignificantBits()` -* `UuidInterface::getNumberConverter()` and `Uuid::getNumberConverter()` are - deprecated. There is no alternative recommendation, so plan accordingly. -* `Builder\DefaultUuidBuilder` is deprecated; transition to `Rfc4122\UuidBuilder`. -* `Converter\Number\BigNumberConverter` is deprecated; transition to - `Converter\Number\GenericNumberConverter`. -* `Converter\Time\BigNumberTimeConverter` is deprecated; transition to - `Converter\Time\GenericTimeConverter`. -* The classes for representing and generating *degraded* UUIDs are deprecated. - These are no longer necessary; this library now behaves the same on 32-bit and - 64-bit systems. - * `Builder\DegradedUuidBuilder` - * `Converter\Number\DegradedNumberConverter` - * `Converter\Time\DegradedTimeConverter` - * `DegradedUuid` -* The `Uuid::UUID_TYPE_IDENTIFIER` constant is deprecated. Use - `Uuid::UUID_TYPE_DCE_SECURITY` instead. -* The `Uuid::VALID_PATTERN` constant is deprecated. Use - `Validator\GenericValidator::getPattern()` or `Rfc4122\Validator::getPattern()` - instead. - -### Removed - -* Remove the following bytes generators and recommend - `Generator\RandomBytesGenerator` as a suitable replacement: - * `Generator\MtRandGenerator` - * `Generator\OpenSslGenerator` - * `Generator\SodiumRandomGenerator` -* Remove `Exception\UnsatisfiedDependencyException`. This library no longer - throws this exception. -* Remove the method `Provider\TimeProviderInterface::currentTime()`. Use - `Provider\TimeProviderInterface::getTime()` instead. - - -## [4.0.0-beta2] - 2020-03-01 - -## Added - -* Add missing convenience methods for `Rfc4122\UuidV2`. -* Add `Provider\Node\StaticNodeProvider` to assist in setting a custom static - node value with the multicast bit set for version 1 UUIDs. - -## Changed - -* `Provider\NodeProviderInterface::getNode()` now returns `Type\Hexadecimal` - instead of `string|false|null`. - - -## [4.0.0-beta1] - 2020-02-27 - -### Added - -* Add `ValidatorInterface::getPattern()` to return the regular expression - pattern used by the validator. -* Add `v6()` helper function for version 6 UUIDs. - -### Changed - -* Set the pattern constants on validators as `private`. Use the `getPattern()` - method instead. -* Change the `$node` parameter for `UuidFactoryInterface::uuid6()` to accept - `null` or `Type\Hexadecimal`. -* Accept `Type\Hexadecimal` for the `$node` parameter for - `UuidFactoryInterface::uuid1()`. This is in addition to the `int|string` types - already accepted, so there are no BC breaks. `Type\Hexadecimal` is now the - recommended type to pass for `$node`. - -### Removed - -* Remove `currentTime()` method from `Provider\Time\FixedTimeProvider` and - `Provider\Time\SystemTimeProvider`; it had previously been removed from - `Provider\TimeProviderInterface`. - - -## [4.0.0-alpha5] - 2020-02-23 - -### Added - -* Introduce `Builder\BuilderCollection` and `Provider\Node\NodeProviderCollection`. - -### Changed - -* `Builder\FallbackBuilder` now accepts only a `Builder\BuilderCollection` as - its constructor parameter. -* `Provider\Node\FallbackNodeProvider` now accepts only a `Provider\Node\NodeProviderCollection` - as its constructor parameter. -* `Provider\Time\FixedTimeProvider` no longer accepts an array but accepts only - `Type\Time` instances. - - -## [4.0.0-alpha4] - 2020-02-23 - -### Added - -* Add a `Type\TypeInterface` that each of the ramsey/uuid types implements. -* Support version 6 UUIDs; see . - -### Changed - -* Rename `Type\IntegerValue` to `Type\Integer`. It was originally named - `IntegerValue` because static analysis sees `Integer` in docblock annotations - and treats it as the native `int` type. `Integer` is not a reserved word in - PHP, so it should be named `Integer` for consistency with other types in this - library. When using it, a class alias prevents static analysis from - complaining. -* Mark `Guid\Guid` and `Nonstandard\Uuid` classes as `final`. -* Add `uuid6()` method to `UuidFactoryInterface`. - -### Deprecated - -* `Uuid::UUID_TYPE_IDENTIFIER` is deprecated. Use `Uuid::UUID_TYPE_DCE_SECURITY` - instead. -* `Uuid::VALID_PATTERN` is deprecated. Use `Validator\GenericValidator::VALID_PATTERN` - instead. - - -## [4.0.0-alpha3] - 2020-02-21 - -### Fixed - -* Fix microsecond rounding error on 32-bit systems. - - -## [4.0.0-alpha2] - 2020-02-21 - -### Added - -* Add `Uuid::fromDateTime()` to create version 1 UUIDs from instances of - `\DateTimeInterface`. -* Add `Generator\NameGeneratorInterface` to support alternate methods of - generating bytes for version 3 and version 5 name-based UUID. By default, - ramsey/uuid uses the `Generator\DefaultNameGenerator`, which uses the standard - algorithm this library has used since the beginning. You may choose to use the - new `Generator\PeclUuidNameGenerator` to make use of the new - `uuid_generate_md5()` and `uuid_generate_sha1()` functions in ext-uuid version - 1.1.0. - -### Changed - -* Add `fromDateTime()` method to `UuidFactoryInterface`. -* Change `UuidInterface::getHex()` to return a `Ramsey\Uuid\Type\Hexadecimal` instance. -* Change `UuidInterface::getInteger()` to return a `Ramsey\Uuid\Type\IntegerValue` instance. - -### Fixed - -* Round microseconds to six digits when getting DateTime from v1 UUIDs. This - circumvents a needless exception for an otherwise valid time-based UUID. - - -## [4.0.0-alpha1] - 2020-01-22 - -### Added - -* Add `Validator\ValidatorInterface` and `Validator\GenericValidator` to allow - flexibility in validating UUIDs/GUIDs. - * Add ability to change the default validator used by `Uuid` through - `FeatureSet::setValidator()`. - * Add `getValidator()` and `setValidator()` to `UuidFactory`. -* Add an internal `InvalidArgumentException` that descends from the built-in - PHP `\InvalidArgumentException`. All places that used to throw - `\InvalidArgumentException` now throw `Ramsey\Uuid\Exception\InvalidArgumentException`. - This should not cause any BC breaks, however. -* Add an internal `DateTimeException` that descends from the built-in PHP - `\RuntimeException`. `Uuid::getDateTime()` may throw this exception if - `\DateTimeImmutable` throws an error or exception. -* Add `RandomSourceException` that descends from the built-in PHP - `\RuntimeException`. `DefaultTimeGenerator`, `RandomBytesGenerator`, and - `RandomNodeProvider` may throw this exception if `random_bytes()` or - `random_int()` throw an error or exception. -* Add `Fields\FieldsInterface` and `Rfc4122\FieldsInterface` to define - field layouts for UUID variants. The implementations `Rfc4122\Fields`, - `Guid\Fields`, and `Nonstandard\Fields` store the 16-byte, - binary string representation of the UUID internally, and these manage - conversion of the binary string into the hexadecimal field values. -* Add `Rfc4122\UuidInterface` to specifically represent RFC 4122 variant UUIDs. -* Add classes to represent each version of RFC 4122 UUID. When generating new - UUIDs or creating UUIDs from existing strings, bytes, or integers, if the UUID - is an RFC 4122 variant, one of these instances will be returned: - * `Rfc4122\UuidV1` - * `Rfc4122\UuidV2` - * `Rfc4122\UuidV3` - * `Rfc4122\UuidV4` - * `Rfc4122\UuidV5` - * `Rfc4122\NilUuid` -* Add `Rfc4122\UuidBuilder` to build RFC 4122 variant UUIDs. This replaces the - existing `Builder\DefaultUuidBuilder`, which is now deprecated. -* Add ability to generate version 2 (DCE Security) UUIDs, including the static - method `Uuid::uuid2()`, which returns an `Rfc4122\UuidV2` instance. -* Add classes to represent GUIDs and nonstandard (non-RFC 4122 variant) UUIDs: - * `Guid\Guid` - * `Nonstandard\Uuid`. -* Introduce a `Builder\FallbackBuilder`, used by `FeatureSet` to help decide - whether to return a `Uuid` or `Nonstandard\Uuid` when decoding a - UUID string or bytes. -* Introduce `Type\Hexadecimal`, `Type\IntegerValue`, and `Type\Time` for - improved type-safety when dealing with arbitrary string values. -* Introduce `Math\CalculatorInterface` for representing calculators to perform - arithmetic operations on integers. -* Depend on [brick/math](https://github.com/brick/math) for the - `Math\BrickMathCalculator`, which is the default calculator used by this - library when math cannot be performed in native PHP due to integer size - limitations. The calculator is configurable and may be changed, if desired. -* Add `Converter\Number\GenericNumberConverter` and - `Converter\Time\GenericTimeConverter` which will use the calculator provided - to convert numbers and time to values for UUIDs. -* The `\DateTimeInterface` instance returned by `UuidInterface::getDateTime()` - (and now `Rfc4122\UuidV1::getDateTime()`) now includes microseconds, as - specified by the version 1 UUID. - -### Changed - -* Set minimum required PHP version to 7.2. -* Add `__toString()` method to `UuidInterface`. -* The `UuidInterface::getDateTime()` method now specifies `\DateTimeInterface` - as the return value, rather than `\DateTime`; `Uuid::getDateTime()` now - returns an instance of `\DateTimeImmutable` instead of `\DateTime`. -* Add `getFields()` method to `UuidInterface`. -* Add `getValidator()` method to `UuidFactoryInterface`. -* Add `uuid2()` method to `UuidFactoryInterface`. -* Add `convertTime()` method to `Converter\TimeConverterInterface`. -* Add `getTime()` method to `Provider\TimeProviderInterface`. -* Change `Uuid::getFields()` to return an instance of `Fields\FieldsInterface`. - Previously, it returned an array of integer values (on 64-bit systems only). -* Change the first required constructor parameter for `Uuid` from - `array $fields` to `Rfc4122\FieldsInterface $fields`. -* Introduce `Converter\TimeConverterInterface $timeConverter` as fourth required - constructor parameter for `Uuid` and second required constructor parameter for - `Builder\DefaultUuidBuilder`. -* Change `UuidInterface::getInteger()` to always return a `string` value instead - of `mixed`. This is a string representation of a 128-bit integer. You may then - use a math library of your choice (bcmath, gmp, etc.) to operate on the - string integer. -* Change the second required parameter of `Builder\UuidBuilderInterface::build()` - from `array $fields` to `string $bytes`. Rather than accepting an array of - hexadecimal strings as UUID fields, the `build()` method now expects a byte - string. -* `Generator\DefaultTimeGenerator` no longer adds the variant and version bits - to the bytes it returns. These must be applied to the bytes afterwards. -* `Converter/TimeConverterInterface::calculateTime()` now returns - `Type\Hexadecimal` instead of `array`. The value is the full UUID timestamp - value (count of 100-nanosecond intervals since the Gregorian calendar epoch) - in hexadecimal format. -* Change methods in converter interfaces to accept and return string values - instead of `mixed`; this simplifies the interface and makes it consistent: - * `NumberConverterInterface::fromHex(string $hex): string` - * `NumberConverterInterface::toHex(string $number): string` - * `TimeConverterInterface::calculateTime(string $seconds, string $microseconds): array` -* `UnsupportedOperationException` is now descended from `\LogicException`. - Previously, it descended from `\RuntimeException`. -* When encoding to bytes or decoding from bytes, `OrderedTimeCodec` now checks - whether the UUID is an RFC 4122 variant, version 1 UUID. If not, it will throw - an exception—`InvalidArgumentException` when using - `OrderedTimeCodec::encodeBinary()` and `UnsupportedOperationException` when - using `OrderedTimeCodec::decodeBytes()`. -* Out of the box, `Uuid::fromString()`, `Uuid::fromBytes()`, and - `Uuid::fromInteger()` will now return either an `Rfc4122\UuidInterface` - instance or an instance of `Nonstandard\Uuid`, depending on whether the input - contains an RFC 4122 variant UUID with a valid version identifier. Both - implement `UuidInterface`, so BC breaks should not occur if typehints use the - interface. -* By default, the following static methods will now return the specific instance - types. This should not cause any BC breaks if typehints target `UuidInterface`: - * `Uuid::uuid1` returns `Rfc4122\UuidV1` - * `Uuid::uuid3` returns `Rfc4122\UuidV3` - * `Uuid::uuid4` returns `Rfc4122\UuidV4` - * `Uuid::uuid5` returns `Rfc4122\UuidV5` - -### Deprecated - -The following functionality is deprecated and will be removed in ramsey/uuid -5.0.0. - -* The following methods from `UuidInterface` and `Uuid` are deprecated. Use their - counterparts on the `Rfc4122\FieldsInterface` returned by `Uuid::getFields()`. - * `getClockSeqHiAndReservedHex()` - * `getClockSeqLowHex()` - * `getClockSequenceHex()` - * `getFieldsHex()` - * `getNodeHex()` - * `getTimeHiAndVersionHex()` - * `getTimeLowHex()` - * `getTimeMidHex()` - * `getTimestampHex()` - * `getVariant()` - * `getVersion()` -* The following methods from `Uuid` are deprecated. Use the `Rfc4122\FieldsInterface` - instance returned by `Uuid::getFields()` to get the `Type\Hexadecimal` value - for these fields, and then use the arbitrary-precision arithmetic library of - your choice to convert them to string integers. - * `getClockSeqHiAndReserved()` - * `getClockSeqLow()` - * `getClockSequence()` - * `getNode()` - * `getTimeHiAndVersion()` - * `getTimeLow()` - * `getTimeMid()` - * `getTimestamp()` -* `getDateTime()` on `UuidInterface` and `Uuid` is deprecated. Use this method - only on instances of `Rfc4122\UuidV1`. -* `getUrn()` on `UuidInterface` and `Uuid` is deprecated. It is available on - `Rfc4122\UuidInterface` and classes that implement it. -* The following methods are deprecated and have no direct replacements. However, - you may obtain the same information by calling `UuidInterface::getHex()` and - splitting the return value in half. - * `UuidInterface::getLeastSignificantBitsHex()` - * `UuidInterface::getMostSignificantBitsHex()` - * `Uuid::getLeastSignificantBitsHex()` - * `Uuid::getMostSignificantBitsHex()` - * `Uuid::getLeastSignificantBits()` - * `Uuid::getMostSignificantBits()` -* `UuidInterface::getNumberConverter()` and `Uuid::getNumberConverter()` are - deprecated. There is no alternative recommendation, so plan accordingly. -* `Builder\DefaultUuidBuilder` is deprecated; transition to - `Rfc4122\UuidBuilder`. -* `Converter\Number\BigNumberConverter` is deprecated; transition to - `Converter\Number\GenericNumberConverter`. -* `Converter\Time\BigNumberTimeConverter` is deprecated; transition to - `Converter\Time\GenericTimeConverter`. -* `Provider\TimeProviderInterface::currentTime()` is deprecated; transition to - the `getTimestamp()` method on the same interface. -* The classes for representing and generating *degraded* UUIDs are deprecated. - These are no longer necessary; this library now behaves the same on 32-bit and - 64-bit PHP. - * `Builder\DegradedUuidBuilder` - * `Converter\Number\DegradedNumberConverter` - * `Converter\Time\DegradedTimeConverter` - * `DegradedUuid` - -### Removed - -* Remove the following bytes generators and recommend - `Generator\RandomBytesGenerator` as a suitable replacement: - * `Generator\MtRandGenerator` - * `Generator\OpenSslGenerator` - * `Generator\SodiumRandomGenerator` -* Remove `Exception\UnsatisfiedDependencyException`. This library no longer - throws this exception. - - -## [3.9.3] - 2020-02-20 - -### Fixed - -* For v1 UUIDs, round down for timestamps so that microseconds do not bump the - timestamp to the next second. - - As an example, consider the case of timestamp `1` with `600000` microseconds - (`1.600000`). This is the first second after midnight on January 1, 1970, UTC. - Previous versions of this library had a bug that would round this to `2`, so - the rendered time was `1970-01-01 00:00:02`. This was incorrect. Despite - having `600000` microseconds, the time should not round up to the next second. - Rather, the time should be `1970-01-01 00:00:01.600000`. Since this version of - ramsey/uuid does not support microseconds, the microseconds are dropped, and - the time is `1970-01-01 00:00:01`. No rounding should occur. - - -## [3.9.2] - 2019-12-17 - -### Fixed - -* Check whether files returned by `/sys/class/net/*/address` are readable - before attempting to read them. This avoids a PHP warning that was being - emitted on hosts that do not grant permission to read these files. - - -## [3.9.1] - 2019-12-01 - -### Fixed - -* Fix `RandomNodeProvider` behavior on 32-bit systems. The `RandomNodeProvider` - was converting a 6-byte string to a decimal number, which is a 48-bit, - unsigned integer. This caused problems on 32-bit systems and has now been - resolved. - - -## [3.9.0] - 2019-11-30 - -### Added - -* Add function API as convenience. The functions are available in the - `Ramsey\Uuid` namespace. - * `v1(int|string|null $node = null, int|null $clockSeq = null): string` - * `v3(string|UuidInterface $ns, string $name): string` - * `v4(): string` - * `v5(string|UuidInterface $ns, string $name): string` - -### Changed - -* Use paragonie/random-lib instead of ircmaxell/random-lib. This is a - non-breaking change. -* Use a high-strength generator by default, when using `RandomLibAdapter`. This - is a non-breaking change. - -### Deprecated - -These will be removed in ramsey/uuid version 4.0.0: - -* `MtRandGenerator`, `OpenSslGenerator`, and `SodiumRandomGenerator` are - deprecated in favor of using the default `RandomBytesGenerator`. - -### Fixed - -* Set `ext-json` as a required dependency in `composer.json`. -* Use `PHP_OS` instead of `php_uname()` when determining the system OS, for - cases when `php_uname()` is disabled for security reasons. - - -## [3.8.0] - 2018-07-19 - -### Added - -* Support discovery of MAC addresses on FreeBSD systems -* Use a polyfill to provide PHP ctype functions when running on systems where the - ctype functions are not part of the PHP build -* Disallow a trailing newline character when validating UUIDs -* Annotate thrown exceptions for improved IDE hinting - - -## [3.7.3] - 2018-01-19 - -### Fixed - -* Gracefully handle cases where `glob()` returns false when searching - `/sys/class/net/*/address` files on Linux -* Fix off-by-one error in `DefaultTimeGenerator` - -### Security - -* Switch to `random_int()` from `mt_rand()` for better random numbers - - -## [3.7.2] - 2018-01-13 - -### Fixed - -* Check sysfs on Linux to determine the node identifier; this provides a - reliable way to identify the node on Docker images, etc. - - -## [3.7.1] - 2017-09-22 - -### Fixed - -* Set the multicast bit for random nodes, according to RFC 4122, §4.5 - -### Security - -* Use `random_bytes()` when generating random nodes - - -## [3.7.0] - 2017-08-04 - -### Added - -* Add the following UUID version constants: - * `Uuid::UUID_TYPE_TIME` - * `Uuid::UUID_TYPE_IDENTIFIER` - * `Uuid::UUID_TYPE_HASH_MD5` - * `Uuid::UUID_TYPE_RANDOM` - * `Uuid::UUID_TYPE_HASH_SHA1` - - -## [3.6.1] - 2017-03-26 - -### Fixed - -* Optimize UUID string decoding by using `str_pad()` instead of `sprintf()` - - -## [3.6.0] - 2017-03-18 - -### Added - -* Add `InvalidUuidStringException`, which is thrown when attempting to decode an - invalid string UUID; this does not introduce any BC issues, since the new - exception inherits from the previously used `InvalidArgumentException` - -### Fixed - -* Improve memory usage when generating large quantities of UUIDs (use `str_pad()` - and `dechex()` instead of `sprintf()`) - - -## [3.5.2] - 2016-11-22 - -### Fixed - -* Improve test coverage - - -## [3.5.1] - 2016-10-02 - -### Fixed - -* Fix issue where the same UUIDs were not being treated as equal when using - mixed cases - - -## [3.5.0] - 2016-08-02 - -### Added - -* Add `OrderedTimeCodec` to store UUID in an optimized way for InnoDB - -### Fixed - -* Fix invalid node generation in `RandomNodeProvider` -* Avoid multiple unnecessary system calls by caching failed attempt to retrieve - system node - - -## [3.4.1] - 2016-04-23 - -### Fixed - -* Fix test that violated a PHP CodeSniffer rule, breaking the build - - -## [3.4.0] - 2016-04-23 - -### Added - -* Add `TimestampFirstCombCodec` and `TimestampLastCombCodec` codecs to provide - the ability to generate [COMB sequential UUIDs] with the timestamp encoded as - either the first 48 bits or the last 48 bits -* Improve logic of `CombGenerator` for COMB sequential UUIDs - - -## [3.3.0] - 2016-03-22 - -### Security - -* Drop the use of OpenSSL as a fallback and use [paragonie/random_compat] to - support `RandomBytesGenerator` in versions of PHP earlier than 7.0; - this addresses and fixes the [collision issue] - - -## [3.2.0] - 2016-02-17 - -### Added - -* Add `SodiumRandomGenerator` to allow use of the [PECL libsodium extension] as - a random bytes generator when creating UUIDs - - -## [3.1.0] - 2015-12-17 - -### Added - -* Implement the PHP `Serializable` interface to provide the ability to - serialize/unserialize UUID objects - - -## [3.0.1] - 2015-10-21 - -### Added - -* Adopt the [Contributor Code of Conduct] for this project - - -## [3.0.0] - 2015-09-28 - -The 3.0.0 release represents a significant step for the ramsey/uuid library. -While the simple and familiar API used in previous versions remains intact, this -release provides greater flexibility to integrators, including the ability to -inject your own number generators, UUID codecs, node and time providers, and -more. - -*Please note: The changelog for 3.0.0 includes all notes from the alpha and beta -versions leading up to this release.* - -### Added - -* Add a number of generators that may be used to override the library defaults - for generating random bytes (version 4) or time-based (version 1) UUIDs - * `CombGenerator` to allow generation of sequential UUIDs - * `OpenSslGenerator` to generate random bytes on systems where - `openssql_random_pseudo_bytes()` is present - * `MtRandGenerator` to provide a fallback in the event other random generators - are not present - * `RandomLibAdapter` to allow use of [ircmaxell/random-lib] - * `RandomBytesGenerator` for use with PHP 7; ramsey/uuid will default to use - this generator when running on PHP 7 - * Refactor time-based (version 1) UUIDs into a `TimeGeneratorInterface` to - allow for other sources to generate version 1 UUIDs in this library - * `PeclUuidTimeGenerator` and `PeclUuidRandomGenerator` for creating version - 1 or version 4 UUIDs using the pecl-uuid extension -* Add a `setTimeGenerator` method on `UuidFactory` to override the default time - generator -* Add option to enable `PeclUuidTimeGenerator` via `FeatureSet` -* Support GUID generation by configuring a `FeatureSet` to use GUIDs -* Allow UUIDs to be serialized as JSON through `JsonSerializable` - -### Changed - -* Change root namespace from "Rhumsaa" to "Ramsey;" in most cases, simply - making this change in your applications is the only upgrade path you will - need—everything else should work as expected -* No longer consider `Uuid` class as `final`; everything is now based around - interfaces and factories, allowing you to use this package as a base to - implement other kinds of UUIDs with different dependencies -* Return an object of type `DegradedUuid` on 32-bit systems to indicate that - certain features are not available -* Default `RandomLibAdapter` to a medium-strength generator with - [ircmaxell/random-lib]; this is configurable, so other generator strengths may - be used - -### Removed - -* Remove `PeclUuidFactory` in favor of using pecl-uuid with generators -* Remove `timeConverter` and `timeProvider` properties, setters, and getters in - both `FeatureSet` and `UuidFactory` as those are now exclusively used by the - default `TimeGenerator` -* Move UUID [Doctrine field type] to [ramsey/uuid-doctrine] -* Move `uuid` console application to [ramsey/uuid-console] -* Remove `Uuid::VERSION` package version constant - -### Fixed - -* Improve GUID support to ensure that: - * On little endian (LE) architectures, the byte order of the first three - fields is LE - * On big endian (BE) architectures, it is the same as a GUID - * String representation is always the same -* Fix exception message for `DegradedNumberConverter::fromHex()` - - -## [3.0.0-beta1] - 2015-08-31 - -### Fixed - -* Improve GUID support to ensure that: - * On little endian (LE) architectures, the byte order of the first three - fields is LE - * On big endian (BE) architectures, it is the same as a GUID - * String representation is always the same -* Fix exception message for `DegradedNumberConverter::fromHex()` - - -## [3.0.0-alpha3] - 2015-07-28 - -### Added - -* Enable use of custom `TimeGenerator` implementations -* Add a `setTimeGenerator` method on `UuidFactory` to override the default time - generator -* Add option to enable `PeclUuidTimeGenerator` via `FeatureSet` - -### Removed - -* Remove `timeConverter` and `timeProvider` properties, setters, and getters in - both `FeatureSet` and `UuidFactory` as those are now exclusively used by the - default `TimeGenerator` - - -## [3.0.0-alpha2] - 2015-07-28 - -### Added - -* Refactor time-based (version 1) UUIDs into a `TimeGeneratorInterface` to allow - for other sources to generate version 1 UUIDs in this library -* Add `PeclUuidTimeGenerator` and `PeclUuidRandomGenerator` for creating version - 1 or version 4 UUIDs using the pecl-uuid extension -* Add `RandomBytesGenerator` for use with PHP 7. ramsey/uuid will default to use - this generator when running on PHP 7 - -### Changed - -* Default `RandomLibAdapter` to a medium-strength generator with - [ircmaxell/random-lib]; this is configurable, so other generator strengths may - be used - -### Removed - -* Remove `PeclUuidFactory` in favor of using pecl-uuid with generators - - -## [3.0.0-alpha1] - 2015-07-16 - -### Added - -* Allow dependency injection through `UuidFactory` and/or extending `FeatureSet` - to override any package defaults -* Add a number of generators that may be used to override the library defaults: - * `CombGenerator` to allow generation of sequential UUIDs - * `OpenSslGenerator` to generate random bytes on systems where - `openssql_random_pseudo_bytes()` is present - * `MtRandGenerator` to provide a fallback in the event other random generators - are not present - * `RandomLibAdapter` to allow use of [ircmaxell/random-lib] -* Support GUID generation by configuring a `FeatureSet` to use GUIDs -* Allow UUIDs to be serialized as JSON through `JsonSerializable` - -### Changed - -* Change root namespace from "Rhumsaa" to "Ramsey;" in most cases, simply - making this change in your applications is the only upgrade path you will - need—everything else should work as expected -* No longer consider `Uuid` class as `final`; everything is now based around - interfaces and factories, allowing you to use this package as a base to - implement other kinds of UUIDs with different dependencies -* Return an object of type `DegradedUuid` on 32-bit systems to indicate that - certain features are not available - -### Removed - -* Move UUID [Doctrine field type] to [ramsey/uuid-doctrine] -* Move `uuid` console application to [ramsey/uuid-console] -* Remove `Uuid::VERSION` package version constant - - -## [2.9.0] - 2016-03-22 - -### Security - -* Drop the use of OpenSSL as a fallback and use [paragonie/random_compat] to - support `RandomBytesGenerator` in versions of PHP earlier than 7.0; - this addresses and fixes the [collision issue] - - -## [2.8.4] - 2015-12-17 - -### Added - -* Add support for symfony/console v3 in the `uuid` CLI application - - -## [2.8.3] - 2015-08-31 - -### Fixed - -* Fix exception message in `Uuid::calculateUuidTime()` - - -## [2.8.2] - 2015-07-23 - -### Fixed - -* Ensure the release tag makes it into the rhumsaa/uuid package - - -## [2.8.1] - 2015-06-16 - -### Fixed - -* Use `passthru()` and output buffering in `getIfconfig()` -* Cache the system node in a static variable so that we process it only once per - runtime - - -## [2.8.0] - 2014-11-09 - -### Added - -* Add static `fromInteger()` method to create UUIDs from string integer or - `Moontoast\Math\BigNumber` - -### Fixed - -* Improve Doctrine conversion to Uuid or string for the ramsey/uuid [Doctrine field type] - - -## [2.7.4] - 2014-10-29 - -### Fixed - -* Change loop in `generateBytes()` from `foreach` to `for` - - -## [2.7.3] - 2014-08-27 - -### Fixed - -* Fix upper range for `mt_rand` used in version 4 UUIDs - - -## [2.7.2] - 2014-07-28 - -### Changed - -* Upgrade to PSR-4 autoloading - - -## [2.7.1] - 2014-02-19 - -### Fixed - -* Move moontoast/math and symfony/console to require-dev -* Support symfony/console 2.3 (LTS version) - - -## [2.7.0] - 2014-01-31 - -### Added - -* Add `Uuid::VALID_PATTERN` constant containing a UUID validation regex pattern - - -## [2.6.1] - 2014-01-27 - -### Fixed - -* Fix bug where `uuid` console application could not find the Composer - autoloader when installed in another project - - -## [2.6.0] - 2014-01-17 - -### Added - -* Introduce `uuid` console application for generating and decoding UUIDs from - CLI (run `./bin/uuid` for details) -* Add `Uuid::getInteger()` to retrieve a `Moontoast\Math\BigNumber` - representation of the 128-bit integer representing the UUID -* Add `Uuid::getHex()` to retrieve the hexadecimal representation of the UUID -* Use `netstat` on Linux to capture the node for a version 1 UUID -* Require moontoast/math as part of the regular package requirements - - -## [2.5.0] - 2013-10-30 - -### Added - -* Use `openssl_random_pseudo_bytes()`, if available, to generate random bytes - - -## [2.4.0] - 2013-07-29 - -### Added - -* Return `null` from `Uuid::getVersion()` if the UUID isn't an RFC 4122 variant -* Support string UUIDs without dashes passed to `Uuid::fromString()` - - -## [2.3.0] - 2013-07-16 - -### Added - -* Support creation of UUIDs from bytes with `Uuid::fromBytes()` - - -## [2.2.0] - 2013-07-04 - -### Added - -* Add `Doctrine\UuidType::requiresSQLCommentHint()` method - - -## [2.1.2] - 2013-07-03 - -### Fixed - -* Fix cases where the system node was coming back with uppercase hexadecimal - digits; this ensures that case in the node is converted to lowercase - - -## [2.1.1] - 2013-04-29 - -### Fixed - -* Fix bug in `Uuid::isValid()` where the NIL UUID was not reported as valid - - -## [2.1.0] - 2013-04-15 - -### Added - -* Allow checking the validity of a UUID through the `Uuid::isValid()` method - - -## [2.0.0] - 2013-02-11 - -### Added - -* Support UUID generation on 32-bit platforms - -### Changed - -* Mark `Uuid` class `final` -* Require moontoast/math on 64-bit platforms for - `Uuid::getLeastSignificantBits()` and `Uuid::getMostSignificantBits()`; the - integers returned by these methods are *unsigned* 64-bit integers and - unsupported even on 64-bit builds of PHP -* Move `UnsupportedOperationException` to the `Exception` subnamespace - - -## [1.1.2] - 2012-11-29 - -### Fixed - -* Relax [Doctrine field type] conversion rules for UUIDs - - -## [1.1.1] - 2012-08-27 - -### Fixed - -* Remove `final` keyword from `Uuid` class - - -## [1.1.0] - 2012-08-06 - -### Added - -* Support ramsey/uuid UUIDs as a Doctrine Database Abstraction Layer (DBAL) - field mapping type - - -## [1.0.0] - 2012-07-19 - -### Added - -* Support generation of version 1, 3, 4, and 5 UUIDs - - -[comb sequential uuids]: http://www.informit.com/articles/article.aspx?p=25862&seqNum=7 -[paragonie/random_compat]: https://github.com/paragonie/random_compat -[collision issue]: https://github.com/ramsey/uuid/issues/80 -[contributor code of conduct]: https://github.com/ramsey/uuid/blob/master/.github/CODE_OF_CONDUCT.md -[pecl libsodium extension]: http://pecl.php.net/package/libsodium -[ircmaxell/random-lib]: https://github.com/ircmaxell/RandomLib -[doctrine field type]: http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html -[ramsey/uuid-doctrine]: https://github.com/ramsey/uuid-doctrine -[ramsey/uuid-console]: https://github.com/ramsey/uuid-console - -[unreleased]: https://github.com/ramsey/uuid/compare/4.1.1...HEAD -[4.1.1]: https://github.com/ramsey/uuid/compare/4.1.0...4.1.1 -[4.1.0]: https://github.com/ramsey/uuid/compare/4.0.1...4.1.0 -[4.0.1]: https://github.com/ramsey/uuid/compare/4.0.0...4.0.1 -[4.0.0]: https://github.com/ramsey/uuid/compare/4.0.0-beta2...4.0.0 -[4.0.0-beta2]: https://github.com/ramsey/uuid/compare/4.0.0-beta1...4.0.0-beta2 -[4.0.0-beta1]: https://github.com/ramsey/uuid/compare/4.0.0-alpha5...4.0.0-beta1 -[4.0.0-alpha5]: https://github.com/ramsey/uuid/compare/4.0.0-alpha4...4.0.0-alpha5 -[4.0.0-alpha4]: https://github.com/ramsey/uuid/compare/4.0.0-alpha3...4.0.0-alpha4 -[4.0.0-alpha3]: https://github.com/ramsey/uuid/compare/4.0.0-alpha2...4.0.0-alpha3 -[4.0.0-alpha2]: https://github.com/ramsey/uuid/compare/4.0.0-alpha1...4.0.0-alpha2 -[4.0.0-alpha1]: https://github.com/ramsey/uuid/compare/3.9.3...4.0.0-alpha1 -[3.9.3]: https://github.com/ramsey/uuid/compare/3.9.2...3.9.3 -[3.9.2]: https://github.com/ramsey/uuid/compare/3.9.1...3.9.2 -[3.9.1]: https://github.com/ramsey/uuid/compare/3.9.0...3.9.1 -[3.9.0]: https://github.com/ramsey/uuid/compare/3.8.0...3.9.0 -[3.8.0]: https://github.com/ramsey/uuid/compare/3.7.3...3.8.0 -[3.7.3]: https://github.com/ramsey/uuid/compare/3.7.2...3.7.3 -[3.7.2]: https://github.com/ramsey/uuid/compare/3.7.1...3.7.2 -[3.7.1]: https://github.com/ramsey/uuid/compare/3.7.0...3.7.1 -[3.7.0]: https://github.com/ramsey/uuid/compare/3.6.1...3.7.0 -[3.6.1]: https://github.com/ramsey/uuid/compare/3.6.0...3.6.1 -[3.6.0]: https://github.com/ramsey/uuid/compare/3.5.2...3.6.0 -[3.5.2]: https://github.com/ramsey/uuid/compare/3.5.1...3.5.2 -[3.5.1]: https://github.com/ramsey/uuid/compare/3.5.0...3.5.1 -[3.5.0]: https://github.com/ramsey/uuid/compare/3.4.1...3.5.0 -[3.4.1]: https://github.com/ramsey/uuid/compare/3.4.0...3.4.1 -[3.4.0]: https://github.com/ramsey/uuid/compare/3.3.0...3.4.0 -[3.3.0]: https://github.com/ramsey/uuid/compare/3.2.0...3.3.0 -[3.2.0]: https://github.com/ramsey/uuid/compare/3.1.0...3.2.0 -[3.1.0]: https://github.com/ramsey/uuid/compare/3.0.1...3.1.0 -[3.0.1]: https://github.com/ramsey/uuid/compare/3.0.0...3.0.1 -[3.0.0]: https://github.com/ramsey/uuid/compare/3.0.0-beta1...3.0.0 -[3.0.0-beta1]: https://github.com/ramsey/uuid/compare/3.0.0-alpha3...3.0.0-beta1 -[3.0.0-alpha3]: https://github.com/ramsey/uuid/compare/3.0.0-alpha2...3.0.0-alpha3 -[3.0.0-alpha2]: https://github.com/ramsey/uuid/compare/3.0.0-alpha1...3.0.0-alpha2 -[3.0.0-alpha1]: https://github.com/ramsey/uuid/compare/2.9.0...3.0.0-alpha1 -[2.9.0]: https://github.com/ramsey/uuid/compare/2.8.4...2.9.0 -[2.8.4]: https://github.com/ramsey/uuid/compare/2.8.3...2.8.4 -[2.8.3]: https://github.com/ramsey/uuid/compare/2.8.2...2.8.3 -[2.8.2]: https://github.com/ramsey/uuid/compare/2.8.1...2.8.2 -[2.8.1]: https://github.com/ramsey/uuid/compare/2.8.0...2.8.1 -[2.8.0]: https://github.com/ramsey/uuid/compare/2.7.4...2.8.0 -[2.7.4]: https://github.com/ramsey/uuid/compare/2.7.3...2.7.4 -[2.7.3]: https://github.com/ramsey/uuid/compare/2.7.2...2.7.3 -[2.7.2]: https://github.com/ramsey/uuid/compare/2.7.1...2.7.2 -[2.7.1]: https://github.com/ramsey/uuid/compare/2.7.0...2.7.1 -[2.7.0]: https://github.com/ramsey/uuid/compare/2.6.1...2.7.0 -[2.6.1]: https://github.com/ramsey/uuid/compare/2.6.0...2.6.1 -[2.6.0]: https://github.com/ramsey/uuid/compare/2.5.0...2.6.0 -[2.5.0]: https://github.com/ramsey/uuid/compare/2.4.0...2.5.0 -[2.4.0]: https://github.com/ramsey/uuid/compare/2.3.0...2.4.0 -[2.3.0]: https://github.com/ramsey/uuid/compare/2.2.0...2.3.0 -[2.2.0]: https://github.com/ramsey/uuid/compare/2.1.2...2.2.0 -[2.1.2]: https://github.com/ramsey/uuid/compare/2.1.1...2.1.2 -[2.1.1]: https://github.com/ramsey/uuid/compare/2.1.0...2.1.1 -[2.1.0]: https://github.com/ramsey/uuid/compare/2.0.0...2.1.0 -[2.0.0]: https://github.com/ramsey/uuid/compare/1.1.2...2.0.0 -[1.1.2]: https://github.com/ramsey/uuid/compare/1.1.1...1.1.2 -[1.1.1]: https://github.com/ramsey/uuid/compare/1.1.0...1.1.1 -[1.1.0]: https://github.com/ramsey/uuid/compare/1.0.0...1.1.0 -[1.0.0]: https://github.com/ramsey/uuid/commits/1.0.0 diff --git a/lib/uuid/LICENSE b/lib/uuid/LICENSE index b2aa4b58..2e8ef166 100644 --- a/lib/uuid/LICENSE +++ b/lib/uuid/LICENSE @@ -1,6 +1,4 @@ -MIT License - -Copyright (c) 2012-2020 Ben Ramsey +Copyright (c) 2012-2022 Ben Ramsey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/lib/uuid/README.md b/lib/uuid/README.md index 0e539e6b..97e81a50 100644 --- a/lib/uuid/README.md +++ b/lib/uuid/README.md @@ -1,24 +1,29 @@ -# ramsey/uuid - -[![Source Code][badge-source]][source] -[![Latest Version][badge-release]][release] -[![Software License][badge-license]][license] -[![PHP Version][badge-php]][php] -[![Build Status][badge-build]][build] -[![Coverage Status][badge-coverage]][coverage] -[![Total Downloads][badge-downloads]][downloads] +

      ramsey/uuid

      + +

      + A PHP library for generating and working with UUIDs. +

      + +

      + Source Code + Download Package + PHP Programming Language + Read License + Build Status + Codecov Code Coverage + Psalm Type Coverage +

      ramsey/uuid is a PHP library for generating and working with universally unique identifiers (UUIDs). -This project adheres to a [Contributor Code of Conduct][conduct]. By -participating in this project and its community, you are expected to uphold this -code. +This project adheres to a [code of conduct](CODE_OF_CONDUCT.md). +By participating in this project and its community, you are expected to +uphold this code. Much inspiration for this library came from the [Java][javauuid] and [Python][pyuuid] UUID libraries. - ## Installation The preferred method of installation is via [Composer][]. Run the following @@ -29,24 +34,38 @@ command to install the package and add it as a requirement to your project's composer require ramsey/uuid ``` - ## Upgrading to Version 4 See the documentation for a thorough upgrade guide: * [Upgrading ramsey/uuid Version 3 to 4](https://uuid.ramsey.dev/en/latest/upgrading/3-to-4.html) - ## Documentation Please see for documentation, tips, examples, and frequently asked questions. - ## Contributing -Contributions are welcome! Please read [CONTRIBUTING.md][] for details. +Contributions are welcome! To contribute, please familiarize yourself with +[CONTRIBUTING.md](CONTRIBUTING.md). +## Coordinated Disclosure + +Keeping user information safe and secure is a top priority, and we welcome the +contribution of external security researchers. If you believe you've found a +security issue in software that is maintained in this repository, please read +[SECURITY.md][] for instructions on submitting a vulnerability report. + +## ramsey/uuid for Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of ramsey/uuid and thousands of other packages are working with +Tidelift to deliver commercial support and maintenance for the open source +packages you use to build your applications. Save time, reduce risk, and improve +code health, while paying the maintainers of the exact packages you use. +[Learn more.](https://tidelift.com/subscription/pkg/packagist-ramsey-uuid?utm_source=undefined&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) ## Copyright and License @@ -54,26 +73,11 @@ The ramsey/uuid library is copyright © [Ben Ramsey](https://benramsey.com/) and licensed for use under the MIT License (MIT). Please see [LICENSE][] for more information. - [rfc4122]: http://tools.ietf.org/html/rfc4122 -[conduct]: https://github.com/ramsey/uuid/blob/master/.github/CODE_OF_CONDUCT.md +[conduct]: https://github.com/ramsey/uuid/blob/main/CODE_OF_CONDUCT.md [javauuid]: http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html [pyuuid]: http://docs.python.org/3/library/uuid.html [composer]: http://getcomposer.org/ -[contributing.md]: https://github.com/ramsey/uuid/blob/master/.github/CONTRIBUTING.md - -[badge-source]: https://img.shields.io/badge/source-ramsey/uuid-blue.svg?style=flat-square -[badge-release]: https://img.shields.io/packagist/v/ramsey/uuid.svg?style=flat-square&label=release -[badge-license]: https://img.shields.io/packagist/l/ramsey/uuid.svg?style=flat-square -[badge-php]: https://img.shields.io/packagist/php-v/ramsey/uuid.svg?style=flat-square -[badge-build]: https://img.shields.io/travis/ramsey/uuid/master.svg?style=flat-square -[badge-coverage]: https://img.shields.io/coveralls/github/ramsey/uuid/master.svg?style=flat-square -[badge-downloads]: https://img.shields.io/packagist/dt/ramsey/uuid.svg?style=flat-square&colorB=mediumvioletred - -[source]: https://github.com/ramsey/uuid -[release]: https://packagist.org/packages/ramsey/uuid -[license]: https://github.com/ramsey/uuid/blob/master/LICENSE -[php]: https://php.net -[build]: https://travis-ci.org/ramsey/uuid -[coverage]: https://coveralls.io/github/ramsey/uuid?branch=master -[downloads]: https://packagist.org/packages/ramsey/uuid +[contributing.md]: https://github.com/ramsey/uuid/blob/main/CONTRIBUTING.md +[security.md]: https://github.com/ramsey/uuid/blob/main/SECURITY.md +[license]: https://github.com/ramsey/uuid/blob/main/LICENSE diff --git a/lib/uuid/composer.json b/lib/uuid/composer.json index 41d500b2..112fabf1 100644 --- a/lib/uuid/composer.json +++ b/lib/uuid/composer.json @@ -1,62 +1,55 @@ { "name": "ramsey/uuid", - "type": "library", "description": "A PHP library for generating and working with universally unique identifiers (UUIDs).", + "license": "MIT", + "type": "library", "keywords": [ "uuid", "identifier", "guid" ], - "homepage": "https://github.com/ramsey/uuid", - "license": "MIT", "require": { - "php": "^7.2 || ^8", + "php": "^8.0", + "ext-ctype": "*", "ext-json": "*", "brick/math": "^0.8 || ^0.9", - "ramsey/collection": "^1.0", - "symfony/polyfill-ctype": "^1.8" + "ramsey/collection": "^1.0" }, "require-dev": { - "codeception/aspect-mock": "^3", - "dealerdirect/phpcodesniffer-composer-installer": "^0.6.2 || ^0.7.0", + "captainhook/captainhook": "^5.10", + "captainhook/plugin-composer": "^5.3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", "doctrine/annotations": "^1.8", - "goaop/framework": "^2", + "ergebnis/composer-normalize": "^2.15", "mockery/mockery": "^1.3", "moontoast/math": "^1.1", "paragonie/random-lib": "^2", + "php-mock/php-mock": "^2.2", "php-mock/php-mock-mockery": "^1.3", - "php-mock/php-mock-phpunit": "^2.5", "php-parallel-lint/php-parallel-lint": "^1.1", - "phpbench/phpbench": "^0.17.1", + "phpbench/phpbench": "^1.0", "phpstan/extension-installer": "^1.0", "phpstan/phpstan": "^0.12", "phpstan/phpstan-mockery": "^0.12", "phpstan/phpstan-phpunit": "^0.12", - "phpunit/phpunit": "^8.5", - "psy/psysh": "^0.10.0", - "slevomat/coding-standard": "^6.0", + "phpunit/phpunit": "^8.5 || ^9", + "slevomat/coding-standard": "^7.0", "squizlabs/php_codesniffer": "^3.5", - "vimeo/psalm": "3.9.4" + "vimeo/psalm": "^4.9" + }, + "replace": { + "rhumsaa/uuid": "self.version" }, "suggest": { "ext-bcmath": "Enables faster math with arbitrary-precision integers using BCMath.", "ext-ctype": "Enables faster processing of character classification using ctype functions.", "ext-gmp": "Enables faster math with arbitrary-precision integers using GMP.", "ext-uuid": "Enables the use of PeclUuidTimeGenerator and PeclUuidRandomGenerator.", - "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type.", - "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter" - }, - "config": { - "sort-packages": true - }, - "extra": { - "branch-alias": { - "dev-master": "4.x-dev" - } - }, - "replace": { - "rhumsaa/uuid": "self.version" + "paragonie/random-lib": "Provides RandomLib for use with the RandomLibAdapter", + "ramsey/uuid-doctrine": "Allows the use of Ramsey\\Uuid\\Uuid as Doctrine field type." }, + "minimum-stability": "dev", + "prefer-stable": true, "autoload": { "psr-4": { "Ramsey\\Uuid\\": "src/" @@ -72,18 +65,38 @@ "Ramsey\\Uuid\\Test\\": "tests/" } }, + "config": { + "allow-plugins": { + "captainhook/plugin-composer": true, + "ergebnis/composer-normalize": true, + "phpstan/extension-installer": true, + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + }, + "extra": { + "captainhook": { + "force-install": true + } + }, "scripts": { + "analyze": [ + "@phpstan", + "@psalm" + ], + "build:clean": "git clean -fX build/", "lint": "parallel-lint src tests", + "lint:paths": "parallel-lint", "phpbench": "phpbench run", "phpcbf": "phpcbf -vpw --cache=build/cache/phpcs.cache", "phpcs": "phpcs --cache=build/cache/phpcs.cache", "phpstan": [ - "phpstan analyse -c tests/phpstan.neon --no-progress", - "phpstan analyse -c tests/phpstan-tests.neon --no-progress" + "phpstan analyse --no-progress", + "phpstan analyse -c phpstan-tests.neon --no-progress" ], - "psalm": "psalm --show-info=false --config=tests/psalm.xml", "phpunit": "phpunit --verbose --colors=always", "phpunit-coverage": "phpunit --verbose --colors=always --coverage-html build/coverage", + "psalm": "psalm --show-info=false --config=psalm.xml", "test": [ "@lint", "@phpbench", @@ -92,10 +105,5 @@ "@psalm", "@phpunit" ] - }, - "support": { - "issues": "https://github.com/ramsey/uuid/issues", - "rss": "https://github.com/ramsey/uuid/releases.atom", - "source": "https://github.com/ramsey/uuid" } } diff --git a/lib/uuid/src/Builder/BuilderCollection.php b/lib/uuid/src/Builder/BuilderCollection.php index b3e5f1dc..9df3110f 100644 --- a/lib/uuid/src/Builder/BuilderCollection.php +++ b/lib/uuid/src/Builder/BuilderCollection.php @@ -15,7 +15,6 @@ namespace Ramsey\Uuid\Builder; use Ramsey\Collection\AbstractCollection; -use Ramsey\Collection\CollectionInterface; use Ramsey\Uuid\Converter\Number\GenericNumberConverter; use Ramsey\Uuid\Converter\Time\GenericTimeConverter; use Ramsey\Uuid\Converter\Time\PhpTimeConverter; @@ -27,8 +26,15 @@ /** * A collection of UuidBuilderInterface objects + * + * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from + * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced + * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use + * more generic types like `iterable` instead. + * + * @extends AbstractCollection */ -class BuilderCollection extends AbstractCollection implements CollectionInterface +class BuilderCollection extends AbstractCollection { public function getType(): string { @@ -52,10 +58,11 @@ public function getIterator(): Traversable * a UuidInterface instance * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress RedundantConditionGivenDocblockType */ public function unserialize($serialized): void { - /** @var mixed[] $data */ + /** @var array $data */ $data = unserialize($serialized, [ 'allowed_classes' => [ BrickMathCalculator::class, @@ -68,6 +75,11 @@ public function unserialize($serialized): void ], ]); - $this->data = $data; + $this->data = array_filter( + $data, + function ($unserialized): bool { + return $unserialized instanceof UuidBuilderInterface; + } + ); } } diff --git a/lib/uuid/src/Builder/DefaultUuidBuilder.php b/lib/uuid/src/Builder/DefaultUuidBuilder.php index 2af4e867..7c4a6f83 100644 --- a/lib/uuid/src/Builder/DefaultUuidBuilder.php +++ b/lib/uuid/src/Builder/DefaultUuidBuilder.php @@ -21,6 +21,6 @@ * * @psalm-immutable */ -class DefaultUuidBuilder extends Rfc4122UuidBuilder implements UuidBuilderInterface +class DefaultUuidBuilder extends Rfc4122UuidBuilder { } diff --git a/lib/uuid/src/Builder/FallbackBuilder.php b/lib/uuid/src/Builder/FallbackBuilder.php index cfd4665a..8ab438a1 100644 --- a/lib/uuid/src/Builder/FallbackBuilder.php +++ b/lib/uuid/src/Builder/FallbackBuilder.php @@ -28,14 +28,14 @@ class FallbackBuilder implements UuidBuilderInterface { /** - * @var BuilderCollection + * @var iterable */ private $builders; /** - * @param BuilderCollection $builders An array of UUID builders + * @param iterable $builders An array of UUID builders */ - public function __construct(BuilderCollection $builders) + public function __construct(iterable $builders) { $this->builders = $builders; } @@ -55,7 +55,6 @@ public function build(CodecInterface $codec, string $bytes): UuidInterface { $lastBuilderException = null; - /** @var UuidBuilderInterface $builder */ foreach ($this->builders as $builder) { try { return $builder->build($codec, $bytes); diff --git a/lib/uuid/src/Codec/OrderedTimeCodec.php b/lib/uuid/src/Codec/OrderedTimeCodec.php index fe9f57c7..0798ebc4 100644 --- a/lib/uuid/src/Codec/OrderedTimeCodec.php +++ b/lib/uuid/src/Codec/OrderedTimeCodec.php @@ -67,6 +67,7 @@ public function encodeBinary(UuidInterface $uuid): string $bytes = $uuid->getFields()->getBytes(); + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $bytes[6] . $bytes[7] . $bytes[4] . $bytes[5] . $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3] diff --git a/lib/uuid/src/Codec/StringCodec.php b/lib/uuid/src/Codec/StringCodec.php index fff13bd8..58c9f580 100644 --- a/lib/uuid/src/Codec/StringCodec.php +++ b/lib/uuid/src/Codec/StringCodec.php @@ -75,6 +75,7 @@ public function encode(UuidInterface $uuid): string */ public function encodeBinary(UuidInterface $uuid): string { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $uuid->getFields()->getBytes(); } diff --git a/lib/uuid/src/Codec/TimestampFirstCombCodec.php b/lib/uuid/src/Codec/TimestampFirstCombCodec.php index 06ce38fb..0e0042d0 100644 --- a/lib/uuid/src/Codec/TimestampFirstCombCodec.php +++ b/lib/uuid/src/Codec/TimestampFirstCombCodec.php @@ -76,6 +76,7 @@ public function encode(UuidInterface $uuid): string */ public function encodeBinary(UuidInterface $uuid): string { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $this->swapBytes($uuid->getFields()->getBytes()); } diff --git a/lib/uuid/src/Converter/Number/GenericNumberConverter.php b/lib/uuid/src/Converter/Number/GenericNumberConverter.php index c85bc3a7..501eac0f 100644 --- a/lib/uuid/src/Converter/Number/GenericNumberConverter.php +++ b/lib/uuid/src/Converter/Number/GenericNumberConverter.php @@ -19,7 +19,7 @@ use Ramsey\Uuid\Type\Integer as IntegerObject; /** - * GenericNumberConverter uses the provided calculate to convert decimal + * GenericNumberConverter uses the provided calculator to convert decimal * numbers to and from hexadecimal values * * @psalm-immutable @@ -57,6 +57,7 @@ public function fromHex(string $hex): string */ public function toHex(string $number): string { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return $this->calculator->toBase(new IntegerObject($number), 16); } } diff --git a/lib/uuid/src/Converter/Time/PhpTimeConverter.php b/lib/uuid/src/Converter/Time/PhpTimeConverter.php index 52963fed..538d2f2f 100644 --- a/lib/uuid/src/Converter/Time/PhpTimeConverter.php +++ b/lib/uuid/src/Converter/Time/PhpTimeConverter.php @@ -111,7 +111,7 @@ public function calculateTime(string $seconds, string $microseconds): Hexadecima ); } - return new Hexadecimal(str_pad(dechex((int) $uuidTime), 16, '0', STR_PAD_LEFT)); + return new Hexadecimal(str_pad(dechex($uuidTime), 16, '0', STR_PAD_LEFT)); } public function convertTime(Hexadecimal $uuidTimestamp): Time diff --git a/lib/uuid/src/Exception/BuilderNotFoundException.php b/lib/uuid/src/Exception/BuilderNotFoundException.php index c0854d25..220ffedb 100644 --- a/lib/uuid/src/Exception/BuilderNotFoundException.php +++ b/lib/uuid/src/Exception/BuilderNotFoundException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that no suitable builder could be found */ -class BuilderNotFoundException extends PhpRuntimeException +class BuilderNotFoundException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/DateTimeException.php b/lib/uuid/src/Exception/DateTimeException.php index dbc48404..5f0e658b 100644 --- a/lib/uuid/src/Exception/DateTimeException.php +++ b/lib/uuid/src/Exception/DateTimeException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the PHP DateTime extension encountered an exception/error */ -class DateTimeException extends PhpRuntimeException +class DateTimeException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/DceSecurityException.php b/lib/uuid/src/Exception/DceSecurityException.php index a65f80cd..e6d80013 100644 --- a/lib/uuid/src/Exception/DceSecurityException.php +++ b/lib/uuid/src/Exception/DceSecurityException.php @@ -20,6 +20,6 @@ * Thrown to indicate an exception occurred while dealing with DCE Security * (version 2) UUIDs */ -class DceSecurityException extends PhpRuntimeException +class DceSecurityException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/InvalidArgumentException.php b/lib/uuid/src/Exception/InvalidArgumentException.php index 08bbb802..2a1fa3ac 100644 --- a/lib/uuid/src/Exception/InvalidArgumentException.php +++ b/lib/uuid/src/Exception/InvalidArgumentException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the argument received is not valid */ -class InvalidArgumentException extends PhpInvalidArgumentException +class InvalidArgumentException extends PhpInvalidArgumentException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/InvalidBytesException.php b/lib/uuid/src/Exception/InvalidBytesException.php index b20be3de..1c94f659 100644 --- a/lib/uuid/src/Exception/InvalidBytesException.php +++ b/lib/uuid/src/Exception/InvalidBytesException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the bytes being operated on are invalid in some way */ -class InvalidBytesException extends PhpRuntimeException +class InvalidBytesException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/InvalidUuidStringException.php b/lib/uuid/src/Exception/InvalidUuidStringException.php index 24f42c64..6d975816 100644 --- a/lib/uuid/src/Exception/InvalidUuidStringException.php +++ b/lib/uuid/src/Exception/InvalidUuidStringException.php @@ -20,6 +20,6 @@ * The InvalidArgumentException that this extends is the ramsey/uuid version * of this exception. It exists in the same namespace as this class. */ -class InvalidUuidStringException extends InvalidArgumentException +class InvalidUuidStringException extends InvalidArgumentException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/NameException.php b/lib/uuid/src/Exception/NameException.php index 54d32ec3..fd96a1fa 100644 --- a/lib/uuid/src/Exception/NameException.php +++ b/lib/uuid/src/Exception/NameException.php @@ -20,6 +20,6 @@ * Thrown to indicate that an error occurred while attempting to hash a * namespace and name */ -class NameException extends PhpRuntimeException +class NameException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/NodeException.php b/lib/uuid/src/Exception/NodeException.php index 21b6d180..0dbdd50b 100644 --- a/lib/uuid/src/Exception/NodeException.php +++ b/lib/uuid/src/Exception/NodeException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that attempting to fetch or create a node ID encountered an error */ -class NodeException extends PhpRuntimeException +class NodeException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/RandomSourceException.php b/lib/uuid/src/Exception/RandomSourceException.php index 0c3e4f52..a44dd34a 100644 --- a/lib/uuid/src/Exception/RandomSourceException.php +++ b/lib/uuid/src/Exception/RandomSourceException.php @@ -22,6 +22,6 @@ * This exception is used mostly to indicate that random_bytes() or random_int() * threw an exception. However, it may be used for other sources of random data. */ -class RandomSourceException extends PhpRuntimeException +class RandomSourceException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/TimeSourceException.php b/lib/uuid/src/Exception/TimeSourceException.php index accd37f8..fc9cf36b 100644 --- a/lib/uuid/src/Exception/TimeSourceException.php +++ b/lib/uuid/src/Exception/TimeSourceException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the source of time encountered an error */ -class TimeSourceException extends PhpRuntimeException +class TimeSourceException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/UnableToBuildUuidException.php b/lib/uuid/src/Exception/UnableToBuildUuidException.php index da964903..5ba26d8d 100644 --- a/lib/uuid/src/Exception/UnableToBuildUuidException.php +++ b/lib/uuid/src/Exception/UnableToBuildUuidException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate a builder is unable to build a UUID */ -class UnableToBuildUuidException extends PhpRuntimeException +class UnableToBuildUuidException extends PhpRuntimeException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/UnsupportedOperationException.php b/lib/uuid/src/Exception/UnsupportedOperationException.php index e6391b03..e1b3eda1 100644 --- a/lib/uuid/src/Exception/UnsupportedOperationException.php +++ b/lib/uuid/src/Exception/UnsupportedOperationException.php @@ -19,6 +19,6 @@ /** * Thrown to indicate that the requested operation is not supported */ -class UnsupportedOperationException extends PhpLogicException +class UnsupportedOperationException extends PhpLogicException implements UuidExceptionInterface { } diff --git a/lib/uuid/src/Exception/UuidExceptionInterface.php b/lib/uuid/src/Exception/UuidExceptionInterface.php new file mode 100644 index 00000000..a2f1c103 --- /dev/null +++ b/lib/uuid/src/Exception/UuidExceptionInterface.php @@ -0,0 +1,21 @@ + + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + +namespace Ramsey\Uuid\Exception; + +use Throwable; + +interface UuidExceptionInterface extends Throwable +{ +} diff --git a/lib/uuid/src/FeatureSet.php b/lib/uuid/src/FeatureSet.php index 4531a6d7..66836660 100644 --- a/lib/uuid/src/FeatureSet.php +++ b/lib/uuid/src/FeatureSet.php @@ -14,7 +14,6 @@ namespace Ramsey\Uuid; -use Ramsey\Uuid\Builder\BuilderCollection; use Ramsey\Uuid\Builder\FallbackBuilder; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; @@ -43,7 +42,6 @@ use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider; use Ramsey\Uuid\Provider\DceSecurityProviderInterface; use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; -use Ramsey\Uuid\Provider\Node\NodeProviderCollection; use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Provider\Node\SystemNodeProvider; use Ramsey\Uuid\Provider\NodeProviderInterface; @@ -274,6 +272,7 @@ public function setCalculator(CalculatorInterface $calculator): void $this->numberConverter = $this->buildNumberConverter($calculator); $this->timeConverter = $this->buildTimeConverter($calculator); + /** @psalm-suppress RedundantPropertyInitializationCheck */ if (isset($this->timeProvider)) { $this->timeGenerator = $this->buildTimeGenerator($this->timeProvider); } @@ -349,10 +348,10 @@ private function buildNodeProvider(): NodeProviderInterface return new RandomNodeProvider(); } - return new FallbackNodeProvider(new NodeProviderCollection([ + return new FallbackNodeProvider([ new SystemNodeProvider(), new RandomNodeProvider(), - ])); + ]); } /** @@ -431,11 +430,10 @@ private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface return new GuidBuilder($this->numberConverter, $this->timeConverter); } - /** @psalm-suppress ImpureArgument */ - return new FallbackBuilder(new BuilderCollection([ + return new FallbackBuilder([ new Rfc4122UuidBuilder($this->numberConverter, $this->timeConverter), new NonstandardUuidBuilder($this->numberConverter, $this->timeConverter), - ])); + ]); } /** diff --git a/lib/uuid/src/Fields/SerializableFieldsTrait.php b/lib/uuid/src/Fields/SerializableFieldsTrait.php index 4ae90be2..16e6525d 100644 --- a/lib/uuid/src/Fields/SerializableFieldsTrait.php +++ b/lib/uuid/src/Fields/SerializableFieldsTrait.php @@ -14,7 +14,10 @@ namespace Ramsey\Uuid\Fields; +use ValueError; + use function base64_decode; +use function sprintf; use function strlen; /** @@ -42,12 +45,21 @@ public function serialize(): string return $this->getBytes(); } + /** + * @return array{bytes: string} + */ + public function __serialize(): array + { + return ['bytes' => $this->getBytes()]; + } + /** * Constructs the object from a serialized string representation * * @param string $serialized The serialized string representation of the object * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress UnusedMethodCall */ public function unserialize($serialized): void { @@ -57,4 +69,18 @@ public function unserialize($serialized): void $this->__construct(base64_decode($serialized)); } } + + /** + * @param array{bytes: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['bytes'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['bytes']); + } } diff --git a/lib/uuid/src/Generator/CombGenerator.php b/lib/uuid/src/Generator/CombGenerator.php index 88ae6ea2..25b7988e 100644 --- a/lib/uuid/src/Generator/CombGenerator.php +++ b/lib/uuid/src/Generator/CombGenerator.php @@ -87,7 +87,7 @@ public function __construct( */ public function generate(int $length): string { - if ($length < self::TIMESTAMP_BYTES || $length < 0) { + if ($length < self::TIMESTAMP_BYTES) { throw new InvalidArgumentException( 'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES ); @@ -107,7 +107,7 @@ public function generate(int $length): string return (string) hex2bin( str_pad( - bin2hex((string) $hash), + bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0' ) diff --git a/lib/uuid/src/Generator/DceSecurityGenerator.php b/lib/uuid/src/Generator/DceSecurityGenerator.php index a3f07f2f..aca8c5db 100644 --- a/lib/uuid/src/Generator/DceSecurityGenerator.php +++ b/lib/uuid/src/Generator/DceSecurityGenerator.php @@ -138,7 +138,7 @@ public function generate( } $domainByte = pack('n', $localDomain)[1]; - $identifierBytes = hex2bin(str_pad($identifierHex, 8, '0', STR_PAD_LEFT)); + $identifierBytes = (string) hex2bin(str_pad($identifierHex, 8, '0', STR_PAD_LEFT)); if ($node instanceof Hexadecimal) { $node = $node->toString(); @@ -149,7 +149,6 @@ public function generate( $clockSeq = $clockSeq << 8; } - /** @var string $bytes */ $bytes = $this->timeGenerator->generate($node, $clockSeq); // Replace bytes in the time-based UUID with DCE Security values. diff --git a/lib/uuid/src/Generator/DefaultNameGenerator.php b/lib/uuid/src/Generator/DefaultNameGenerator.php index 270e8fbe..7303e9fa 100644 --- a/lib/uuid/src/Generator/DefaultNameGenerator.php +++ b/lib/uuid/src/Generator/DefaultNameGenerator.php @@ -16,6 +16,7 @@ use Ramsey\Uuid\Exception\NameException; use Ramsey\Uuid\UuidInterface; +use ValueError; use function hash; @@ -28,8 +29,12 @@ class DefaultNameGenerator implements NameGeneratorInterface /** @psalm-pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string { - /** @var string|bool $bytes */ - $bytes = @hash($hashAlgorithm, $ns->getBytes() . $name, true); + try { + /** @var string|bool $bytes */ + $bytes = @hash($hashAlgorithm, $ns->getBytes() . $name, true); + } catch (ValueError $e) { + $bytes = false; // keep same behavior than PHP 7 + } if ($bytes === false) { throw new NameException(sprintf( diff --git a/lib/uuid/src/Generator/PeclUuidNameGenerator.php b/lib/uuid/src/Generator/PeclUuidNameGenerator.php index 93b78687..3780c5c6 100644 --- a/lib/uuid/src/Generator/PeclUuidNameGenerator.php +++ b/lib/uuid/src/Generator/PeclUuidNameGenerator.php @@ -35,11 +35,11 @@ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm) { switch ($hashAlgorithm) { case 'md5': - $uuid = (string) uuid_generate_md5($ns->toString(), $name); + $uuid = uuid_generate_md5($ns->toString(), $name); break; case 'sha1': - $uuid = (string) uuid_generate_sha1($ns->toString(), $name); + $uuid = uuid_generate_sha1($ns->toString(), $name); break; default: @@ -49,6 +49,6 @@ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm) )); } - return (string) uuid_parse($uuid); + return uuid_parse($uuid); } } diff --git a/lib/uuid/src/Generator/PeclUuidRandomGenerator.php b/lib/uuid/src/Generator/PeclUuidRandomGenerator.php index df750f6a..07c47d26 100644 --- a/lib/uuid/src/Generator/PeclUuidRandomGenerator.php +++ b/lib/uuid/src/Generator/PeclUuidRandomGenerator.php @@ -14,6 +14,9 @@ namespace Ramsey\Uuid\Generator; +use function uuid_create; +use function uuid_parse; + use const UUID_TYPE_RANDOM; /** diff --git a/lib/uuid/src/Generator/PeclUuidTimeGenerator.php b/lib/uuid/src/Generator/PeclUuidTimeGenerator.php index 903798dd..e01f44e5 100644 --- a/lib/uuid/src/Generator/PeclUuidTimeGenerator.php +++ b/lib/uuid/src/Generator/PeclUuidTimeGenerator.php @@ -14,6 +14,9 @@ namespace Ramsey\Uuid\Generator; +use function uuid_create; +use function uuid_parse; + use const UUID_TYPE_TIME; /** diff --git a/lib/uuid/src/Generator/RandomBytesGenerator.php b/lib/uuid/src/Generator/RandomBytesGenerator.php index e6e9a199..12edb96a 100644 --- a/lib/uuid/src/Generator/RandomBytesGenerator.php +++ b/lib/uuid/src/Generator/RandomBytesGenerator.php @@ -15,6 +15,7 @@ namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Exception\RandomSourceException; +use Throwable; /** * RandomBytesGenerator generates strings of random binary data using the @@ -33,7 +34,7 @@ public function generate(int $length): string { try { return random_bytes($length); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { throw new RandomSourceException( $exception->getMessage(), (int) $exception->getCode(), diff --git a/lib/uuid/src/Generator/RandomLibAdapter.php b/lib/uuid/src/Generator/RandomLibAdapter.php index 24ed5692..793ccd5a 100644 --- a/lib/uuid/src/Generator/RandomLibAdapter.php +++ b/lib/uuid/src/Generator/RandomLibAdapter.php @@ -21,6 +21,10 @@ * RandomLibAdapter generates strings of random binary data using the * paragonie/random-lib library * + * @deprecated This class will be removed in 5.0.0. Use the default + * RandomBytesGenerator or implement your own generator that implements + * RandomGeneratorInterface. + * * @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib */ class RandomLibAdapter implements RandomGeneratorInterface diff --git a/lib/uuid/src/Guid/Fields.php b/lib/uuid/src/Guid/Fields.php index 49db4ed2..d8a1a2b1 100644 --- a/lib/uuid/src/Guid/Fields.php +++ b/lib/uuid/src/Guid/Fields.php @@ -94,6 +94,7 @@ public function getBytes(): string public function getTimeLow(): Hexadecimal { // Swap the bytes from little endian to network byte order. + /** @var array $hex */ $hex = unpack( 'H*', pack( @@ -109,6 +110,7 @@ public function getTimeLow(): Hexadecimal public function getTimeMid(): Hexadecimal { // Swap the bytes from little endian to network byte order. + /** @var array $hex */ $hex = unpack( 'H*', pack( @@ -123,6 +125,7 @@ public function getTimeMid(): Hexadecimal public function getTimeHiAndVersion(): Hexadecimal { // Swap the bytes from little endian to network byte order. + /** @var array $hex */ $hex = unpack( 'H*', pack( @@ -172,6 +175,7 @@ public function getVersion(): ?int return null; } + /** @var array $parts */ $parts = unpack('n*', $this->bytes); return ((int) $parts[4] >> 4) & 0x00f; diff --git a/lib/uuid/src/Guid/Guid.php b/lib/uuid/src/Guid/Guid.php index 08a00695..b3ed096a 100644 --- a/lib/uuid/src/Guid/Guid.php +++ b/lib/uuid/src/Guid/Guid.php @@ -18,7 +18,6 @@ use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Uuid; -use Ramsey\Uuid\UuidInterface; /** * Guid represents a UUID with "native" (little-endian) byte order @@ -49,7 +48,7 @@ * * @psalm-immutable */ -final class Guid extends Uuid implements UuidInterface +final class Guid extends Uuid { public function __construct( Fields $fields, diff --git a/lib/uuid/src/Lazy/LazyUuidFromString.php b/lib/uuid/src/Lazy/LazyUuidFromString.php index 3d4ddcb2..8ba75796 100644 --- a/lib/uuid/src/Lazy/LazyUuidFromString.php +++ b/lib/uuid/src/Lazy/LazyUuidFromString.php @@ -7,7 +7,7 @@ * file that was distributed with this source code. * * @copyright Copyright (c) Ben Ramsey - * @license http://opensource.org/licenses/MIT MIT + * @license http://opensource.org/licenses/MIT MIT */ declare(strict_types=1); @@ -24,10 +24,12 @@ use Ramsey\Uuid\Type\Integer as IntegerObject; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidInterface; +use ValueError; use function assert; use function bin2hex; use function hex2bin; +use function sprintf; use function str_replace; use function substr; @@ -90,6 +92,16 @@ public function serialize(): string return $this->uuid; } + /** + * @return array{string: string} + * + * @psalm-return array{string: non-empty-string} + */ + public function __serialize(): array + { + return ['string' => $this->uuid]; + } + /** * {@inheritDoc} * @@ -102,6 +114,22 @@ public function unserialize($serialized): void $this->uuid = $serialized; } + /** + * @param array{string: string} $data + * + * @psalm-param array{string: non-empty-string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } + /** @psalm-suppress DeprecatedMethod */ public function getNumberConverter(): NumberConverterInterface { @@ -242,6 +270,7 @@ public function equals(?object $other): bool */ public function getBytes(): string { + /** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */ return (string) hex2bin(str_replace('-', '', $this->uuid)); } @@ -497,7 +526,7 @@ public function getTimeMid(): string public function getTimestamp(): string { $instance = ($this->unwrapped ?? $this->unwrap()); - $fields = $instance->getFields(); + $fields = $instance->getFields(); if ($fields->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); diff --git a/lib/uuid/src/Nonstandard/Uuid.php b/lib/uuid/src/Nonstandard/Uuid.php index 5a7a3334..715f8255 100644 --- a/lib/uuid/src/Nonstandard/Uuid.php +++ b/lib/uuid/src/Nonstandard/Uuid.php @@ -18,14 +18,13 @@ use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Uuid as BaseUuid; -use Ramsey\Uuid\UuidInterface; /** * Nonstandard\Uuid is a UUID that doesn't conform to RFC 4122 * * @psalm-immutable */ -final class Uuid extends BaseUuid implements UuidInterface +final class Uuid extends BaseUuid { public function __construct( Fields $fields, diff --git a/lib/uuid/src/Provider/Dce/SystemDceSecurityProvider.php b/lib/uuid/src/Provider/Dce/SystemDceSecurityProvider.php index 1a1f4cf2..7ff40764 100644 --- a/lib/uuid/src/Provider/Dce/SystemDceSecurityProvider.php +++ b/lib/uuid/src/Provider/Dce/SystemDceSecurityProvider.php @@ -177,8 +177,7 @@ private function getWindowsUid(): string return ''; } - /** @var string $sid */ - $sid = str_getcsv(trim($response))[1] ?? ''; + $sid = str_getcsv(trim((string) $response))[1] ?? ''; if (($lastHyphen = strrpos($sid, '-')) === false) { return ''; @@ -207,7 +206,7 @@ private function getWindowsGid(): string } /** @var string[] $userGroups */ - $userGroups = preg_split('/\s{2,}/', $response, -1, PREG_SPLIT_NO_EMPTY); + $userGroups = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); $firstGroup = trim($userGroups[1] ?? '', "* \t\n\r\0\x0B"); @@ -222,7 +221,7 @@ private function getWindowsGid(): string } /** @var string[] $userGroup */ - $userGroup = preg_split('/\s{2,}/', $response, -1, PREG_SPLIT_NO_EMPTY); + $userGroup = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY); $sid = $userGroup[1] ?? ''; @@ -230,6 +229,6 @@ private function getWindowsGid(): string return ''; } - return trim((string) substr($sid, $lastHyphen + 1)); + return trim(substr($sid, $lastHyphen + 1)); } } diff --git a/lib/uuid/src/Provider/Node/FallbackNodeProvider.php b/lib/uuid/src/Provider/Node/FallbackNodeProvider.php index f6e5e406..fe890cc4 100644 --- a/lib/uuid/src/Provider/Node/FallbackNodeProvider.php +++ b/lib/uuid/src/Provider/Node/FallbackNodeProvider.php @@ -25,14 +25,14 @@ class FallbackNodeProvider implements NodeProviderInterface { /** - * @var NodeProviderCollection + * @var iterable */ private $nodeProviders; /** - * @param NodeProviderCollection $providers Array of node providers + * @param iterable $providers Array of node providers */ - public function __construct(NodeProviderCollection $providers) + public function __construct(iterable $providers) { $this->nodeProviders = $providers; } @@ -41,7 +41,6 @@ public function getNode(): Hexadecimal { $lastProviderException = null; - /** @var NodeProviderInterface $provider */ foreach ($this->nodeProviders as $provider) { try { return $provider->getNode(); diff --git a/lib/uuid/src/Provider/Node/NodeProviderCollection.php b/lib/uuid/src/Provider/Node/NodeProviderCollection.php index 89d09178..1b979fae 100644 --- a/lib/uuid/src/Provider/Node/NodeProviderCollection.php +++ b/lib/uuid/src/Provider/Node/NodeProviderCollection.php @@ -15,14 +15,20 @@ namespace Ramsey\Uuid\Provider\Node; use Ramsey\Collection\AbstractCollection; -use Ramsey\Collection\CollectionInterface; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; /** * A collection of NodeProviderInterface objects + * + * @deprecated this class has been deprecated, and will be removed in 5.0.0. The use-case for this class comes from + * a pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced + * at runtime: that is no longer necessary, now that you can safely verify your code to be correct, and use + * more generic types like `iterable` instead. + * + * @extends AbstractCollection */ -class NodeProviderCollection extends AbstractCollection implements CollectionInterface +class NodeProviderCollection extends AbstractCollection { public function getType(): string { @@ -36,10 +42,11 @@ public function getType(): string * a UuidInterface instance * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress RedundantConditionGivenDocblockType */ public function unserialize($serialized): void { - /** @var mixed[] $data */ + /** @var array $data */ $data = unserialize($serialized, [ 'allowed_classes' => [ Hexadecimal::class, @@ -49,6 +56,11 @@ public function unserialize($serialized): void ], ]); - $this->data = $data; + $this->data = array_filter( + $data, + function ($unserialized): bool { + return $unserialized instanceof NodeProviderInterface; + } + ); } } diff --git a/lib/uuid/src/Provider/Node/RandomNodeProvider.php b/lib/uuid/src/Provider/Node/RandomNodeProvider.php index 266c0b73..76141361 100644 --- a/lib/uuid/src/Provider/Node/RandomNodeProvider.php +++ b/lib/uuid/src/Provider/Node/RandomNodeProvider.php @@ -17,6 +17,7 @@ use Ramsey\Uuid\Exception\RandomSourceException; use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Type\Hexadecimal; +use Throwable; use function bin2hex; use function dechex; @@ -38,7 +39,7 @@ public function getNode(): Hexadecimal { try { $nodeBytes = random_bytes(6); - } catch (\Throwable $exception) { + } catch (Throwable $exception) { throw new RandomSourceException( $exception->getMessage(), (int) $exception->getCode(), diff --git a/lib/uuid/src/Provider/Node/SystemNodeProvider.php b/lib/uuid/src/Provider/Node/SystemNodeProvider.php index 8234abae..d512f22a 100644 --- a/lib/uuid/src/Provider/Node/SystemNodeProvider.php +++ b/lib/uuid/src/Provider/Node/SystemNodeProvider.php @@ -132,7 +132,7 @@ protected function getIfconfig(): string $node = $matches[1][0] ?? ''; } - return (string) $node; + return $node; } /** diff --git a/lib/uuid/src/Rfc4122/Fields.php b/lib/uuid/src/Rfc4122/Fields.php index 0989d842..2ccc20bb 100644 --- a/lib/uuid/src/Rfc4122/Fields.php +++ b/lib/uuid/src/Rfc4122/Fields.php @@ -177,6 +177,7 @@ public function getVersion(): ?int return null; } + /** @var array $parts */ $parts = unpack('n*', $this->bytes); return (int) $parts[4] >> 12; diff --git a/lib/uuid/src/Rfc4122/VariantTrait.php b/lib/uuid/src/Rfc4122/VariantTrait.php index c32a8ce8..4c981658 100644 --- a/lib/uuid/src/Rfc4122/VariantTrait.php +++ b/lib/uuid/src/Rfc4122/VariantTrait.php @@ -58,6 +58,7 @@ public function getVariant(): int throw new InvalidBytesException('Invalid number of bytes'); } + /** @var array $parts */ $parts = unpack('n*', $this->getBytes()); // $parts[5] is a 16-bit, unsigned integer containing the variant bits diff --git a/lib/uuid/src/Type/Decimal.php b/lib/uuid/src/Type/Decimal.php index 5ba88653..10f93845 100644 --- a/lib/uuid/src/Type/Decimal.php +++ b/lib/uuid/src/Type/Decimal.php @@ -15,8 +15,10 @@ namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; use function is_numeric; +use function sprintf; /** * A value object representing a decimal @@ -98,15 +100,38 @@ public function serialize(): string return $this->toString(); } + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + /** * Constructs the object from a serialized string representation * * @param string $serialized The serialized string representation of the object * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress UnusedMethodCall */ public function unserialize($serialized): void { $this->__construct($serialized); } + + /** + * @param array{string: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } } diff --git a/lib/uuid/src/Type/Hexadecimal.php b/lib/uuid/src/Type/Hexadecimal.php index 11450186..88adc2e7 100644 --- a/lib/uuid/src/Type/Hexadecimal.php +++ b/lib/uuid/src/Type/Hexadecimal.php @@ -15,8 +15,10 @@ namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; use function ctype_xdigit; +use function sprintf; use function strpos; use function strtolower; use function substr; @@ -77,15 +79,38 @@ public function serialize(): string return $this->toString(); } + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + /** * Constructs the object from a serialized string representation * * @param string $serialized The serialized string representation of the object * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress UnusedMethodCall */ public function unserialize($serialized): void { $this->__construct($serialized); } + + /** + * @param array{string: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } } diff --git a/lib/uuid/src/Type/Integer.php b/lib/uuid/src/Type/Integer.php index 05d420a8..7690f6cd 100644 --- a/lib/uuid/src/Type/Integer.php +++ b/lib/uuid/src/Type/Integer.php @@ -15,9 +15,11 @@ namespace Ramsey\Uuid\Type; use Ramsey\Uuid\Exception\InvalidArgumentException; +use ValueError; use function ctype_digit; use function ltrim; +use function sprintf; use function strpos; use function substr; @@ -36,7 +38,7 @@ final class Integer implements NumberInterface { /** - * @var string + * @psalm-var numeric-string */ private $value; @@ -80,7 +82,10 @@ public function __construct($value) $this->isNegative = true; } - $this->value = $value; + /** @psalm-var numeric-string $numericValue */ + $numericValue = $value; + + $this->value = $numericValue; } public function isNegative(): bool @@ -88,6 +93,9 @@ public function isNegative(): bool return $this->isNegative; } + /** + * @psalm-return numeric-string + */ public function toString(): string { return $this->value; @@ -108,15 +116,38 @@ public function serialize(): string return $this->toString(); } + /** + * @return array{string: string} + */ + public function __serialize(): array + { + return ['string' => $this->toString()]; + } + /** * Constructs the object from a serialized string representation * * @param string $serialized The serialized string representation of the object * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress UnusedMethodCall */ public function unserialize($serialized): void { $this->__construct($serialized); } + + /** + * @param array{string: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['string'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['string']); + } } diff --git a/lib/uuid/src/Type/Time.php b/lib/uuid/src/Type/Time.php index f6a140f0..dd1b8bc2 100644 --- a/lib/uuid/src/Type/Time.php +++ b/lib/uuid/src/Type/Time.php @@ -16,10 +16,12 @@ use Ramsey\Uuid\Exception\UnsupportedOperationException; use Ramsey\Uuid\Type\Integer as IntegerObject; +use ValueError; use stdClass; use function json_decode; use function json_encode; +use function sprintf; /** * A value object representing a timestamp @@ -88,12 +90,24 @@ public function serialize(): string return (string) json_encode($this); } + /** + * @return array{seconds: string, microseconds: string} + */ + public function __serialize(): array + { + return [ + 'seconds' => $this->getSeconds()->toString(), + 'microseconds' => $this->getMicroseconds()->toString(), + ]; + } + /** * Constructs the object from a serialized string representation * * @param string $serialized The serialized string representation of the object * * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint + * @psalm-suppress UnusedMethodCall */ public function unserialize($serialized): void { @@ -108,4 +122,18 @@ public function unserialize($serialized): void $this->__construct($time->seconds, $time->microseconds); } + + /** + * @param array{seconds: string, microseconds: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['seconds']) || !isset($data['microseconds'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->__construct($data['seconds'], $data['microseconds']); + } } diff --git a/lib/uuid/src/Uuid.php b/lib/uuid/src/Uuid.php index 762dfdba..5f0922b9 100644 --- a/lib/uuid/src/Uuid.php +++ b/lib/uuid/src/Uuid.php @@ -23,9 +23,12 @@ use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface; use Ramsey\Uuid\Type\Hexadecimal; use Ramsey\Uuid\Type\Integer as IntegerObject; +use ValueError; +use function assert; use function bin2hex; use function preg_match; +use function sprintf; use function str_replace; use function strcmp; use function strlen; @@ -238,9 +241,9 @@ class Uuid implements UuidInterface * ``` * use Ramsey\Uuid\Uuid; * - * $timeBasedUuid = Uuid::uuid1(); - * $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/'); - * $randomUuid = Uuid::uuid4(); + * $timeBasedUuid = Uuid::uuid1(); + * $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/'); + * $randomUuid = Uuid::uuid4(); * $namespaceSha1Uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'http://php.net/'); * ``` * @@ -285,7 +288,15 @@ public function jsonSerialize(): string */ public function serialize(): string { - return $this->getBytes(); + return $this->getFields()->getBytes(); + } + + /** + * @return array{bytes: string} + */ + public function __serialize(): array + { + return ['bytes' => $this->serialize()]; } /** @@ -312,6 +323,20 @@ public function unserialize($serialized): void $this->timeConverter = $uuid->timeConverter; } + /** + * @param array{bytes: string} $data + */ + public function __unserialize(array $data): void + { + // @codeCoverageIgnoreStart + if (!isset($data['bytes'])) { + throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__)); + } + // @codeCoverageIgnoreEnd + + $this->unserialize($data['bytes']); + } + public function compareTo(UuidInterface $other): int { $compare = strcmp($this->toString(), $other->toString()); @@ -451,8 +476,11 @@ public static function fromBytes(string $bytes): UuidInterface */ public static function fromString(string $uuid): UuidInterface { + $uuid = strtolower($uuid); if (! self::$factoryReplaced && preg_match(LazyUuidFromString::VALID_REGEX, $uuid) === 1) { - return new LazyUuidFromString(strtolower($uuid)); + assert($uuid !== ''); + + return new LazyUuidFromString($uuid); } return self::getFactory()->fromString($uuid); diff --git a/lib/uuid/src/UuidFactory.php b/lib/uuid/src/UuidFactory.php index feddef88..6f2cea06 100644 --- a/lib/uuid/src/UuidFactory.php +++ b/lib/uuid/src/UuidFactory.php @@ -471,10 +471,14 @@ private function uuidFromNsAndName($ns, string $name, int $version, string $hash */ private function uuidFromBytesAndVersion(string $bytes, int $version): UuidInterface { - $timeHi = (int) unpack('n*', substr($bytes, 6, 2))[1]; + /** @var array $unpackedTime */ + $unpackedTime = unpack('n*', substr($bytes, 6, 2)); + $timeHi = (int) $unpackedTime[1]; $timeHiAndVersion = pack('n*', BinaryUtils::applyVersion($timeHi, $version)); - $clockSeqHi = (int) unpack('n*', substr($bytes, 8, 2))[1]; + /** @var array $unpackedClockSeq */ + $unpackedClockSeq = unpack('n*', substr($bytes, 8, 2)); + $clockSeqHi = (int) $unpackedClockSeq[1]; $clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi)); $bytes = substr_replace($bytes, $timeHiAndVersion, 6, 2); diff --git a/lib/uuid/src/functions.php b/lib/uuid/src/functions.php index 7b29ec4b..f5df1488 100644 --- a/lib/uuid/src/functions.php +++ b/lib/uuid/src/functions.php @@ -29,7 +29,7 @@ * could arise when the clock is set backwards in time or if the node ID * changes * - * @return string Version 1 UUID as a string + * @return non-empty-string Version 1 UUID as a string */ function v1($node = null, ?int $clockSeq = null): string { @@ -52,7 +52,7 @@ function v1($node = null, ?int $clockSeq = null): string * that could arise when the clock is set backwards in time or if the * node ID changes * - * @return string Version 2 UUID as a string + * @return non-empty-string Version 2 UUID as a string */ function v2( int $localDomain, @@ -69,7 +69,10 @@ function v2( * * @param string|UuidInterface $ns The namespace (must be a valid UUID) * - * @return string Version 3 UUID as a string + * @return non-empty-string Version 3 UUID as a string + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners */ function v3($ns, string $name): string { @@ -79,7 +82,7 @@ function v3($ns, string $name): string /** * Returns a version 4 (random) UUID * - * @return string Version 4 UUID as a string + * @return non-empty-string Version 4 UUID as a string */ function v4(): string { @@ -92,7 +95,10 @@ function v4(): string * * @param string|UuidInterface $ns The namespace (must be a valid UUID) * - * @return string Version 5 UUID as a string + * @return non-empty-string Version 5 UUID as a string + * + * @psalm-pure note: changing the internal factory is an edge case not covered by purity invariants, + * but under constant factory setups, this method operates in functionally pure manners */ function v5($ns, string $name): string { @@ -109,7 +115,7 @@ function v5($ns, string $name): string * could arise when the clock is set backwards in time or if the node ID * changes * - * @return string Version 6 UUID as a string + * @return non-empty-string Version 6 UUID as a string */ function v6(?Hexadecimal $node = null, ?int $clockSeq = null): string { diff --git a/plugins/README.md b/plugins/README.md index abd96e8a..f7cebcda 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -36,6 +36,28 @@ $plugin = \SLiMS\Plugins::getInstance(); $plugin->registerMenu('bibliography', 'Label & Barcode', __DIR__ . '/index.php'); ``` +#### Group Menu Plugin +Submenu yang ditambahkan dari plugin dapat dikelempokan. +Berikut ini contoh untuk meregistrasikannya, pada contoh kali ini juga akan ditampilkan bagaimana meregistrasikan plugin dengan `static method` +``` +use \SLiMS\Plugins; + +Plugins::group('Nama Group', function() { + Plugins::menu('nama_module', 'nama menu 1', '/path/dari/endpoint/pluginya/1.php'); + Plugins::menu('nama_module', 'nama menu 2', '/path/dari/endpoint/pluginya/2.php'); + Plugins::menu('nama_module', 'nama menu 3', '/path/dari/endpoint/pluginya/3.php'); +}); +``` + +Kelompok menu-menu ini juga dapat kita letakan sebelum atau setelah menu bawaan SLiMS. +Sebagai contoh kita akan meletakan contoh menu plugin diatas setelah kelompok `Eksemplar` pada module `Bibliography` + +``` +Plugins::group('Nama Group', function() { + ... +})->after(__('ITEMS')); +``` + #### Hooking Plugin Jenis plugin ini akan berjalan saat sebuah fitur berada pada state tertentu. Berikut ini contoh untuk meregistrasikannya: diff --git a/plugins/read_counter/migration/1_CreateReadCounterTable.php b/plugins/read_counter/migration/1_CreateReadCounterTable.php index c3b74e61..7060775e 100644 --- a/plugins/read_counter/migration/1_CreateReadCounterTable.php +++ b/plugins/read_counter/migration/1_CreateReadCounterTable.php @@ -20,6 +20,9 @@ * */ +use SLiMS\Table\Schema; +use SLiMS\Table\Blueprint; + class CreateReadCounterTable extends \SLiMS\Migration\Migration { @@ -30,13 +33,15 @@ class CreateReadCounterTable extends \SLiMS\Migration\Migration */ function up() { - \SLiMS\DB::getInstance()->query("CREATE TABLE `read_counter` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `item_code` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL, - `title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, - `created_at` datetime NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"); + Schema::create('read_counter', function(Blueprint $table){ + $table->engine = 'MyISAM'; + $table->charset = 'utf8mb4'; + $table->collation = 'utf8mb4_unicode_ci'; + $table->autoIncrement('id'); + $table->string('item_code', 20)->notNull(); + $table->string('title', 255)->notNull(); + $table->datetime('created_at')->notNull(); + }); } /** @@ -46,6 +51,6 @@ function up() */ function down() { - \SLiMS\DB::getInstance()->query("DROP TABLE `read_counter`;"); + Schema::drop('read_counter'); } } \ No newline at end of file diff --git a/plugins/read_counter/migration/2_AddUIDColumn.php b/plugins/read_counter/migration/2_AddUIDColumn.php index 50f8a6b4..8d10156d 100644 --- a/plugins/read_counter/migration/2_AddUIDColumn.php +++ b/plugins/read_counter/migration/2_AddUIDColumn.php @@ -20,6 +20,9 @@ * */ +use SLiMS\Table\Schema; +use SLiMS\Table\Blueprint; + class AddUIDColumn extends \SLiMS\Migration\Migration { @@ -30,7 +33,9 @@ class AddUIDColumn extends \SLiMS\Migration\Migration */ function up() { - \SLiMS\DB::getInstance()->query("ALTER TABLE read_counter ADD COLUMN uid int(11) NULL AFTER created_at;"); + Schema::table('read_counter', function(Blueprint $table){ + $table->number('uid', 11)->nullable()->after('created_at')->add(); + }); } /** @@ -40,6 +45,8 @@ function up() */ function down() { - \SLiMS\DB::getInstance()->query("ALTER TABLE read_counter DROP COLUMN uid;"); + Schema::table('read_counter', function(Blueprint $table){ + $table->drop('uid'); + }); } } \ No newline at end of file diff --git a/simbio2/simbio_GUI/form_maker/simbio_form_element.inc.php b/simbio2/simbio_GUI/form_maker/simbio_form_element.inc.php index 9c254c03..967489b2 100755 --- a/simbio2/simbio_GUI/form_maker/simbio_form_element.inc.php +++ b/simbio2/simbio_GUI/form_maker/simbio_form_element.inc.php @@ -131,7 +131,7 @@ public function out() $_buffer .= ''."\n"; } else { - $_buffer .= ''."\n"; } } diff --git a/simbio2/simbio_GUI/form_maker/simbio_form_table.inc.php b/simbio2/simbio_GUI/form_maker/simbio_form_table.inc.php index 06f3c902..3bb22c38 100755 --- a/simbio2/simbio_GUI/form_maker/simbio_form_table.inc.php +++ b/simbio2/simbio_GUI/form_maker/simbio_form_table.inc.php @@ -84,7 +84,7 @@ public function printOut() $_row_num = 0; foreach ($this->elements as $row) { $_form_element = $row['element']->out(); - if ($_form_element_info = trim($row['info'])) { + if ($_form_element_info = trim($row['info']??'')) { $_form_element .= '
      '.$_form_element_info.'
      '; } // append row diff --git a/simbio2/simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php b/simbio2/simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php index cc30269b..d9506281 100755 --- a/simbio2/simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php +++ b/simbio2/simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php @@ -79,7 +79,7 @@ public function printOut() $_row_num = 0; foreach ($this->elements as $row) { $_form_element = $row['element']->out(); - if ($_form_element_info = trim($row['info'])) { + if ($_form_element_info = trim($row['info']??'')) { $_form_element .= '
      '.$_form_element_info.'
      '; } // append row diff --git a/simbio2/simbio_GUI/table/simbio_table.inc.php b/simbio2/simbio_GUI/table/simbio_table.inc.php index 4098e57f..bf530c5a 100755 --- a/simbio2/simbio_GUI/table/simbio_table.inc.php +++ b/simbio2/simbio_GUI/table/simbio_table.inc.php @@ -199,7 +199,7 @@ public function getColumnContent($int_row, $int_column, $str_column_content) * @param string $str_column_attr * @return void */ - public function setCellAttr($int_row = 0, $int_column = null, $str_column_attr) + public function setCellAttr($int_row = 0, $int_column = null, $str_column_attr = null) { if (is_null($int_column)) { $this->row_attr[$int_row] = $str_column_attr; diff --git a/simbio2/simbio_UTILS/simbio_tokenizecql.inc.php b/simbio2/simbio_UTILS/simbio_tokenizecql.inc.php index c5a0e56f..474c2194 100755 --- a/simbio2/simbio_UTILS/simbio_tokenizecql.inc.php +++ b/simbio2/simbio_UTILS/simbio_tokenizecql.inc.php @@ -34,7 +34,7 @@ * * @param string $str_query * @param array $arr_stop_words - * @return string + * @return array **/ function simbio_tokenizeCQL($str_query, $arr_searcheable_fields, $arr_stop_words = array(), $int_max_words = 20) { diff --git a/sysconfig.inc.php b/sysconfig.inc.php index e276f823..a7575194 100755 --- a/sysconfig.inc.php +++ b/sysconfig.inc.php @@ -27,12 +27,15 @@ die("can not access this file directly"); } +// Environment config +require __DIR__ . '/config/sysconfig.env.inc.php'; + /* * Set to development or production * * In production mode, the system error message will be disabled */ -define('ENVIRONMENT', 'production'); +define('ENVIRONMENT', $Environment); switch (ENVIRONMENT) { case 'development': @@ -49,10 +52,6 @@ exit(1); // EXIT_ERROR } -// require composer library -if (file_exists(realpath(dirname(__FILE__)) . '/vendor/autoload.php')) require 'vendor/autoload.php'; -require 'lib/autoload.php'; - // use httpOnly for cookie @ini_set( 'session.cookie_httponly', true ); // check if safe mode is on @@ -60,10 +59,6 @@ define('SENAYAN_IN_SAFE_MODE', 1); } -// set default timezone -// for a list of timezone, please see PHP Manual at "List of Supported Timezones" section -@date_default_timezone_set('Asia/Jakarta'); - // senayan version define('SENAYAN_VERSION', 'SLiMS 9 (Bulian)'); define('SENAYAN_VERSION_TAG', 'v9.4.2'); @@ -149,6 +144,9 @@ define('COMMAND_SUCCESS', 0); define('COMMAND_FAILED', 2); +// require composer library +if (file_exists(SB . 'vendor/autoload.php')) require SB . 'vendor/autoload.php'; +require LIB . 'autoload.php'; // simbio main class inclusion require SIMBIO.'simbio.inc.php'; // simbio security class @@ -506,6 +504,7 @@ /** * Mailing Settings */ +$sysconf['mail']['debug'] = 0; $sysconf['mail']['SMTPSecure'] = 'ssl'; // ssl or tls $sysconf['mail']['enable'] = true; $sysconf['mail']['server'] = 'ssl://smtp.gmail.com:465'; // SMTP server @@ -518,6 +517,9 @@ $sysconf['mail']['reply_to'] = &$sysconf['mail']['from']; $sysconf['mail']['reply_to_name'] = &$sysconf['mail']['from_name']; +if (file_exists(SB.'config'.DS.'sysconfig.mail.inc.php')) { + include SB.'config'.DS.'sysconfig.mail.inc.php'; +} /** * Maximum biblio mark for member */ @@ -753,7 +755,12 @@ $sysconf['load_balanced_env'] = false; // load helper -require_once "lib/helper.inc.php"; +require_once LIB . "helper.inc.php"; + +// set default timezone +// for a list of timezone, please see PHP Manual at "List of Supported Timezones" section +// https://www.php.net/manual/en/timezones.php +@date_default_timezone_set(config('timezone', 'Asia/Jakarta')); // load all Plugins \SLiMS\Plugins::getInstance()->loadPlugins(); diff --git a/template/akasia-dz/biblio_list_template.php b/template/akasia-dz/biblio_list_template.php index cb8d0ed7..970ab035 100644 --- a/template/akasia-dz/biblio_list_template.php +++ b/template/akasia-dz/biblio_list_template.php @@ -89,7 +89,10 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret if (!empty($biblio_detail['image']) && !defined('LIGHTWEIGHT_MODE')) { $biblio_detail['image'] = urlencode($biblio_detail['image']); $images_loc = 'images/docs/'.$biblio_detail['image']; - if ($sysconf['tg']['type'] == 'minigalnano') { + if($biblio_detail['image'] == '' || $biblio_detail['image'] == NULL){ + $images_loc = 'images/default/image.png'; + } + if ($sysconf['tg']['type'] == 'minigalnano') { $thumb_url = './lib/minigalnano/createthumb.php?filename='.urlencode($images_loc).'&width=120'; $image_cover = ''.$title.''; } diff --git a/template/akasia-dz/partials/meta.php b/template/akasia-dz/partials/meta.php index 5d8e2c64..a642db56 100644 --- a/template/akasia-dz/partials/meta.php +++ b/template/akasia-dz/partials/meta.php @@ -78,6 +78,11 @@ + diff --git a/template/akasia/biblio_list_template.php b/template/akasia/biblio_list_template.php index 1c679e32..261743cc 100644 --- a/template/akasia/biblio_list_template.php +++ b/template/akasia/biblio_list_template.php @@ -90,6 +90,9 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret if (!empty($biblio_detail['image']) && !defined('LIGHTWEIGHT_MODE')) { $biblio_detail['image'] = urlencode($biblio_detail['image']); $images_loc = 'images/docs/'.$biblio_detail['image']; + if($biblio_detail['image'] == '' || $biblio_detail['image'] == NULL){ + $images_loc = 'images/default/image.png'; + } if ($sysconf['tg']['type'] == 'minigalnano') { $thumb_url = './lib/minigalnano/createthumb.php?filename='.urlencode($images_loc).'&width=120'; $image_cover = ''.$title.''; diff --git a/template/akasia/partials/meta.php b/template/akasia/partials/meta.php index e751ea25..7f482f7f 100644 --- a/template/akasia/partials/meta.php +++ b/template/akasia/partials/meta.php @@ -78,6 +78,11 @@ + diff --git a/template/akasia/style.css b/template/akasia/style.css index d4f49e7e..b639046d 100644 --- a/template/akasia/style.css +++ b/template/akasia/style.css @@ -2189,6 +2189,7 @@ keyframes coverUp 100% { } #visitorCounterPhoto { margin: 0; + width: 100px; } /* Social Icon ================================ */ diff --git a/template/default/biblio_list_template.php b/template/default/biblio_list_template.php index 253be2d3..70fa8684 100644 --- a/template/default/biblio_list_template.php +++ b/template/default/biblio_list_template.php @@ -50,6 +50,9 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret // image thumbnail $images_loc = 'images/docs/'.$biblio_detail['image']; + if($biblio_detail['image'] == '' || $biblio_detail['image'] == NULL){ + $images_loc = 'images/default/image.png'; + } $thumb_url = './lib/minigalnano/createthumb.php?filename='.urlencode($images_loc).'&width=120'; // notes @@ -61,7 +64,7 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret $custom_field = '
      '; foreach ($settings['custom_fields'] as $field => $field_opts) { if ($field_opts[0] == 1) { - $custom_field .= '
      '.$field_opts[1].'
      '.(trim($biblio_detail[$field]) !== '' ? $biblio_detail[$field] : '-').'
      '; + $custom_field .= '
      '.$field_opts[1].'
      '.(trim($biblio_detail[$field]??'') !== '' ? $biblio_detail[$field] : '-').'
      '; $i++; } } @@ -117,6 +120,7 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret $output .= '
      '; // -- close card-body pt-3 pb-2 px-1 $output .= '
  • '; // -- close card availability $output .= ''.__('View Detail').''; + $output .= ''.__('MARC Download').''; $output .= ''.__('Cite').''; $output .= '
    '; // -- close col-2 $output .= '
    '; // -- close row @@ -136,12 +140,12 @@ function getNotes($dbs, $biblio_id) { $query = $dbs->query('SELECT notes FROM biblio WHERE biblio_id = ' . $biblio_id); $data = $query->fetch_row(); - return addEllipsis($data[0], 200); + return addEllipsis($data[0], 400); } function addEllipsis($string, $length, $end='…') { - if (strlen($string) > $length) + if (strlen($string??'') > $length) { $length -= strlen($end); $string = substr($string, 0, $length); diff --git a/template/default/parts/header.php b/template/default/parts/header.php index 027817aa..3700d78f 100644 --- a/template/default/parts/header.php +++ b/template/default/parts/header.php @@ -95,6 +95,11 @@ + diff --git a/template/default/visitor_template.php b/template/default/visitor_template.php index 1f57dd1f..426d03e5 100644 --- a/template/default/visitor_template.php +++ b/template/default/visitor_template.php @@ -62,7 +62,6 @@

    -

    @@ -98,7 +97,8 @@ this.image = './images/persons/photo.png' }, getQuotes: function() { - axios.get('https://api.quotable.io/random') + // Alternative Free Quotes API: https://api.quotable.io/random + axios.get('https://kutipan.herokuapp.com/') .then(res => { this.quotes = res.data }) @@ -130,8 +130,8 @@ headers: {'Content-Type': 'multipart/form-data' } }) .then(res => { - this.textInfo = res.data - this.image = `./images/persons/member_${this.memberId}.jpg` + this.textInfo = res.data.message + this.image = `./images/persons/${res.data.image}` this.textToSpeech(this.textInfo.replace(/(<([^>]+)>)/ig, '')) diff --git a/template/lightweight/biblio_list_template.php b/template/lightweight/biblio_list_template.php index cb8d0ed7..0405ae67 100644 --- a/template/lightweight/biblio_list_template.php +++ b/template/lightweight/biblio_list_template.php @@ -89,6 +89,9 @@ function biblio_list_format($dbs, $biblio_detail, $n, $settings = array(), &$ret if (!empty($biblio_detail['image']) && !defined('LIGHTWEIGHT_MODE')) { $biblio_detail['image'] = urlencode($biblio_detail['image']); $images_loc = 'images/docs/'.$biblio_detail['image']; + if($biblio_detail['image'] == '' || $biblio_detail['image'] == NULL){ + $images_loc = 'images/default/image.png'; + } if ($sysconf['tg']['type'] == 'minigalnano') { $thumb_url = './lib/minigalnano/createthumb.php?filename='.urlencode($images_loc).'&width=120'; $image_cover = ''.$title.''; diff --git a/template/lightweight/partials/meta.php b/template/lightweight/partials/meta.php index c0411179..e58db038 100644 --- a/template/lightweight/partials/meta.php +++ b/template/lightweight/partials/meta.php @@ -81,6 +81,11 @@ --> +