repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Proprietary.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Proprietary.php
<?php /** * Module defines proprietary tags and attributes in HTML. * @warning If this module is enabled, standards-compliance is off! */ class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule { /** * @type string */ public $name = 'Proprietary'; /** * @param HTMLPurifier_Config $config */ public function setup($config) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Target.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Target.php
<?php /** * XHTML 1.1 Target Module, defines target attribute in link elements. */ class HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule { /** * @type string */ public $name = 'Target'; /** * @param HTMLPurifier_Config $config */ public function setup($config) { $elements = array('a'); foreach ($elements as $name) { $e = $this->addBlankElement($name); $e->attr = array( 'target' => new HTMLPurifier_AttrDef_HTML_FrameTarget() ); } } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/TargetNoreferrer.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/TargetNoreferrer.php
<?php /** * Module adds the target-based noreferrer attribute transformation to a tags. It * is enabled by HTML.TargetNoreferrer */ class HTMLPurifier_HTMLModule_TargetNoreferrer extends HTMLPurifier_HTMLModule { /** * @type string */ public $name = 'TargetNoreferrer'; /** * @param HTMLPurifier_Config $config */ public function setup($config) { $a = $this->addBlankElement('a'); $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetNoreferrer(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/XHTMLAndHTML4.php
<?php class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy { /** * @return array */ public function makeFixes() { $r = array(); // == deprecated tag transforms =================================== $r['font'] = new HTMLPurifier_TagTransform_Font(); $r['menu'] = new HTMLPurifier_TagTransform_Simple('ul'); $r['dir'] = new HTMLPurifier_TagTransform_Simple('ul'); $r['center'] = new HTMLPurifier_TagTransform_Simple('div', 'text-align:center;'); $r['u'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;'); $r['s'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;'); $r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;'); // == deprecated attribute transforms ============================= $r['caption@align'] = new HTMLPurifier_AttrTransform_EnumToCSS( 'align', array( // we're following IE's behavior, not Firefox's, due // to the fact that no one supports caption-side:right, // W3C included (with CSS 2.1). This is a slightly // unreasonable attribute! 'left' => 'text-align:left;', 'right' => 'text-align:right;', 'top' => 'caption-side:top;', 'bottom' => 'caption-side:bottom;' // not supported by IE ) ); // @align for img ------------------------------------------------- $r['img@align'] = new HTMLPurifier_AttrTransform_EnumToCSS( 'align', array( 'left' => 'float:left;', 'right' => 'float:right;', 'top' => 'vertical-align:top;', 'middle' => 'vertical-align:middle;', 'bottom' => 'vertical-align:baseline;', ) ); // @align for table ----------------------------------------------- $r['table@align'] = new HTMLPurifier_AttrTransform_EnumToCSS( 'align', array( 'left' => 'float:left;', 'center' => 'margin-left:auto;margin-right:auto;', 'right' => 'float:right;' ) ); // @align for hr ----------------------------------------------- $r['hr@align'] = new HTMLPurifier_AttrTransform_EnumToCSS( 'align', array( // we use both text-align and margin because these work // for different browsers (IE and Firefox, respectively) // and the melange makes for a pretty cross-compatible // solution 'left' => 'margin-left:0;margin-right:auto;text-align:left;', 'center' => 'margin-left:auto;margin-right:auto;text-align:center;', 'right' => 'margin-left:auto;margin-right:0;text-align:right;' ) ); // @align for h1, h2, h3, h4, h5, h6, p, div ---------------------- // {{{ $align_lookup = array(); $align_values = array('left', 'right', 'center', 'justify'); foreach ($align_values as $v) { $align_lookup[$v] = "text-align:$v;"; } // }}} $r['h1@align'] = $r['h2@align'] = $r['h3@align'] = $r['h4@align'] = $r['h5@align'] = $r['h6@align'] = $r['p@align'] = $r['div@align'] = new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup); // @bgcolor for table, tr, td, th --------------------------------- $r['table@bgcolor'] = $r['tr@bgcolor'] = $r['td@bgcolor'] = $r['th@bgcolor'] = new HTMLPurifier_AttrTransform_BgColor(); // @border for img ------------------------------------------------ $r['img@border'] = new HTMLPurifier_AttrTransform_Border(); // @clear for br -------------------------------------------------- $r['br@clear'] = new HTMLPurifier_AttrTransform_EnumToCSS( 'clear', array( 'left' => 'clear:left;', 'right' => 'clear:right;', 'all' => 'clear:both;', 'none' => 'clear:none;', ) ); // @height for td, th --------------------------------------------- $r['td@height'] = $r['th@height'] = new HTMLPurifier_AttrTransform_Length('height'); // @hspace for img ------------------------------------------------ $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace'); // @noshade for hr ------------------------------------------------ // this transformation is not precise but often good enough. // different browsers use different styles to designate noshade $r['hr@noshade'] = new HTMLPurifier_AttrTransform_BoolToCSS( 'noshade', 'color:#808080;background-color:#808080;border:0;' ); // @nowrap for td, th --------------------------------------------- $r['td@nowrap'] = $r['th@nowrap'] = new HTMLPurifier_AttrTransform_BoolToCSS( 'nowrap', 'white-space:nowrap;' ); // @size for hr -------------------------------------------------- $r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height'); // @type for li, ol, ul ------------------------------------------- // {{{ $ul_types = array( 'disc' => 'list-style-type:disc;', 'square' => 'list-style-type:square;', 'circle' => 'list-style-type:circle;' ); $ol_types = array( '1' => 'list-style-type:decimal;', 'i' => 'list-style-type:lower-roman;', 'I' => 'list-style-type:upper-roman;', 'a' => 'list-style-type:lower-alpha;', 'A' => 'list-style-type:upper-alpha;' ); $li_types = $ul_types + $ol_types; // }}} $r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types); $r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true); $r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true); // @vspace for img ------------------------------------------------ $r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace'); // @width for hr, td, th ------------------------------------------ $r['td@width'] = $r['th@width'] = $r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width'); return $r; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Strict.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Strict.php
<?php class HTMLPurifier_HTMLModule_Tidy_Strict extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 { /** * @type string */ public $name = 'Tidy_Strict'; /** * @type string */ public $defaultLevel = 'light'; /** * @return array */ public function makeFixes() { $r = parent::makeFixes(); $r['blockquote#content_model_type'] = 'strictblockquote'; return $r; } /** * @type bool */ public $defines_child_def = true; /** * @param HTMLPurifier_ElementDef $def * @return HTMLPurifier_ChildDef_StrictBlockquote */ public function getChildDef($def) { if ($def->content_model_type != 'strictblockquote') { return parent::getChildDef($def); } return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model); } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Name.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Name.php
<?php /** * Name is deprecated, but allowed in strict doctypes, so onl */ class HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy { /** * @type string */ public $name = 'Tidy_Name'; /** * @type string */ public $defaultLevel = 'heavy'; /** * @return array */ public function makeFixes() { $r = array(); // @name for img, a ----------------------------------------------- // Technically, it's allowed even on strict, so we allow authors to use // it. However, it's deprecated in future versions of XHTML. $r['img@name'] = $r['a@name'] = new HTMLPurifier_AttrTransform_Name(); return $r; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/XHTML.php
<?php class HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy { /** * @type string */ public $name = 'Tidy_XHTML'; /** * @type string */ public $defaultLevel = 'medium'; /** * @return array */ public function makeFixes() { $r = array(); $r['@lang'] = new HTMLPurifier_AttrTransform_Lang(); return $r; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Transitional.php
<?php class HTMLPurifier_HTMLModule_Tidy_Transitional extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 { /** * @type string */ public $name = 'Tidy_Transitional'; /** * @type string */ public $defaultLevel = 'heavy'; } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/HTMLModule/Tidy/Proprietary.php
<?php class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy { /** * @type string */ public $name = 'Tidy_Proprietary'; /** * @type string */ public $defaultLevel = 'light'; /** * @return array */ public function makeFixes() { $r = array(); $r['table@background'] = new HTMLPurifier_AttrTransform_Background(); $r['td@background'] = new HTMLPurifier_AttrTransform_Background(); $r['th@background'] = new HTMLPurifier_AttrTransform_Background(); $r['tr@background'] = new HTMLPurifier_AttrTransform_Background(); $r['thead@background'] = new HTMLPurifier_AttrTransform_Background(); $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background(); $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background(); $r['table@height'] = new HTMLPurifier_AttrTransform_Length('height'); return $r; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Clone.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Clone.php
<?php /** * Dummy AttrDef that mimics another AttrDef, BUT it generates clones * with make. */ class HTMLPurifier_AttrDef_Clone extends HTMLPurifier_AttrDef { /** * What we're cloning. * @type HTMLPurifier_AttrDef */ protected $clone; /** * @param HTMLPurifier_AttrDef $clone */ public function __construct($clone) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Enum.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Enum.php
<?php // Enum = Enumerated /** * Validates a keyword against a list of valid values. * @warning The case-insensitive compare of this function uses PHP's * built-in strtolower and ctype_lower functions, which may * cause problems with international comparisons */ class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef { /** * Lookup table of valid values. * @type array * @todo Make protected */ public $valid_values = array(); /** * Bool indicating whether or not enumeration is case sensitive. * @note In general this is always case insensitive. */ protected $case_sensitive = false; // values according to W3C spec /** * @param array $valid_values List of valid values * @param bool $case_sensitive Whether or not case sensitive */ public function __construct($valid_values = array(), $case_sensitive = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Text.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Text.php
<?php /** * Validates arbitrary text according to the HTML spec. */ class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { return $this->parseCDATA($string); } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI.php
<?php /** * Validates a URI as defined by RFC 3986. * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme */ class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_URIParser */ protected $parser; /** * @type bool */ protected $embedsResource; /** * @param bool $embeds_resource Does the URI here result in an extra HTTP request? */ public function __construct($embeds_resource = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Lang.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Lang.php
<?php /** * Validates the HTML attribute lang, effectively a language code. * @note Built according to RFC 3066, which obsoleted RFC 1766 */ class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef { /** * @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) { return false; } $subtags = explode('-', $string); $num_subtags = count($subtags); if ($num_subtags == 0) { // sanity check return false; } // process primary subtag : $subtags[0] $length = strlen($subtags[0]); switch ($length) { case 0: return false; case 1: if (!($subtags[0] == 'x' || $subtags[0] == 'i')) { return false; } break; case 2: case 3: if (!ctype_alpha($subtags[0])) { return false; } elseif (!ctype_lower($subtags[0])) { $subtags[0] = strtolower($subtags[0]); } break; default: return false; } $new_string = $subtags[0]; if ($num_subtags == 1) { return $new_string; } // process second subtag : $subtags[1] $length = strlen($subtags[1]); if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Integer.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Integer.php
<?php /** * Validates an integer. * @note While this class was modeled off the CSS definition, no currently * allowed CSS uses this type. The properties that do are: widows, * orphans, z-index, counter-increment, counter-reset. Some of the * HTML attributes, however, find use for a non-negative version of this. */ class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef { /** * Whether or not negative values are allowed. * @type bool */ protected $negative = true; /** * Whether or not zero is allowed. * @type bool */ protected $zero = true; /** * Whether or not positive values are allowed. * @type bool */ protected $positive = true; /** * @param $negative Bool indicating whether or not negative values are allowed * @param $zero Bool indicating whether or not zero is allowed * @param $positive Bool indicating whether or not positive values are allowed */ public function __construct($negative = true, $zero = true, $positive = true) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Switch.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/Switch.php
<?php /** * Decorator that, depending on a token, switches between two definitions. */ class HTMLPurifier_AttrDef_Switch { /** * @type string */ protected $tag; /** * @type HTMLPurifier_AttrDef */ protected $withTag; /** * @type HTMLPurifier_AttrDef */ protected $withoutTag; /** * @param string $tag Tag name to switch upon * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token */ public function __construct($tag, $with_tag, $without_tag) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS.php
<?php /** * Validates the HTML attribute style, otherwise known as CSS. * @note We don't implement the whole CSS specification, so it might be * difficult to reuse this component in the context of validating * actual stylesheet declarations. * @note If we were really serious about validating the CSS, we would * tokenize the styles and then parse the tokens. Obviously, we * are not doing that. Doing that could seriously harm performance, * but would make these components a lot more viable for a CSS * filtering solution. */ class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef { /** * @param string $css * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($css, $config, $context) { $css = $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv6.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv6.php
<?php /** * Validates an IPv6 address. * @author Feyd @ forums.devnetwork.net (public domain) * @note This function requires brackets to have been removed from address * in URI. */ class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4 { /** * @param string $aIP * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($aIP, $config, $context) { if (!$this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email.php
<?php abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef { /** * Unpacks a mailbox into its display-name and address * @param string $string * @return mixed */ public function unpack($string) { // needs to be implemented } } // sub-implementations // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv4.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/IPv4.php
<?php /** * Validates an IPv4 address * @author Feyd @ forums.devnetwork.net (public domain) */ class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef { /** * IPv4 regex, protected so that IPv6 can reuse it. * @type string */ protected $ip4; /** * @param string $aIP * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($aIP, $config, $context) { if (!$this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Host.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Host.php
<?php /** * Validates a host according to the IPv4, IPv6 and DNS (future) specifications. */ class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef { /** * IPv4 sub-validator. * @type HTMLPurifier_AttrDef_URI_IPv4 */ protected $ipv4; /** * IPv6 sub-validator. * @type HTMLPurifier_AttrDef_URI_IPv6 */ protected $ipv6; public function __construct() { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/URI/Email/SimpleCheck.php
<?php /** * Primitive email validation class based on the regexp found at * http://www.regular-expressions.info/email.html */ class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { // no support for named mailboxes i.e. "Bob <bob@example.com>" // 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/FontFamily.php
<?php /** * Validates a font family list according to CSS spec */ class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef { protected $mask = null; public function __construct() { $this->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 // <http://ja.wikipedia.org/wiki/MS_明朝>. See // the CSS3 spec for more examples: // <http://www.w3.org/TR/2011/WD-css3-fonts-20110324/localizedfamilynames.png> // You can see live samples of these on the Internet: // <http://www.google.co.jp/search?q=font-family+MS+明朝|ゴシック> // 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Number.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Number.php
<?php /** * Validates a number as defined by the CSS spec. */ class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef { /** * Indicates whether or not only positive values are allowed. * @type bool */ protected $non_negative = false; /** * @param bool $non_negative indicates whether negatives are forbidden */ public function __construct($non_negative = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Font.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Font.php
<?php /** * Validates shorthand CSS property font. */ class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef { /** * Local copy of validators * @type HTMLPurifier_AttrDef[] * @note If we moved specific CSS property definitions to their own * classes instead of having them be assembled at run time by * CSSDefinition, this wouldn't be necessary. We'd instantiate * our own copies. */ protected $info = array(); /** * @param HTMLPurifier_Config $config */ public function __construct($config) { $def = $config->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Composite.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Composite.php
<?php /** * Allows multiple validators to attempt to validate attribute. * * Composite is just what it sounds like: a composite of many validators. * This means that multiple HTMLPurifier_AttrDef objects will have a whack * at the string. If one of them passes, that's what is returned. This is * especially useful for CSS values, which often are a choice between * an enumerated set of predefined values or a flexible data type. */ class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef { /** * List of objects that may process strings. * @type HTMLPurifier_AttrDef[] * @todo Make protected */ public $defs; /** * @param HTMLPurifier_AttrDef[] $defs List of HTMLPurifier_AttrDef objects */ public function __construct($defs) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/TextDecoration.php
<?php /** * Validates the value for the CSS property text-decoration * @note This class could be generalized into a version that acts sort of * like Enum except you can compound the allowed values. */ class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { static $allowed_values = array( 'line-through' => 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/AlphaValue.php
<?php class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number { public function __construct() { parent::__construct(false); // opacity is non-negative, but we will clamp it } /** * @param string $number * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return string */ public function validate($number, $config, $context) { $result = parent::validate($number, $config, $context); if ($result === false) { return $result; } $float = (float)$result; if ($float < 0.0) { $result = '0'; } if ($float > 1.0) { $result = '1'; } return $result; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/URI.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/URI.php
<?php /** * Validates a URI in CSS syntax, which uses url('http://example.com') * @note While theoretically speaking a URI in a CSS document could * be non-embedded, as of CSS2 there is no such usage so we're * generalizing it. This may need to be changed in the future. * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as * the separator, you cannot put a literal semicolon in * in the URI. Try percent encoding it, in that case. */ class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI { public function __construct() { parent::__construct(true); // always embedded } /** * @param string $uri_string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($uri_string, $config, $context) { // parse the URI out of the string and then pass it onto // the parent object $uri_string = $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ListStyle.php
<?php /** * Validates shorthand CSS property list-style. * @warning Does not support url tokens that have internal spaces. */ class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef { /** * Local copy of validators. * @type HTMLPurifier_AttrDef[] * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl. */ protected $info; /** * @param HTMLPurifier_Config $config */ public function __construct($config) { $def = $config->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/ImportantDecorator.php
<?php /** * Decorator which enables !important to be used in CSS values. */ class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_AttrDef */ public $def; /** * @type bool */ public $allow; /** * @param HTMLPurifier_AttrDef $def Definition to wrap * @param bool $allow Whether or not to allow !important */ public function __construct($def, $allow = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Length.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Length.php
<?php /** * Represents a Length as defined by CSS. */ class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_Length|string */ protected $min; /** * @type HTMLPurifier_Length|string */ protected $max; /** * @param HTMLPurifier_Length|string $min Minimum length, or null for no bound. String is also acceptable. * @param HTMLPurifier_Length|string $max Maximum length, or null for no bound. String is also acceptable. */ public function __construct($min = null, $max = null) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Background.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Background.php
<?php /** * Validates shorthand CSS property background. * @warning Does not support url tokens that have internal spaces. */ class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef { /** * Local copy of component validators. * @type HTMLPurifier_AttrDef[] * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl. */ protected $info; /** * @param HTMLPurifier_Config $config */ public function __construct($config) { $def = $config->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']; } /** * @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; $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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Multiple.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Multiple.php
<?php /** * Framework class for strings that involve multiple values. * * Certain CSS properties such as border-width and margin allow multiple * lengths to be specified. This class can take a vanilla border-width * definition and multiply it, usually into a max of four. * * @note Even though the CSS specification isn't clear about it, inherit * can only be used alone: it will never manifest as part of a multi * shorthand declaration. Thus, this class does not allow inherit. */ class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef { /** * Instance of component definition to defer validation to. * @type HTMLPurifier_AttrDef * @todo Make protected */ public $single; /** * Max number of values allowed. * @todo Make protected */ public $max; /** * @param HTMLPurifier_AttrDef $single HTMLPurifier_AttrDef to multiply * @param int $max Max number of values allowed (usually four) */ public function __construct($single, $max = 4) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/DenyElementDecorator.php
<?php /** * Decorator which enables CSS properties to be disabled for specific elements. */ class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_AttrDef */ public $def; /** * @type string */ public $element; /** * @param HTMLPurifier_AttrDef $def Definition to wrap * @param string $element Element to deny */ public function __construct($def, $element) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Ident.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Ident.php
<?php /** * Validates based on {ident} CSS grammar production */ class HTMLPurifier_AttrDef_CSS_Ident extends HTMLPurifier_AttrDef { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { $string = trim($string); // early abort: '' and '0' (strings that convert to false) are invalid if (!$string) { return false; } $pattern = '/^(-?[A-Za-z_][A-Za-z_\-0-9]*)$/'; if (!preg_match($pattern, $string)) { return false; } return $string; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Percentage.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Percentage.php
<?php /** * Validates a Percentage as defined by the CSS spec. */ class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef { /** * Instance to defer number validation to. * @type HTMLPurifier_AttrDef_CSS_Number */ protected $number_def; /** * @param bool $non_negative Whether to forbid negative values */ public function __construct($non_negative = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/BackgroundPosition.php
<?php /* W3C says: [ // adjective and number must be in correct order, even if // you could switch them without introducing ambiguity. // some browsers support that syntax [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Filter.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Filter.php
<?php /** * Microsoft's proprietary filter: CSS property * @note Currently supports the alpha filter. In the future, this will * probably need an extensible framework */ class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_AttrDef_Integer */ protected $intValidator; public function __construct() { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Border.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Border.php
<?php /** * Validates the border property as defined by CSS. */ class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef { /** * Local copy of properties this property is shorthand for. * @type HTMLPurifier_AttrDef[] */ protected $info = array(); /** * @param HTMLPurifier_Config $config */ public function __construct($config) { $def = $config->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Color.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/CSS/Color.php
<?php /** * Validates Color as defined by CSS. */ class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef { /** * @type HTMLPurifier_AttrDef_CSS_AlphaValue */ protected $alpha; public function __construct() { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Pixels.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Pixels.php
<?php /** * Validates an integer representation of pixels according to the HTML spec. */ class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef { /** * @type int */ protected $max; /** * @param int $max */ public function __construct($max = null) { $this->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 <http://ha.ckers.org/imagecrash.html> // 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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/FrameTarget.php
<?php /** * Special-case enum attribute definition that lazy loads allowed frame targets */ class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum { /** * @type array */ public $valid_values = false; // uninitialized value /** * @type bool */ protected $case_sensitive = false; public function __construct() { } /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { if ($this->valid_values === false) { $this->valid_values = $config->get('Attr.AllowedFrameTargets'); } return parent::validate($string, $config, $context); } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Bool.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Bool.php
<?php /** * Validates a boolean attribute */ class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef { /** * @type string */ protected $name; /** * @type bool */ public $minimized = true; /** * @param bool|string $name */ public function __construct($name = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/MultiLength.php
<?php /** * Validates a MultiLength as defined by the HTML spec. * * A multilength is either a integer (pixel count), a percentage, or * a relative number. */ class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length { /** * @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 === '') { return false; } $parent_result = parent::validate($string, $config, $context); if ($parent_result !== false) { return $parent_result; } $length = strlen($string); $last_char = $string[$length - 1]; if ($last_char !== '*') { return false; } $int = substr($string, 0, $length - 1); if ($int == '') { return '*'; } if (!is_numeric($int)) { return false; } $int = (int)$int; if ($int < 0) { return false; } if ($int == 0) { return '0'; } if ($int == 1) { return '*'; } return ((string)$int) . '*'; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Class.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Class.php
<?php /** * Implements special behavior for class attribute (normally NMTOKENS) */ class HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ protected function split($string, $config, $context) { // really, this twiddle should be lazy loaded $name = $config->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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Length.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Length.php
<?php /** * Validates the HTML type length (not to be confused with CSS's length). * * This accepts integer pixels or percentages as lengths for certain * HTML attributes. */ class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels { /** * @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 === '') { return false; } $parent_result = parent::validate($string, $config, $context); if ($parent_result !== false) { return $parent_result; } $length = strlen($string); $last_char = $string[$length - 1]; if ($last_char !== '%') { return false; } $points = substr($string, 0, $length - 1); if (!is_numeric($points)) { return false; } $points = (int)$points; if ($points < 0) { return '0%'; } if ($points > 100) { return '100%'; } return ((string)$points) . '%'; } } // vim: et sw=4 sts=4
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/LinkTypes.php
<?php /** * Validates a rel/rev link attribute against a directive of allowed values * @note We cannot use Enum because link types allow multiple * values. * @note Assumes link types are ASCII text */ class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef { /** * Name config attribute to pull. * @type string */ protected $name; /** * @param string $name */ public function __construct($name) { $configLookup = array( 'rel' => '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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/ID.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/ID.php
<?php /** * Validates the HTML attribute ID. * @warning Even though this is the id processor, it * will ignore the directive Attr:IDBlacklist, since it will only * go according to the ID accumulator. Since the accumulator is * automatically generated, it will have already absorbed the * blacklist. If you're hacking around, make sure you use load()! */ class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef { // selector is NOT a valid thing to use for IDREFs, because IDREFs // *must* target IDs that exist, whereas selector #ids do not. /** * Determines whether or not we're validating an ID in a CSS * selector context. * @type bool */ protected $selector; /** * @param bool $selector */ public function __construct($selector = false) { $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Nmtokens.php
<?php /** * Validates contents based on NMTOKENS attribute type. */ class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { $string = trim($string); // early abort: '' and '0' (strings that convert to false) are invalid if (!$string) { return false; } $tokens = $this->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Color.php
vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrDef/HTML/Color.php
<?php /** * Validates a color according to the HTML spec. */ class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef { /** * @param string $string * @param HTMLPurifier_Config $config * @param HTMLPurifier_Context $context * @return bool|string */ public function validate($string, $config, $context) { static $colors = null; if ($colors === null) { $colors = $config->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
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Bigint.php
vendor/maennchen/zipstream-php/src/Bigint.php
<?php declare(strict_types=1); namespace ZipStream; use OverflowException; class Bigint { /** * @var int[] */ private $bytes = [0, 0, 0, 0, 0, 0, 0, 0]; /** * Initialize the bytes array * * @param int $value */ public function __construct(int $value = 0) { $this->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 * * @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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/DeflateStream.php
vendor/maennchen/zipstream-php/src/DeflateStream.php
<?php declare(strict_types=1); namespace ZipStream; class DeflateStream extends Stream { protected $filter; /** * @var Option\File */ protected $options; /** * Rewind stream * * @return void */ public function rewind(): void { // deflate filter needs to be removed before rewind if ($this->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 ); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Stream.php
vendor/maennchen/zipstream-php/src/Stream.php
<?php declare(strict_types=1); namespace ZipStream; use Psr\Http\Message\StreamInterface; use RuntimeException; /** * Describes a data stream. * * Typically, an instance will wrap a PHP stream; this interface provides * a wrapper around the most common operations, including serialization of * the entire stream to a string. */ class Stream implements StreamInterface { protected $stream; public function __construct($stream) { $this->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 { return preg_match('/[waxc+]/', $this->getMetadata('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 { return preg_match('/[r+]/', $this->getMetadata('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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception.php
vendor/maennchen/zipstream-php/src/Exception.php
<?php declare(strict_types=1); namespace ZipStream; /** * This class is only for inheriting */ abstract class Exception extends \Exception { }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/File.php
vendor/maennchen/zipstream-php/src/File.php
<?php declare(strict_types=1); namespace ZipStream; use Psr\Http\Message\StreamInterface; use ZipStream\Exception\EncodingException; use ZipStream\Exception\FileNotFoundException; use ZipStream\Exception\FileNotReadableException; use ZipStream\Exception\OverflowException; use ZipStream\Option\File as FileOptions; use ZipStream\Option\Method; use ZipStream\Option\Version; class File { const HASH_ALGORITHM = 'crc32b'; const BIT_ZERO_HEADER = 0x0008; const BIT_EFS_UTF8 = 0x0800; const COMPUTE = 1; const SEND = 2; private const CHUNKED_READ_BLOCK_SIZE = 1048576; /** * @var string */ public $name; /** * @var FileOptions */ public $opt; /** * @var Bigint */ public $len; /** * @var Bigint */ public $zlen; /** @var int */ public $crc; /** * @var Bigint */ public $hlen; /** * @var Bigint */ public $ofs; /** * @var int */ public $bits; /** * @var Version */ public $version; /** * @var ZipStream */ public $zip; /** * @var resource */ private $deflate; /** * @var resource */ private $hash; /** * @var Method */ private $method; /** * @var Bigint */ private $totalLength; public function __construct(ZipStream $zip, string $name, ?FileOptions $opt = null) { $this->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(); } 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 { $this->hash = hash_init(self::HASH_ALGORITHM); 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/ZipStream.php
vendor/maennchen/zipstream-php/src/ZipStream.php
<?php declare(strict_types=1); namespace ZipStream; use Psr\Http\Message\StreamInterface; use ZipStream\Exception\OverflowException; use ZipStream\Option\Archive as ArchiveOptions; use ZipStream\Option\File as FileOptions; use ZipStream\Option\Version; /** * ZipStream * * Streamed, dynamically generated zip archives. * * Usage: * * Streaming zip archives is a simple, three-step process: * * 1. Create the zip stream: * * $zip = new ZipStream('example.zip'); * * 2. Add one or more files to the archive: * * * add first file * $data = file_get_contents('some_file.gif'); * $zip->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: * * // 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->addFileFromPsr7Stream('streamfile.txt', $fp); * * @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; fwrite($this->opt->getOutputStream(), $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(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/IncompatibleOptionsException.php
vendor/maennchen/zipstream-php/src/Exception/IncompatibleOptionsException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if options are incompatible */ class IncompatibleOptionsException extends Exception { }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/EncodingException.php
vendor/maennchen/zipstream-php/src/Exception/EncodingException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if file or comment encoding is incorrect */ class EncodingException extends Exception { }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/FileNotFoundException.php
vendor/maennchen/zipstream-php/src/Exception/FileNotFoundException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a file wasn't found */ class FileNotFoundException extends Exception { /** * Constructor of the Exception * * @param String $path - The path which wasn't found */ public function __construct(string $path) { parent::__construct("The file with the path $path wasn't found."); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/OverflowException.php
vendor/maennchen/zipstream-php/src/Exception/OverflowException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a counter value exceeds storage size */ class OverflowException extends Exception { public function __construct() { parent::__construct('File size exceeds limit of 32 bit integer. Please enable "zip64" option.'); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/StreamNotReadableException.php
vendor/maennchen/zipstream-php/src/Exception/StreamNotReadableException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if `fread` fails on a stream. */ class StreamNotReadableException extends Exception { /** * Constructor of the Exception * * @param string $fileName - The name of the file which the stream belongs to. */ public function __construct(string $fileName) { parent::__construct("The stream for $fileName could not be read."); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Exception/FileNotReadableException.php
vendor/maennchen/zipstream-php/src/Exception/FileNotReadableException.php
<?php declare(strict_types=1); namespace ZipStream\Exception; use ZipStream\Exception; /** * This Exception gets invoked if a file wasn't found */ class FileNotReadableException extends Exception { /** * Constructor of the Exception * * @param String $path - The path which wasn't found */ public function __construct(string $path) { parent::__construct("The file with the path $path isn't readable."); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Option/Method.php
vendor/maennchen/zipstream-php/src/Option/Method.php
<?php declare(strict_types=1); namespace ZipStream\Option; use MyCLabs\Enum\Enum; /** * Methods enum * * @method static STORE(): Method * @method static DEFLATE(): Method * @psalm-immutable */ class Method extends Enum { const STORE = 0x00; const DEFLATE = 0x08; }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Option/Version.php
vendor/maennchen/zipstream-php/src/Option/Version.php
<?php declare(strict_types=1); namespace ZipStream\Option; use MyCLabs\Enum\Enum; /** * Class Version * @package ZipStream\Option * * @method static STORE(): Version * @method static DEFLATE(): Version * @method static ZIP64(): Version * @psalm-immutable */ class Version extends Enum { const STORE = 0x000A; // 1.00 const DEFLATE = 0x0014; // 2.00 const ZIP64 = 0x002D; // 4.50 }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Option/Archive.php
vendor/maennchen/zipstream-php/src/Option/Archive.php
<?php declare(strict_types=1); namespace ZipStream\Option; final class Archive { const DEFAULT_DEFLATE_LEVEL = 6; /** * @var string */ private $comment = ''; /** * Size, in bytes, of the largest file to try * and load into memory (used by * addFileFromPath()). Large files may also * be compressed differently; see the * 'largeFileMethod' option. Default is ~20 Mb. * * @var int */ private $largeFileSize = 20 * 1024 * 1024; /** * How to handle large files. Legal values are * Method::STORE() (the default), or * Method::DEFLATE(). STORE sends the file * raw and is significantly * faster, while DEFLATE compresses the file * and is much, much slower. Note that DEFLATE * must compress the file twice and is extremely slow. * * @var Method */ private $largeFileMethod; /** * Boolean indicating whether or not to send * the HTTP headers for this file. * * @var bool */ private $sendHttpHeaders = false; /** * The method called to send headers * * @var Callable */ private $httpHeaderCallback = 'header'; /** * Enable Zip64 extension, supporting very large * archives (any size > 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 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 resource */ public function getOutputStream() { return $this->outputStream; } /** * @param 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/src/Option/File.php
vendor/maennchen/zipstream-php/src/Option/File.php
<?php declare(strict_types=1); namespace ZipStream\Option; use DateTime; final class File { /** * @var string */ private $comment = ''; /** * @var Method */ private $method; /** * @var int */ private $deflateLevel; /** * @var DateTime */ private $time; /** * @var int */ private $size = 0; public function defaultTo(Archive $archiveOptions): void { $this->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 DateTime */ public function getTime(): DateTime { return $this->time; } /** * @param DateTime $time */ public function setTime(DateTime $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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/test/ZipStreamTest.php
vendor/maennchen/zipstream-php/test/ZipStreamTest.php
<?php declare(strict_types=1); namespace ZipStreamTest; use org\bovigo\vfs\vfsStream; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; use ZipStream\File; use ZipStream\Option\Archive as ArchiveOptions; use ZipStream\Option\File as FileOptions; use ZipStream\Option\Method; use ZipStream\ZipStream; /** * Test Class for the Main ZipStream CLass */ class ZipStreamTest extends TestCase { const OSX_ARCHIVE_UTILITY = '/System/Library/CoreServices/Applications/Archive Utility.app/Contents/MacOS/Archive Utility'; public function testFileNotFoundException(): void { $this->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/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/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/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 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/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(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/test/bootstrap.php
vendor/maennchen/zipstream-php/test/bootstrap.php
<?php declare(strict_types=1); date_default_timezone_set('UTC'); require __DIR__ . '/../vendor/autoload.php';
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/test/BigintTest.php
vendor/maennchen/zipstream-php/test/BigintTest.php
<?php declare(strict_types=1); namespace BigintTest; use OverflowException; use PHPUnit\Framework\TestCase; use ZipStream\Bigint; class BigintTest extends TestCase { public function testConstruct(): void { $bigint = new Bigint(0x12345678); $this->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)); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/maennchen/zipstream-php/test/bug/BugHonorFileTimeTest.php
vendor/maennchen/zipstream-php/test/bug/BugHonorFileTimeTest.php
<?php declare(strict_types=1); namespace BugHonorFileTimeTest; use DateTime; use PHPUnit\Framework\TestCase; use ZipStream\Option\{ Archive, File }; use ZipStream\ZipStream; use function fopen; /** * Asserts that specified last-modified timestamps are not overwritten when a * file is added */ class BugHonorFileTimeTest extends TestCase { public function testHonorsFileTime(): void { $archiveOpt = new Archive(); $fileOpt = new File(); $expectedTime = new DateTime('2019-04-21T19:25:00-0800'); $archiveOpt->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()); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/.php-cs-fixer.dist.php
vendor/phpoffice/phpspreadsheet/.php-cs-fixer.dist.php
<?php $finder = PhpCsFixer\Finder::create() ->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' => true, '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' => true, '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', 'method', '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' => true, '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;
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedFormula.php
<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedFormula extends DefinedName { /** * Create a new Named Formula. */ public function __construct( string $name, ?Worksheet $worksheet = null, ?string $formula = null, bool $localOnly = false, ?Worksheet $scope = null ) { // Validate data if (!isset($formula)) { throw new Exception('You must specify a Formula value for a Named Formula'); } parent::__construct($name, $worksheet, $formula, $localOnly, $scope); } /** * Get the formula value. */ public function getFormula(): string { return $this->value; } /** * Set the formula value. */ public function setFormula(string $formula): self { if (!empty($formula)) { $this->value = $formula; } return $this; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php
<?php namespace PhpOffice\PhpSpreadsheet; 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 { /** * Class name of the chart renderer used for rendering charts * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph. * * @var string */ private static $chartRenderer; /** * Default options for libxml loader. * * @var int */ private static $libXmlLoaderOptions; /** * The cache implementation to be used for cell collection. * * @var CacheInterface */ private static $cache; /** * The HTTP client implementation to be used for network request. * * @var null|ClientInterface */ private static $httpClient; /** * @var null|RequestFactoryInterface */ private static $requestFactory; /** * Set the locale code to use for formula translations and any special formatting. * * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") * * @return bool Success or failure */ 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 $rendererClassName Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ public static function setChartRenderer(string $rendererClassName): void { if (!is_a($rendererClassName, IRenderer::class, true)) { throw new Exception('Chart renderer must implement ' . IRenderer::class); } self::$chartRenderer = $rendererClassName; } /** * Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use. * * @return null|string Class name of the chart renderer * eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph */ 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): void { if ($options === null && defined('LIBXML_DTDLOAD')) { $options = LIBXML_DTDLOAD | LIBXML_DTDATTR; } self::$libXmlLoaderOptions = $options; } /** * Get default options for libxml loader. * Defaults to LIBXML_DTDLOAD | LIBXML_DTDATTR when not set explicitly. * * @return int Default options for libxml loader */ public static function getLibXmlLoaderOptions(): int { if (self::$libXmlLoaderOptions === null && defined('LIBXML_DTDLOAD')) { self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); } elseif (self::$libXmlLoaderOptions === null) { self::$libXmlLoaderOptions = 0; } return self::$libXmlLoaderOptions; } /** * 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): void { // noop } /** * 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(): bool { return true; } /** * Sets the implementation of cache that should be used for cell collection. */ public static function setCache(CacheInterface $cache): void { self::$cache = $cache; } /** * Gets the implementation of cache that is being used for cell collection. */ public static function getCache(): CacheInterface { if (!self::$cache) { self::$cache = new Memory(); } 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.'); } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php
<?php 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. * * It is not required to use this class, but it should make it easier to read and write files. * Especially for reading files with an unknown format. */ abstract class IOFactory { 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, ]; private static $writers = [ 'Xls' => Writer\Xls::class, 'Xlsx' => Writer\Xlsx::class, 'Ods' => Writer\Ods::class, 'Csv' => Writer\Csv::class, 'Html' => Writer\Html::class, 'Tcpdf' => Writer\Pdf\Tcpdf::class, 'Dompdf' => Writer\Pdf\Dompdf::class, 'Mpdf' => Writer\Pdf\Mpdf::class, ]; /** * Create Writer\IWriter. */ public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter { if (!isset(self::$writers[$writerType])) { throw new Writer\Exception("No writer found for type $writerType"); } // Instantiate writer $className = self::$writers[$writerType]; return new $className($spreadsheet); } /** * Create IReader. */ public static function createReader(string $readerType): IReader { if (!isset(self::$readers[$readerType])) { throw new Reader\Exception("No reader found for type $readerType"); } // Instantiate reader $className = self::$readers[$readerType]; return new $className(); } /** * Loads Spreadsheet from file using automatic Reader\IReader resolution. * * @param string $filename The name of the spreadsheet file */ public static function load(string $filename, int $flags = 0): Spreadsheet { $reader = self::createReaderForFile($filename); return $reader->load($filename, $flags); } /** * Identify file type using automatic IReader resolution. */ public static function identify(string $filename): string { $reader = self::createReaderForFile($filename); $className = get_class($reader); $classType = explode('\\', $className); unset($reader); return array_pop($classType); } /** * Create Reader\IReader for file using automatic IReader resolution. */ public static function createReaderForFile(string $filename): IReader { File::assertFile($filename); // First, lucky guess by inspecting file extension $guessedReader = self::getReaderTypeFromExtension($filename); if ($guessedReader !== null) { $reader = self::createReader($guessedReader); // Let's see if we are lucky 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) { // Ignore our original guess, we know that won't work if ($type !== $guessedReader) { $reader = self::createReader($type); if ($reader->canRead($filename)) { return $reader; } } } throw new Reader\Exception('Unable to identify a reader for this file'); } /** * Guess a reader type from the file extension, if any. */ private static function getReaderTypeFromExtension(string $filename): ?string { $pathinfo = pathinfo($filename); if (!isset($pathinfo['extension'])) { return null; } switch (strtolower($pathinfo['extension'])) { case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded) case 'xltx': // Excel (OfficeOpenXML) Template case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded) return 'Xlsx'; case 'xls': // Excel (BIFF) Spreadsheet case 'xlt': // Excel (BIFF) Template return 'Xls'; case 'ods': // Open/Libre Offic Calc case 'ots': // Open/Libre Offic Calc Template return 'Ods'; case 'slk': return 'Slk'; case 'xml': // Excel 2003 SpreadSheetML return 'Xml'; case 'gnumeric': return 'Gnumeric'; case 'htm': case 'html': return 'Html'; case 'csv': // Do nothing // We must not try to use CSV reader since it loads // all files including Excel files etc. return null; default: return null; } } /** * Register a writer with its type and class name. */ public static function registerWriter(string $writerType, string $writerClass): void { if (!is_a($writerClass, IWriter::class, true)) { throw new Writer\Exception('Registered writers must implement ' . IWriter::class); } self::$writers[$writerType] = $writerClass; } /** * Register a reader with its type and class name. */ public static function registerReader(string $readerType, string $readerClass): void { if (!is_a($readerClass, IReader::class, true)) { throw new Reader\Exception('Registered readers must implement ' . IReader::class); } self::$readers[$readerType] = $readerClass; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/DefinedName.php
<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class DefinedName { protected const REGEXP_IDENTIFY_FORMULA = '[^_\p{N}\p{L}:, \$\'!]'; /** * Name. * * @var string */ protected $name; /** * Worksheet on which the defined name can be resolved. * * @var Worksheet */ protected $worksheet; /** * Value of the named object. * * @var string */ protected $value; /** * Is the defined named local? (i.e. can only be used on $this->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; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Exception.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Exception.php
<?php namespace PhpOffice\PhpSpreadsheet; class Exception extends \Exception { }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/NamedRange.php
<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class NamedRange extends DefinedName { /** * 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'); } parent::__construct($name, $worksheet, $range, $localOnly, $scope); } /** * Get the range value. */ public function getRange(): string { return $this->value; } /** * Set the range value. */ public function setRange(string $range): self { if (!empty($range)) { $this->value = $range; } return $this; } public function getCellsInRange(): array { $range = $this->value; if (substr($range, 0, 1) === '=') { $range = substr($range, 1); } return Coordinate::extractAllCellReferencesInRange($range); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Comment.php
<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Helper\Size; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Style\Alignment; use PhpOffice\PhpSpreadsheet\Style\Color; class Comment implements IComparable { /** * Author. * * @var string */ private $author; /** * Rich text comment. * * @var RichText */ private $text; /** * Comment width (CSS style, i.e. XXpx or YYpt). * * @var string */ private $width = '96pt'; /** * Left margin (CSS style, i.e. XXpx or YYpt). * * @var string */ private $marginLeft = '59.25pt'; /** * Top margin (CSS style, i.e. XXpx or YYpt). * * @var string */ private $marginTop = '1.5pt'; /** * Visible. * * @var bool */ private $visible = false; /** * Comment height (CSS style, i.e. XXpx or YYpt). * * @var string */ private $height = '55.5pt'; /** * Comment fill color. * * @var Color */ private $fillColor; /** * Alignment. * * @var string */ private $alignment; /** * Create a new Comment. */ public function __construct() { // Initialise variables $this->author = 'Author'; $this->text = new RichText(); $this->fillColor = new Color('FFFFFFE1'); $this->alignment = Alignment::HORIZONTAL_GENERAL; } /** * Get Author. */ public function getAuthor(): string { return $this->author; } /** * Set Author. */ public function setAuthor(string $author): self { $this->author = $author; return $this; } /** * Get Rich text comment. */ public function getText(): RichText { return $this->text; } /** * Set Rich text comment. */ public function setText(RichText $text): self { $this->text = $text; return $this; } /** * Get comment width (CSS style, i.e. XXpx or YYpt). */ public function getWidth(): string { return $this->width; } /** * Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setWidth(string $width): self { $width = new Size($width); if ($width->valid()) { $this->width = (string) $width; } return $this; } /** * Get comment height (CSS style, i.e. XXpx or YYpt). */ public function getHeight(): string { return $this->height; } /** * Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setHeight(string $height): self { $height = new Size($height); if ($height->valid()) { $this->height = (string) $height; } return $this; } /** * Get left margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginLeft(): string { return $this->marginLeft; } /** * Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginLeft(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginLeft = (string) $margin; } return $this; } /** * Get top margin (CSS style, i.e. XXpx or YYpt). */ public function getMarginTop(): string { return $this->marginTop; } /** * Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt. */ public function setMarginTop(string $margin): self { $margin = new Size($margin); if ($margin->valid()) { $this->marginTop = (string) $margin; } return $this; } /** * Is the comment visible by default? */ public function getVisible(): bool { return $this->visible; } /** * Set comment default visibility. */ public function setVisible(bool $visibility): self { $this->visible = $visibility; return $this; } /** * Set fill color. */ public function setFillColor(Color $color): self { $this->fillColor = $color; return $this; } /** * Get fill color. */ public function getFillColor(): Color { return $this->fillColor; } /** * Set Alignment. */ public function setAlignment(string $alignment): self { $this->alignment = $alignment; return $this; } /** * Get Alignment. */ public function getAlignment(): string { return $this->alignment; } /** * Get hash code. */ public function getHashCode(): string { return md5( $this->author . $this->text->getHashCode() . $this->width . $this->height . $this->marginLeft . $this->marginTop . ($this->visible ? 1 : 0) . $this->fillColor->getHashCode() . $this->alignment . __CLASS__ ); } /** * 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; } } } /** * Convert to string. */ public function __toString(): string { return $this->text->getPlainText(); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/HashTable.php
<?php namespace PhpOffice\PhpSpreadsheet; /** * @template T of IComparable */ class HashTable { /** * HashTable elements. * * @var array<string, T> */ protected $items = []; /** * HashTable key map. * * @var array<int, string> */ protected $keyMap = []; /** * Create a new HashTable. * * @param T[] $source Optional source array to create HashTable from */ public function __construct($source = null) { if ($source !== null) { // Create HashTable $this->addFromSource($source); } } /** * Add HashTable items from source. * * @param T[] $source Source array to create HashTable from */ public function addFromSource(?array $source = null): void { // Check if an array was passed if ($source === null) { return; } foreach ($source as $item) { $this->add($item); } } /** * Add HashTable item. * * @param T $source Item to add */ public function add(IComparable $source): void { $hash = $source->getHashCode(); if (!isset($this->items[$hash])) { $this->items[$hash] = $source; $this->keyMap[count($this->items) - 1] = $hash; } } /** * Remove HashTable item. * * @param T $source Item to remove */ public function remove(IComparable $source): void { $hash = $source->getHashCode(); if (isset($this->items[$hash])) { unset($this->items[$hash]); $deleteKey = -1; foreach ($this->keyMap as $key => $value) { if ($deleteKey >= 0) { $this->keyMap[$key - 1] = $value; } if ($value == $hash) { $deleteKey = $key; } } unset($this->keyMap[count($this->keyMap) - 1]); } } /** * Clear HashTable. */ public function clear(): void { $this->items = []; $this->keyMap = []; } /** * Count. * * @return int */ public function count() { return count($this->items); } /** * Get index for hash code. * * @return false|int Index */ public function getIndexForHashCode(string $hashCode) { return array_search($hashCode, $this->keyMap, true); } /** * Get by index. * * @return null|T */ public function getByIndex(int $index) { if (isset($this->keyMap[$index])) { return $this->getByHashCode($this->keyMap[$index]); } return null; } /** * Get by hashcode. * * @return null|T */ public function getByHashCode(string $hashCode) { if (isset($this->items[$hashCode])) { return $this->items[$hashCode]; } return null; } /** * HashTable to array. * * @return T[] */ public function toArray() { return $this->items; } /** * 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) { // 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; } } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IComparable.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IComparable.php
<?php namespace PhpOffice\PhpSpreadsheet; interface IComparable { /** * Get hash code. * * @return string Hash code */ public function getHashCode(); }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Spreadsheet.php
<?php 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; class Spreadsheet { // Allowable values for workbook window visilbity const VISIBILITY_VISIBLE = 'visible'; 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, self::VISIBILITY_VERY_HIDDEN, ]; /** * Unique ID. * * @var string */ private $uniqueID; /** * Document properties. * * @var Document\Properties */ private $properties; /** * Document security. * * @var Document\Security */ private $security; /** * Collection of Worksheet objects. * * @var Worksheet[] */ private $workSheetCollection = []; /** * Calculation Engine. * * @var null|Calculation */ private $calculationEngine; /** * Active sheet index. * * @var int */ private $activeSheetIndex = 0; /** * Named ranges. * * @var DefinedName[] */ private $definedNames = []; /** * CellXf supervisor. * * @var Style */ private $cellXfSupervisor; /** * CellXf collection. * * @var Style[] */ private $cellXfCollection = []; /** * CellStyleXf collection. * * @var Style[] */ private $cellStyleXfCollection = []; /** * hasMacros : this workbook have macros ? * * @var bool */ private $hasMacros = false; /** * macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro. * * @var null|string */ private $macrosCode; /** * macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed. * * @var null|string */ private $macrosCertificate; /** * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI. * * @var null|array{target: string, data: string} */ private $ribbonXMLData; /** * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements * ignored if $ribbonXMLData is null. * * @var null|array */ private $ribbonBinObjects; /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @var array */ private $unparsedLoadedData = []; /** * Controls visibility of the horizonal scroll bar in the application. * * @var bool */ private $showHorizontalScroll = true; /** * Controls visibility of the horizonal scroll bar in the application. * * @var bool */ private $showVerticalScroll = true; /** * Controls visibility of the sheet tabs in the application. * * @var bool */ private $showSheetTabs = true; /** * Specifies a boolean value that indicates whether the workbook window * is minimized. * * @var bool */ private $minimized = false; /** * Specifies a boolean value that indicates whether to group dates * when presenting the user with filtering optiomd in the user * interface. * * @var bool */ private $autoFilterDateGrouping = true; /** * Specifies the index to the first sheet in the book view. * * @var int */ private $firstSheetIndex = 0; /** * Specifies the visible status of the workbook. * * @var string */ private $visibility = self::VISIBILITY_VISIBLE; /** * Specifies the ratio between the workbook tabs bar and the horizontal * scroll bar. TabRatio is assumed to be out of 1000 of the horizontal * window width. * * @var int */ private $tabRatio = 600; /** * The workbook has macros ? * * @return bool */ public function hasMacros() { return $this->hasMacros; } /** * Define if a workbook has macros. * * @param bool $hasMacros true|false */ public function setHasMacros($hasMacros): void { $this->hasMacros = (bool) $hasMacros; } /** * Set the macros code. * * @param string $macroCode string|null */ public function setMacrosCode($macroCode): void { $this->macrosCode = $macroCode; $this->setHasMacros($macroCode !== null); } /** * Return the macros code. * * @return null|string */ public function getMacrosCode() { return $this->macrosCode; } /** * Set the macros certificate. * * @param null|string $certificate */ public function setMacrosCertificate($certificate): void { $this->macrosCertificate = $certificate; } /** * Is the project signed ? * * @return bool true|false */ public function hasMacrosCertificate() { return $this->macrosCertificate !== null; } /** * Return the macros certificate. * * @return null|string */ public function getMacrosCertificate() { return $this->macrosCertificate; } /** * Remove all macros, certificate from spreadsheet. */ public function discardMacros(): void { $this->hasMacros = false; $this->macrosCode = null; $this->macrosCertificate = null; } /** * set ribbon XML data. * * @param null|mixed $target * @param null|mixed $xmlData */ public function setRibbonXMLData($target, $xmlData): void { if ($target !== null && $xmlData !== null) { $this->ribbonXMLData = ['target' => $target, 'data' => $xmlData]; } else { $this->ribbonXMLData = null; } } /** * retrieve ribbon XML Data. * * @param string $what * * @return null|array|string */ public function getRibbonXMLData($what = 'all') //we need some constants here... { $returnData = null; $what = strtolower($what); switch ($what) { case 'all': $returnData = $this->ribbonXMLData; break; case 'target': case 'data': if (is_array($this->ribbonXMLData) && isset($this->ribbonXMLData[$what])) { $returnData = $this->ribbonXMLData[$what]; } break; } return $returnData; } /** * store binaries ribbon objects (pictures). * * @param null|mixed $BinObjectsNames * @param null|mixed $BinObjectsData */ public function setRibbonBinObjects($BinObjectsNames, $BinObjectsData): void { if ($BinObjectsNames !== null && $BinObjectsData !== null) { $this->ribbonBinObjects = ['names' => $BinObjectsNames, 'data' => $BinObjectsData]; } else { $this->ribbonBinObjects = null; } } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal * * @return array */ public function getUnparsedLoadedData() { return $this->unparsedLoadedData; } /** * List of unparsed loaded data for export to same format with better compatibility. * It has to be minimized when the library start to support currently unparsed data. * * @internal */ public function setUnparsedLoadedData(array $unparsedLoadedData): void { $this->unparsedLoadedData = $unparsedLoadedData; } /** * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function). * * @param mixed $path * * @return string */ private function getExtensionOnly($path) { $extension = pathinfo($path, PATHINFO_EXTENSION); return is_array($extension) ? '' : $extension; } /** * retrieve Binaries Ribbon Objects. * * @param string $what * * @return null|array */ public function getRibbonBinObjects($what = 'all') { $ReturnData = null; $what = strtolower($what); switch ($what) { case 'all': return $this->ribbonBinObjects; break; case 'names': case 'data': if (is_array($this->ribbonBinObjects) && isset($this->ribbonBinObjects[$what])) { $ReturnData = $this->ribbonBinObjects[$what]; } break; case 'types': 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 { $ReturnData = []; // the caller want an array... not null if empty } break; } return $ReturnData; } /** * This workbook have a custom UI ? * * @return bool */ public function hasRibbon() { return $this->ribbonXMLData !== null; } /** * This workbook have additionnal object for the ribbon ? * * @return bool */ public function hasRibbonBinObjects() { return $this->ribbonBinObjects !== null; } /** * Check if a sheet with a specified code name already exists. * * @param string $codeName Name of the worksheet to check * * @return bool */ public function sheetCodeNameExists($codeName) { return $this->getSheetByCodeName($codeName) !== null; } /** * Get sheet by code name. Warning : sheet don't have always a code name ! * * @param string $codeName Sheet name * * @return null|Worksheet */ public function getSheetByCodeName($codeName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { if ($this->workSheetCollection[$i]->getCodeName() == $codeName) { return $this->workSheetCollection[$i]; } } return null; } /** * Create a new PhpSpreadsheet with one Worksheet. */ public function __construct() { $this->uniqueID = uniqid('', true); $this->calculationEngine = new Calculation($this); // Initialise worksheet collection and add one worksheet $this->workSheetCollection = []; $this->workSheetCollection[] = new Worksheet($this); $this->activeSheetIndex = 0; // Create document properties $this->properties = new Document\Properties(); // Create document security $this->security = new Document\Security(); // Set defined names $this->definedNames = []; // Create the cellXf supervisor $this->cellXfSupervisor = new Style(true); $this->cellXfSupervisor->bindParent($this); // Create the default style $this->addCellXf(new Style()); $this->addCellStyleXf(new Style()); } /** * Code to execute when this worksheet is unset(). */ public function __destruct() { $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(): void { foreach ($this->workSheetCollection as $worksheet) { $worksheet->disconnectCells(); unset($worksheet); } $this->workSheetCollection = []; } /** * Return the calculation engine for this worksheet. * * @return null|Calculation */ public function getCalculationEngine() { return $this->calculationEngine; } /** * Get properties. * * @return Document\Properties */ public function getProperties() { return $this->properties; } /** * Set properties. */ public function setProperties(Document\Properties $documentProperties): void { $this->properties = $documentProperties; } /** * Get security. * * @return Document\Security */ public function getSecurity() { return $this->security; } /** * Set security. */ public function setSecurity(Document\Security $documentSecurity): void { $this->security = $documentSecurity; } /** * Get active sheet. * * @return Worksheet */ public function getActiveSheet() { return $this->getSheet($this->activeSheetIndex); } /** * Create sheet and add it to this workbook. * * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * * @return Worksheet */ public function createSheet($sheetIndex = null) { $newSheet = new Worksheet($this); $this->addSheet($newSheet, $sheetIndex); return $newSheet; } /** * Check if a sheet with a specified name already exists. * * @param string $worksheetName Name of the worksheet to check * * @return bool */ public function sheetNameExists($worksheetName) { return $this->getSheetByName($worksheetName) !== null; } /** * Add sheet. * * @param Worksheet $worksheet The worskeet to add * @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last) * * @return Worksheet */ public function addSheet(Worksheet $worksheet, $sheetIndex = null) { if ($this->sheetNameExists($worksheet->getTitle())) { throw new Exception( "Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first." ); } if ($sheetIndex === null) { if ($this->activeSheetIndex < 0) { $this->activeSheetIndex = 0; } $this->workSheetCollection[] = $worksheet; } else { // Insert the sheet at the requested index array_splice( $this->workSheetCollection, $sheetIndex, 0, [$worksheet] ); // Adjust active sheet index if necessary if ($this->activeSheetIndex >= $sheetIndex) { ++$this->activeSheetIndex; } } if ($worksheet->getParent() === null) { $worksheet->rebindParent($this); } return $worksheet; } /** * Remove sheet by index. * * @param int $sheetIndex Index position of the worksheet to remove */ public function removeSheetByIndex($sheetIndex): void { $numSheets = count($this->workSheetCollection); if ($sheetIndex > $numSheets - 1) { throw new Exception( "You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}." ); } array_splice($this->workSheetCollection, $sheetIndex, 1); // Adjust active sheet index if necessary if ( ($this->activeSheetIndex >= $sheetIndex) && ($this->activeSheetIndex > 0 || $numSheets <= 1) ) { --$this->activeSheetIndex; } } /** * Get sheet by index. * * @param int $sheetIndex Sheet index * * @return Worksheet */ public function getSheet($sheetIndex) { if (!isset($this->workSheetCollection[$sheetIndex])) { $numSheets = $this->getSheetCount(); throw new Exception( "Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}." ); } return $this->workSheetCollection[$sheetIndex]; } /** * Get all sheets. * * @return Worksheet[] */ public function getAllSheets() { return $this->workSheetCollection; } /** * Get sheet by name. * * @param string $worksheetName Sheet name * * @return null|Worksheet */ public function getSheetByName($worksheetName) { $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { if ($this->workSheetCollection[$i]->getTitle() === trim($worksheetName, "'")) { return $this->workSheetCollection[$i]; } } return null; } /** * Get index for sheet. * * @return int index */ public function getIndex(Worksheet $worksheet) { foreach ($this->workSheetCollection as $key => $value) { if ($value->getHashCode() === $worksheet->getHashCode()) { return $key; } } throw new Exception('Sheet does not exist.'); } /** * Set index for sheet by sheet name. * * @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($worksheetName, $newIndexPosition) { $oldIndex = $this->getIndex($this->getSheetByName($worksheetName)); $worksheet = array_splice( $this->workSheetCollection, $oldIndex, 1 ); array_splice( $this->workSheetCollection, $newIndexPosition, 0, $worksheet ); return $newIndexPosition; } /** * Get sheet count. * * @return int */ public function getSheetCount() { return count($this->workSheetCollection); } /** * Get active sheet index. * * @return int Active sheet index */ public function getActiveSheetIndex() { return $this->activeSheetIndex; } /** * Set active sheet index. * * @param int $worksheetIndex Active sheet index * * @return Worksheet */ public function setActiveSheetIndex($worksheetIndex) { $numSheets = count($this->workSheetCollection); if ($worksheetIndex > $numSheets - 1) { throw new Exception( "You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}." ); } $this->activeSheetIndex = $worksheetIndex; return $this->getActiveSheet(); } /** * Set active sheet index by name. * * @param string $worksheetName Sheet title * * @return Worksheet */ public function setActiveSheetIndexByName($worksheetName) { if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) { $this->setActiveSheetIndex($this->getIndex($worksheet)); return $worksheet; } throw new Exception('Workbook does not contain sheet:' . $worksheetName); } /** * Get sheet names. * * @return string[] */ public function getSheetNames() { $returnValue = []; $worksheetCount = $this->getSheetCount(); for ($i = 0; $i < $worksheetCount; ++$i) { $returnValue[] = $this->getSheet($i)->getTitle(); } return $returnValue; } /** * Add external sheet. * * @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 $worksheet, $sheetIndex = null) { 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 ($worksheet->getParent()->getCellXfCollection() as $cellXf) { $this->addCellXf(clone $cellXf); } // move sheet to this workbook $worksheet->rebindParent($this); // update the cellXfs foreach ($worksheet->getCoordinates(false) as $coordinate) { $cell = $worksheet->getCell($coordinate); $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); } return $this->addSheet($worksheet, $sheetIndex); } /** * Get an array of all Named Ranges. * * @return DefinedName[] */ public function getNamedRanges(): array { return array_filter( $this->definedNames, function (DefinedName $definedName) { return $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE; } ); } /** * Get an array of all Named Formulae. * * @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 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 addDefinedName(DefinedName $definedName): void { $upperCaseName = StringHelper::strToUpper($definedName->getName()); if ($definedName->getScope() == null) { // global scope $this->definedNames[$upperCaseName] = $definedName; } else { // local scope $this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName; } } /** * Get named range. * * @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. * * @param null|Worksheet $worksheet Scope. Use null for global scope */ public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName { $returnValue = null; if ($definedName !== '') { $definedName = StringHelper::strToUpper($definedName); // first look for global defined name 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 (($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) { $returnValue = $this->definedNames[$worksheet->getTitle() . '!' . $definedName]; } } return $returnValue; } /** * Remove named range. * * @param null|Worksheet $worksheet scope: use null for global scope * * @return $this */ public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self { 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->definedNames[$worksheet->getTitle() . '!' . $definedName])) { unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]); } elseif (isset($this->definedNames[$definedName])) { unset($this->definedNames[$definedName]); } } return $this; } /** * Get worksheet iterator. * * @return Iterator */ public function getWorksheetIterator() { return new Iterator($this); } /** * Copy workbook (!= clone!). * * @return Spreadsheet */ public function copy() { $copied = clone $this; $worksheetCount = count($this->workSheetCollection); for ($i = 0; $i < $worksheetCount; ++$i) { $this->workSheetCollection[$i] = $this->workSheetCollection[$i]->copy(); $this->workSheetCollection[$i]->rebindParent($this); } return $copied; } /** * Implement PHP __clone to create a deep clone, not just a shallow 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)); } } } /** * Get the workbook collection of cellXfs. * * @return Style[] */ public function getCellXfCollection() { return $this->cellXfCollection; } /** * Get cellXf by index. * * @param int $cellStyleIndex * * @return Style */ public function getCellXfByIndex($cellStyleIndex) { return $this->cellXfCollection[$cellStyleIndex]; } /** * Get cellXf by hash code. * * @param string $hashcode * * @return false|Style */ public function getCellXfByHashCode($hashcode) { foreach ($this->cellXfCollection as $cellXf) { if ($cellXf->getHashCode() === $hashcode) { return $cellXf; } } return false; } /** * Check if style exists in style collection. * * @return bool */ public function cellXfExists(Style $cellStyleIndex) { return in_array($cellStyleIndex, $this->cellXfCollection, true); } /** * Get default style. * * @return Style */ public function getDefaultStyle() { if (isset($this->cellXfCollection[0])) { return $this->cellXfCollection[0]; } throw new Exception('No default style found for this workbook'); } /** * Add a cellXf to the workbook. */ public function addCellXf(Style $style): void { $this->cellXfCollection[] = $style; $style->setIndex(count($this->cellXfCollection) - 1); } /** * Remove cellXf by index. It is ensured that all cells get their xf index updated. * * @param int $cellStyleIndex Index to cellXf */ public function removeCellXfByIndex($cellStyleIndex): void { if ($cellStyleIndex > count($this->cellXfCollection) - 1) { throw new Exception('CellXf index is out of bounds.'); } // first remove the cellXf 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 > $cellStyleIndex) { // decrease xf index by 1 $cell->setXfIndex($xfIndex - 1); } elseif ($xfIndex == $cellStyleIndex) {
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/ReferenceHelper.php
<?php namespace PhpOffice\PhpSpreadsheet; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class ReferenceHelper { /** Constants */ /** Regular Expressions */ const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)'; const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; /** * Instance of this class. * * @var ReferenceHelper */ private static $instance; /** * Get an instance of this class. * * @return ReferenceHelper */ public static function getInstance() { if (!isset(self::$instance) || (self::$instance === null)) { self::$instance = new self(); } return self::$instance; } /** * Create a new ReferenceHelper. */ protected function __construct() { } /** * Compare two column addresses * Intended for use as a Callback function for sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') * * @return int */ public static function columnSort($a, $b) { return strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two column addresses * Intended for use as a Callback function for reverse sorting column addresses by column. * * @param string $a First column to test (e.g. 'AA') * @param string $b Second column to test (e.g. 'Z') * * @return int */ public static function columnReverseSort($a, $b) { return -strcasecmp(strlen($a) . $a, strlen($b) . $b); } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') * * @return int */ public static function cellSort($a, $b) { [$ac, $ar] = sscanf($a, '%[A-Z]%d'); [$bc, $br] = sscanf($b, '%[A-Z]%d'); if ($ar === $br) { return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); } return ($ar < $br) ? -1 : 1; } /** * Compare two cell addresses * Intended for use as a Callback function for sorting cell addresses by column and row. * * @param string $a First cell to test (e.g. 'AA1') * @param string $b Second cell to test (e.g. 'Z1') * * @return int */ public static function cellReverseSort($a, $b) { [$ac, $ar] = sscanf($a, '%[A-Z]%d'); [$bc, $br] = sscanf($b, '%[A-Z]%d'); if ($ar === $br) { 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 $numberOfRows 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 $numberOfCols Number of columns to insert/delete (negative values indicate deletion) * * @return bool */ private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfCols) { [$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress); $cellColumnIndex = Coordinate::columnIndexFromString($cellColumn); // Is cell within the range of rows/columns if we're deleting if ( $numberOfRows < 0 && ($cellRow >= ($beforeRow + $numberOfRows)) && ($cellRow < $beforeRow) ) { return true; } elseif ( $numberOfCols < 0 && ($cellColumnIndex >= ($beforeColumnIndex + $numberOfCols)) && ($cellColumnIndex < $beforeColumnIndex) ) { return true; } return false; } /** * Update page breaks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustPageBreaks(Worksheet $worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void { $aBreaks = $worksheet->getBreaks(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aBreaks, ['self', 'cellReverseSort']) : uksort($aBreaks, ['self', 'cellSort']); foreach ($aBreaks as $key => $value) { if (self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) { // If we're deleting, then clear any defined breaks that are within the range // of rows/columns that we're deleting $worksheet->setBreak($key, 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, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { $worksheet->setBreak($newReference, $value) ->setBreak($key, Worksheet::BREAK_NONE); } } } } /** * Update cell comments when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') * @param int $beforeColumnIndex Index number of the column we're inserting/deleting before * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustComments($worksheet, $beforeCellAddress, $beforeColumnIndex, $numberOfColumns, $beforeRow, $numberOfRows): void { $aComments = $worksheet->getComments(); $aNewComments = []; // the new array of all comments foreach ($aComments as $key => &$value) { // Any comments inside a deleted range will be ignored if (!self::cellAddressInDeleteRange($key, $beforeRow, $numberOfRows, $beforeColumnIndex, $numberOfColumns)) { // Otherwise build a new array of comments indexed by the adjusted cell reference $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); $aNewComments[$newReference] = $value; } } // Replace the comments array with the new set of comments $worksheet->setComments($aNewComments); } /** * Update hyperlinks when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete 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) */ protected function adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void { $aHyperlinkCollection = $worksheet->getHyperlinkCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aHyperlinkCollection, ['self', 'cellReverseSort']) : uksort($aHyperlinkCollection, ['self', 'cellSort']); foreach ($aHyperlinkCollection as $key => $value) { $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { $worksheet->setHyperlink($newReference, $value); $worksheet->setHyperlink($key, null); } } } /** * Update data validations when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $before Insert/Delete 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) */ protected function adjustDataValidations(Worksheet $worksheet, $before, $numberOfColumns, $numberOfRows): void { $aDataValidationCollection = $worksheet->getDataValidationCollection(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aDataValidationCollection, ['self', 'cellReverseSort']) : uksort($aDataValidationCollection, ['self', 'cellSort']); foreach ($aDataValidationCollection as $key => $value) { $newReference = $this->updateCellReference($key, $before, $numberOfColumns, $numberOfRows); if ($key != $newReference) { $worksheet->setDataValidation($newReference, $value); $worksheet->setDataValidation($key, null); } } } /** * Update merged cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete 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) */ protected function adjustMergeCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void { $aMergeCells = $worksheet->getMergeCells(); $aNewMergeCells = []; // the new array of all merge cells foreach ($aMergeCells as $key => &$value) { $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); $aNewMergeCells[$newReference] = $newReference; } $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array } /** * Update protected cells when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete 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) */ protected function adjustProtectedCells(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void { $aProtectedCells = $worksheet->getProtectedCells(); ($numberOfColumns > 0 || $numberOfRows > 0) ? uksort($aProtectedCells, ['self', 'cellReverseSort']) : uksort($aProtectedCells, ['self', 'cellSort']); foreach ($aProtectedCells as $key => $value) { $newReference = $this->updateCellReference($key, $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($key != $newReference) { $worksheet->protectCells($newReference, $value, true); $worksheet->unprotectCells($key); } } } /** * Update column dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete 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) */ protected function adjustColumnDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows): void { $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true); if (!empty($aColumnDimensions)) { foreach ($aColumnDimensions as $objColumnDimension) { $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $beforeCellAddress, $numberOfColumns, $numberOfRows); [$newReference] = Coordinate::coordinateFromString($newReference); if ($objColumnDimension->getColumnIndex() != $newReference) { $objColumnDimension->setColumnIndex($newReference); } } $worksheet->refreshColumnDimensions(); } } /** * Update row dimensions when inserting/deleting rows/columns. * * @param Worksheet $worksheet The worksheet that we're editing * @param string $beforeCellAddress Insert/Delete before this cell address (e.g. 'A1') * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion) * @param int $beforeRow Number of the row we're inserting/deleting before * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion) */ protected function adjustRowDimensions(Worksheet $worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows): void { $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true); if (!empty($aRowDimensions)) { foreach ($aRowDimensions as $objRowDimension) { $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $beforeCellAddress, $numberOfColumns, $numberOfRows); [, $newReference] = Coordinate::coordinateFromString($newReference); if ($objRowDimension->getRowIndex() != $newReference) { $objRowDimension->setRowIndex($newReference); } } $worksheet->refreshRowDimensions(); $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()); $newDimension->setCollapsed($copyDimension->getCollapsed()); } } } /** * Insert a new column or row, updating all possible related data. * * @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($beforeCellAddress, $numberOfColumns, $numberOfRows, Worksheet $worksheet): void { $remove = ($numberOfColumns < 0 || $numberOfRows < 0); $allCoordinates = $worksheet->getCoordinates(); // Get coordinate of $beforeCellAddress [$beforeColumn, $beforeRow] = Coordinate::indexesFromString($beforeCellAddress); // Clear cells if we are removing columns or rows $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); // 1. Clear column strips if we are removing columns if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) { 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); } } } } // 2. Clear row strips if we are removing rows if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) { for ($i = $beforeColumn - 1; $i <= Coordinate::columnIndexFromString($highestColumn) - 1; ++$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); } } } } // Loop through cells, bottom-up, and change cell coordinate if ($remove) { // It's faster to reverse and pop than to use unshift, especially with large cell collections $allCoordinates = array_reverse($allCoordinates); } while ($coordinate = array_pop($allCoordinates)) { $cell = $worksheet->getCell($coordinate); $cellIndex = Coordinate::columnIndexFromString($cell->getColumn()); if ($cellIndex - 1 + $numberOfColumns < 0) { continue; } // New coordinate $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 >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) { // Update cell styles $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex()); // Insert this cell at its new location if ($cell->getDataType() == DataType::TYPE_FORMULA) { // Formula should be adjusted $worksheet->getCell($newCoordinate) ->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle())); } else { // Formula should not be adjusted $worksheet->getCell($newCoordinate)->setValue($cell->getValue()); } // Clear the original cell $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) { // Formula should be adjusted $cell->setValue($this->updateFormulaReferences($cell->getValue(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle())); } } } // Duplicate styles for the newly inserted cells $highestColumn = $worksheet->getHighestColumn(); $highestRow = $worksheet->getHighestRow(); if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) { for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($beforeColumn - 1) . $i; if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ? $worksheet->getConditionalStyles($coordinate) : false; for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) { $worksheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); if ($conditionalStyles) { $cloned = []; foreach ($conditionalStyles as $conditionalStyle) { $cloned[] = clone $conditionalStyle; } $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($j) . $i, $cloned); } } } } } if ($numberOfRows > 0 && $beforeRow - 1 > 0) { for ($i = $beforeColumn; $i <= Coordinate::columnIndexFromString($highestColumn); ++$i) { // Style $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1); if ($worksheet->cellExists($coordinate)) { $xfIndex = $worksheet->getCell($coordinate)->getXfIndex(); $conditionalStyles = $worksheet->conditionalStylesExists($coordinate) ? $worksheet->getConditionalStyles($coordinate) : false; for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) { $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); if ($conditionalStyles) { $cloned = []; foreach ($conditionalStyles as $conditionalStyle) { $cloned[] = clone $conditionalStyle; } $worksheet->setConditionalStyles(Coordinate::stringFromColumnIndex($i) . $j, $cloned); } } } } } // Update worksheet: column dimensions $this->adjustColumnDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: row dimensions $this->adjustRowDimensions($worksheet, $beforeCellAddress, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: page breaks $this->adjustPageBreaks($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: comments $this->adjustComments($worksheet, $beforeCellAddress, $beforeColumn, $numberOfColumns, $beforeRow, $numberOfRows); // Update worksheet: hyperlinks $this->adjustHyperlinks($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: data validations $this->adjustDataValidations($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: merge cells $this->adjustMergeCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: protected cells $this->adjustProtectedCells($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows); // Update worksheet: autofilter $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) { // 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) { if (isset($autoFilterColumns[Coordinate::stringFromColumnIndex($deleteColumn + 1)])) { $autoFilter->clearColumn(Coordinate::stringFromColumnIndex($deleteColumn + 1)); } ++$deleteColumn; } } $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; // Shuffle columns in autofilter range if ($numberOfColumns > 0) { $startColRef = $startCol; $endColRef = $rangeEnd[0]; $toColRef = $rangeEnd[0] + $numberOfColumns; 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 + $numberOfColumns); $endColID = Coordinate::stringFromColumnIndex($rangeEnd[0] + 1); do { $autoFilter->shiftColumn($startColID, $toColID); ++$startColID; ++$toColID; } while ($startColID != $endColID); } } } } $worksheet->setAutoFilter($this->updateCellReference($autoFilterRange, $beforeCellAddress, $numberOfColumns, $numberOfRows)); } // Update worksheet: freeze pane if ($worksheet->getFreezePane()) { $splitCell = $worksheet->getFreezePane() ?? ''; $topLeftCell = $worksheet->getTopLeftCell() ?? ''; $splitCell = $this->updateCellReference($splitCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); $topLeftCell = $this->updateCellReference($topLeftCell, $beforeCellAddress, $numberOfColumns, $numberOfRows); $worksheet->freezePane($splitCell, $topLeftCell); } // Page setup if ($worksheet->getPageSetup()->isPrintAreaSet()) { $worksheet->getPageSetup()->setPrintArea($this->updateCellReference($worksheet->getPageSetup()->getPrintArea(), $beforeCellAddress, $numberOfColumns, $numberOfRows)); } // Update worksheet: drawings $aDrawings = $worksheet->getDrawingCollection(); foreach ($aDrawings as $objDrawing) { $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $beforeCellAddress, $numberOfColumns, $numberOfRows); if ($objDrawing->getCoordinates() != $newReference) { $objDrawing->setCoordinates($newReference); } } // 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(), $beforeCellAddress, $numberOfColumns, $numberOfRows)); } } } // Garbage collect $worksheet->garbageCollect(); } /** * Update references within formulas. * * @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($formula = '', $beforeCellAddress = 'A1', $numberOfColumns = 0, $numberOfRows = 0, $worksheetName = '') { // Update cell references in the formula $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) if ($i = !$i) { $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); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : ''; $fromString .= $match[3] . ':' . $match[4]; $modified3 = substr($this->updateCellReference('$A' . $match[3], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2); $modified4 = substr($this->updateCellReference('$A' . $match[4], $beforeCellAddress, $numberOfColumns, $numberOfRows), 2); if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) { 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 + (int) trim($match[3], '$'); $cellIndex = $column . $row; $newCellTokens[$cellIndex] = preg_quote($toString, '/'); $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i'; ++$adjustCount; } } } } // 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); if ($matchCount > 0) { foreach ($matches as $match) { $fromString = ($match[2] > '') ? $match[2] . '!' : '';
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
true
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Font.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; class Font extends Supervisor { // Underline types const UNDERLINE_NONE = 'none'; const UNDERLINE_DOUBLE = 'double'; const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting'; const UNDERLINE_SINGLE = 'single'; const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting'; /** * Font Name. * * @var null|string */ protected $name = 'Calibri'; /** * Font Size. * * @var null|float */ protected $size = 11; /** * Bold. * * @var null|bool */ protected $bold = false; /** * Italic. * * @var null|bool */ protected $italic = false; /** * Superscript. * * @var null|bool */ protected $superscript = false; /** * Subscript. * * @var null|bool */ protected $subscript = false; /** * Underline. * * @var null|string */ protected $underline = self::UNDERLINE_NONE; /** * Strikethrough. * * @var null|bool */ protected $strikethrough = false; /** * Foreground color. * * @var Color */ protected $color; /** * @var null|int */ public $colorIndex; /** * Create a new Font. * * @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) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if ($isConditional) { $this->name = null; $this->size = null; $this->bold = null; $this->italic = null; $this->superscript = null; $this->subscript = null; $this->underline = null; $this->strikethrough = null; $this->color = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); } else { $this->color = new Color(Color::COLOR_BLACK, $isSupervisor); } // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Font */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getFont(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['font' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray( * [ * 'name' => 'Arial', * 'bold' => TRUE, * 'italic' => FALSE, * 'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE, * 'strikethrough' => FALSE, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['name'])) { $this->setName($styleArray['name']); } if (isset($styleArray['bold'])) { $this->setBold($styleArray['bold']); } if (isset($styleArray['italic'])) { $this->setItalic($styleArray['italic']); } if (isset($styleArray['superscript'])) { $this->setSuperscript($styleArray['superscript']); } if (isset($styleArray['subscript'])) { $this->setSubscript($styleArray['subscript']); } if (isset($styleArray['underline'])) { $this->setUnderline($styleArray['underline']); } if (isset($styleArray['strikethrough'])) { $this->setStrikethrough($styleArray['strikethrough']); } if (isset($styleArray['color'])) { $this->getColor()->applyFromArray($styleArray['color']); } if (isset($styleArray['size'])) { $this->setSize($styleArray['size']); } } return $this; } /** * Get Name. * * @return null|string */ public function getName() { if ($this->isSupervisor) { return $this->getSharedComponent()->getName(); } return $this->name; } /** * Set Name. * * @param string $fontname * * @return $this */ public function setName($fontname) { if ($fontname == '') { $fontname = 'Calibri'; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['name' => $fontname]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->name = $fontname; } return $this; } /** * Get Size. * * @return null|float */ public function getSize() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSize(); } return $this->size; } /** * Set Size. * * @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch) * * @return $this */ public function setSize($sizeInPoints) { 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' => $sizeInPoints]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->size = $sizeInPoints; } return $this; } /** * Get Bold. * * @return null|bool */ public function getBold() { if ($this->isSupervisor) { return $this->getSharedComponent()->getBold(); } return $this->bold; } /** * Set Bold. * * @param bool $bold * * @return $this */ public function setBold($bold) { if ($bold == '') { $bold = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['bold' => $bold]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->bold = $bold; } return $this; } /** * Get Italic. * * @return null|bool */ public function getItalic() { if ($this->isSupervisor) { return $this->getSharedComponent()->getItalic(); } return $this->italic; } /** * Set Italic. * * @param bool $italic * * @return $this */ public function setItalic($italic) { if ($italic == '') { $italic = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['italic' => $italic]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->italic = $italic; } return $this; } /** * Get Superscript. * * @return null|bool */ public function getSuperscript() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSuperscript(); } return $this->superscript; } /** * Set Superscript. * * @return $this */ public function setSuperscript(bool $superscript) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['superscript' => $superscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->superscript = $superscript; if ($this->superscript) { $this->subscript = false; } } return $this; } /** * Get Subscript. * * @return null|bool */ public function getSubscript() { if ($this->isSupervisor) { return $this->getSharedComponent()->getSubscript(); } return $this->subscript; } /** * Set Subscript. * * @return $this */ public function setSubscript(bool $subscript) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['subscript' => $subscript]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->subscript = $subscript; if ($this->subscript) { $this->superscript = false; } } return $this; } /** * Get Underline. * * @return null|string */ public function getUnderline() { if ($this->isSupervisor) { return $this->getSharedComponent()->getUnderline(); } return $this->underline; } /** * Set Underline. * * @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($underlineStyle) { 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' => $underlineStyle]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->underline = $underlineStyle; } return $this; } /** * Get Strikethrough. * * @return null|bool */ public function getStrikethrough() { if ($this->isSupervisor) { return $this->getSharedComponent()->getStrikethrough(); } return $this->strikethrough; } /** * Set Strikethrough. * * @param bool $strikethru * * @return $this */ public function setStrikethrough($strikethru) { if ($strikethru == '') { $strikethru = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['strikethrough' => $strikethru]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->strikethrough = $strikethru; } return $this; } /** * Get Color. * * @return Color */ public function getColor() { return $this->color; } /** * Set Color. * * @return $this */ public function setColor(Color $color) { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->name . $this->size . ($this->bold ? 't' : 'f') . ($this->italic ? 't' : 'f') . ($this->superscript ? 't' : 'f') . ($this->subscript ? 't' : 'f') . $this->underline . ($this->strikethrough ? 't' : 'f') . $this->color->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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Protection.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Protection.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; class Protection extends Supervisor { /** Protection styles */ const PROTECTION_INHERIT = 'inherit'; const PROTECTION_PROTECTED = 'protected'; const PROTECTION_UNPROTECTED = 'unprotected'; /** * Locked. * * @var string */ protected $locked; /** * Hidden. * * @var string */ protected $hidden; /** * Create a new Protection. * * @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) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { $this->locked = self::PROTECTION_INHERIT; $this->hidden = self::PROTECTION_INHERIT; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Protection */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getProtection(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['protection' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray( * [ * 'locked' => TRUE, * 'hidden' => FALSE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['locked'])) { $this->setLocked($styleArray['locked']); } if (isset($styleArray['hidden'])) { $this->setHidden($styleArray['hidden']); } } return $this; } /** * Get locked. * * @return string */ public function getLocked() { if ($this->isSupervisor) { return $this->getSharedComponent()->getLocked(); } return $this->locked; } /** * Set locked. * * @param string $lockType see self::PROTECTION_* * * @return $this */ public function setLocked($lockType) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['locked' => $lockType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->locked = $lockType; } return $this; } /** * Get hidden. * * @return string */ public function getHidden() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHidden(); } return $this->hidden; } /** * Set hidden. * * @param string $hiddenType see self::PROTECTION_* * * @return $this */ public function setHidden($hiddenType) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['hidden' => $hiddenType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->hidden = $hiddenType; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->locked . $this->hidden . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'locked', $this->getLocked()); $this->exportArray2($exportedArray, 'hidden', $this->getHidden()); return $exportedArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Supervisor.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\IComparable; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; abstract class Supervisor implements IComparable { /** * Supervisor? * * @var bool */ protected $isSupervisor; /** * Parent. Only used for supervisor. * * @var Spreadsheet|Style */ protected $parent; /** * Parent property name. * * @var null|string */ protected $parentPropertyName; /** * Create a new 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 */ public function __construct($isSupervisor = false) { // Supervisor? $this->isSupervisor = $isSupervisor; } /** * Bind parent. Only used for supervisor. * * @param Spreadsheet|Style $parent * @param null|string $parentPropertyName * * @return $this */ public function bindParent($parent, $parentPropertyName = null) { $this->parent = $parent; $this->parentPropertyName = $parentPropertyName; return $this; } /** * Is this a supervisor or a cell style component? * * @return bool */ public function getIsSupervisor() { return $this->isSupervisor; } /** * Get the currently active sheet. Only used for supervisor. * * @return Worksheet */ public function getActiveSheet() { return $this->parent->getActiveSheet(); } /** * Get the currently active cell coordinate in currently active sheet. * Only used for supervisor. * * @return string E.g. 'A1' */ public function getSelectedCells() { return $this->getActiveSheet()->getSelectedCells(); } /** * Get the currently active cell coordinate in currently active sheet. * Only used for supervisor. * * @return string E.g. 'A1' */ public function getActiveCell() { return $this->getActiveSheet()->getActiveCell(); } /** * 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)) && ($key != 'parent')) { $this->$key = clone $value; } else { $this->$key = $value; } } } /** * 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; } } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Borders.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Borders extends Supervisor { // Diagonal directions const DIAGONAL_NONE = 0; const DIAGONAL_UP = 1; const DIAGONAL_DOWN = 2; const DIAGONAL_BOTH = 3; /** * Left. * * @var Border */ protected $left; /** * Right. * * @var Border */ protected $right; /** * Top. * * @var Border */ protected $top; /** * Bottom. * * @var Border */ protected $bottom; /** * Diagonal. * * @var Border */ protected $diagonal; /** * DiagonalDirection. * * @var int */ protected $diagonalDirection; /** * All borders pseudo-border. Only applies to supervisor. * * @var Border */ protected $allBorders; /** * Outline pseudo-border. Only applies to supervisor. * * @var Border */ protected $outline; /** * Inside pseudo-border. Only applies to supervisor. * * @var Border */ protected $inside; /** * Vertical pseudo-border. Only applies to supervisor. * * @var Border */ protected $vertical; /** * Horizontal pseudo-border. Only applies to supervisor. * * @var Border */ protected $horizontal; /** * Create a new Borders. * * @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 */ public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values $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 if ($isSupervisor) { // Initialize pseudo-borders $this->allBorders = new Border(true); $this->outline = new Border(true); $this->inside = new Border(true); $this->vertical = new Border(true); $this->horizontal = new Border(true); // bind parent if we are a supervisor $this->left->bindParent($this, 'left'); $this->right->bindParent($this, 'right'); $this->top->bindParent($this, 'top'); $this->bottom->bindParent($this, 'bottom'); $this->diagonal->bindParent($this, 'diagonal'); $this->allBorders->bindParent($this, 'allBorders'); $this->outline->bindParent($this, 'outline'); $this->inside->bindParent($this, 'inside'); $this->vertical->bindParent($this, 'vertical'); $this->horizontal->bindParent($this, 'horizontal'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Borders */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getBorders(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['borders' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'bottom' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'top' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * </code> * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( * [ * 'allBorders' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['left'])) { $this->getLeft()->applyFromArray($styleArray['left']); } if (isset($styleArray['right'])) { $this->getRight()->applyFromArray($styleArray['right']); } if (isset($styleArray['top'])) { $this->getTop()->applyFromArray($styleArray['top']); } if (isset($styleArray['bottom'])) { $this->getBottom()->applyFromArray($styleArray['bottom']); } if (isset($styleArray['diagonal'])) { $this->getDiagonal()->applyFromArray($styleArray['diagonal']); } if (isset($styleArray['diagonalDirection'])) { $this->setDiagonalDirection($styleArray['diagonalDirection']); } if (isset($styleArray['allBorders'])) { $this->getLeft()->applyFromArray($styleArray['allBorders']); $this->getRight()->applyFromArray($styleArray['allBorders']); $this->getTop()->applyFromArray($styleArray['allBorders']); $this->getBottom()->applyFromArray($styleArray['allBorders']); } } return $this; } /** * Get Left. * * @return Border */ public function getLeft() { return $this->left; } /** * Get Right. * * @return Border */ public function getRight() { return $this->right; } /** * Get Top. * * @return Border */ public function getTop() { return $this->top; } /** * Get Bottom. * * @return Border */ public function getBottom() { return $this->bottom; } /** * Get Diagonal. * * @return Border */ public function getDiagonal() { return $this->diagonal; } /** * Get AllBorders (pseudo-border). Only applies to supervisor. * * @return Border */ public function getAllBorders() { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->allBorders; } /** * Get Outline (pseudo-border). Only applies to supervisor. * * @return Border */ public function getOutline() { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->outline; } /** * Get Inside (pseudo-border). Only applies to supervisor. * * @return Border */ public function getInside() { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->inside; } /** * Get Vertical (pseudo-border). Only applies to supervisor. * * @return Border */ public function getVertical() { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->vertical; } /** * Get Horizontal (pseudo-border). Only applies to supervisor. * * @return Border */ public function getHorizontal() { if (!$this->isSupervisor) { throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.'); } return $this->horizontal; } /** * Get DiagonalDirection. * * @return int */ public function getDiagonalDirection() { if ($this->isSupervisor) { return $this->getSharedComponent()->getDiagonalDirection(); } return $this->diagonalDirection; } /** * Set DiagonalDirection. * * @param int $direction see self::DIAGONAL_* * * @return $this */ public function setDiagonalDirection($direction) { if ($direction == '') { $direction = self::DIAGONAL_NONE; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['diagonalDirection' => $direction]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->diagonalDirection = $direction; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashcode(); } return md5( $this->getLeft()->getHashCode() . $this->getRight()->getHashCode() . $this->getTop()->getHashCode() . $this->getBottom()->getHashCode() . $this->getDiagonal()->getHashCode() . $this->getDiagonalDirection() . __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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Fill.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; class Fill extends Supervisor { // Fill types const FILL_NONE = 'none'; const FILL_SOLID = 'solid'; const FILL_GRADIENT_LINEAR = 'linear'; const FILL_GRADIENT_PATH = 'path'; const FILL_PATTERN_DARKDOWN = 'darkDown'; const FILL_PATTERN_DARKGRAY = 'darkGray'; const FILL_PATTERN_DARKGRID = 'darkGrid'; const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; const FILL_PATTERN_DARKUP = 'darkUp'; const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; const FILL_PATTERN_GRAY0625 = 'gray0625'; const FILL_PATTERN_GRAY125 = 'gray125'; const FILL_PATTERN_LIGHTDOWN = 'lightDown'; const FILL_PATTERN_LIGHTGRAY = 'lightGray'; const FILL_PATTERN_LIGHTGRID = 'lightGrid'; const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'; const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; const FILL_PATTERN_LIGHTUP = 'lightUp'; const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; /** * @var null|int */ public $startcolorIndex; /** * @var null|int */ public $endcolorIndex; /** * Fill type. * * @var null|string */ protected $fillType = self::FILL_NONE; /** * Rotation. * * @var float */ protected $rotation = 0; /** * Start color. * * @var Color */ protected $startColor; /** * End color. * * @var Color */ protected $endColor; /** * Create a new Fill. * * @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) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if ($isConditional) { $this->fillType = null; } $this->startColor = new Color(Color::COLOR_WHITE, $isSupervisor, $isConditional); $this->endColor = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional); // bind parent if we are a supervisor if ($isSupervisor) { $this->startColor->bindParent($this, 'startColor'); $this->endColor->bindParent($this, 'endColor'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Fill */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getFill(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['fill' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( * [ * 'fillType' => Fill::FILL_GRADIENT_LINEAR, * 'rotation' => 0, * 'startColor' => [ * 'rgb' => '000000' * ], * 'endColor' => [ * 'argb' => 'FFFFFFFF' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['fillType'])) { $this->setFillType($styleArray['fillType']); } if (isset($styleArray['rotation'])) { $this->setRotation($styleArray['rotation']); } if (isset($styleArray['startColor'])) { $this->getStartColor()->applyFromArray($styleArray['startColor']); } if (isset($styleArray['endColor'])) { $this->getEndColor()->applyFromArray($styleArray['endColor']); } if (isset($styleArray['color'])) { $this->getStartColor()->applyFromArray($styleArray['color']); $this->getEndColor()->applyFromArray($styleArray['color']); } } return $this; } /** * Get Fill Type. * * @return null|string */ public function getFillType() { if ($this->isSupervisor) { return $this->getSharedComponent()->getFillType(); } return $this->fillType; } /** * Set Fill Type. * * @param string $fillType Fill type, see self::FILL_* * * @return $this */ public function setFillType($fillType) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['fillType' => $fillType]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->fillType = $fillType; } return $this; } /** * Get Rotation. * * @return float */ public function getRotation() { if ($this->isSupervisor) { return $this->getSharedComponent()->getRotation(); } return $this->rotation; } /** * Set Rotation. * * @param float $angleInDegrees * * @return $this */ public function setRotation($angleInDegrees) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->rotation = $angleInDegrees; } return $this; } /** * Get Start Color. * * @return Color */ public function getStartColor() { return $this->startColor; } /** * Set Start Color. * * @return $this */ public function setStartColor(Color $color) { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->startColor = $color; } return $this; } /** * Get End Color. * * @return Color */ public function getEndColor() { return $this->endColor; } /** * Set End Color. * * @return $this */ public function setEndColor(Color $color) { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->endColor = $color; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } // Note that we don't care about colours for fill type NONE, but could have duplicate NONEs with // different hashes if we don't explicitly prevent this return md5( $this->getFillType() . $this->getRotation() . ($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '') . ($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '') . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'endColor', $this->getEndColor()); $this->exportArray2($exportedArray, 'fillType', $this->getFillType()); $this->exportArray2($exportedArray, 'rotation', $this->getRotation()); $this->exportArray2($exportedArray, 'startColor', $this->getStartColor()); return $exportedArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Style.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Spreadsheet; class Style extends Supervisor { /** * Font. * * @var Font */ protected $font; /** * Fill. * * @var Fill */ protected $fill; /** * Borders. * * @var Borders */ protected $borders; /** * Alignment. * * @var Alignment */ protected $alignment; /** * Number Format. * * @var NumberFormat */ protected $numberFormat; /** * Protection. * * @var Protection */ protected $protection; /** * Index of style in collection. Only used for real style. * * @var int */ protected $index; /** * Use Quote Prefix when displaying in cell editor. Only used for real style. * * @var bool */ 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() * * @phpstan-var null|array{styleByHash: array<string, Style>, hashByObjId: array<int, string>} * * @var array<string, array> */ private static $cachedStyles; /** * Create a new Style. * * @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) { parent::__construct($isSupervisor); // Initialise values $this->font = new Font($isSupervisor, $isConditional); $this->fill = new Fill($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); // bind parent if we are a supervisor if ($isSupervisor) { $this->font->bindParent($this); $this->fill->bindParent($this); $this->borders->bindParent($this); $this->alignment->bindParent($this); $this->numberFormat->bindParent($this); $this->protection->bindParent($this); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. */ public function getSharedComponent(): self { $activeSheet = $this->getActiveSheet(); $selectedCell = $this->getActiveCell(); // e.g. 'A1' if ($activeSheet->cellExists($selectedCell)) { $xfIndex = $activeSheet->getCell($selectedCell)->getXfIndex(); } else { $xfIndex = 0; } return $this->parent->getCellXfByIndex($xfIndex); } /** * Get parent. Only used for style supervisor. * * @return Spreadsheet */ public function getParent() { return $this->parent; } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['quotePrefix' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->applyFromArray( * [ * 'font' => [ * 'name' => 'Arial', * 'bold' => true, * 'italic' => false, * 'underline' => Font::UNDERLINE_DOUBLE, * 'strikethrough' => false, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'borders' => [ * 'bottom' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ], * 'top' => [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ], * 'alignment' => [ * 'horizontal' => Alignment::HORIZONTAL_CENTER, * 'vertical' => Alignment::VERTICAL_CENTER, * 'wrapText' => true, * ], * 'quotePrefix' => true * ] * ); * </code> * * @param array $styleArray Array containing style information * @param bool $advancedBorders advanced mode for setting borders * * @return $this */ public function applyFromArray(array $styleArray, $advancedBorders = true) { if ($this->isSupervisor) { $pRange = $this->getSelectedCells(); // Uppercase coordinate $pRange = strtoupper($pRange); // Is it a cell range or a single cell? if (strpos($pRange, ':') === false) { $rangeA = $pRange; $rangeB = $pRange; } else { [$rangeA, $rangeB] = explode(':', $pRange); } // Calculate range outer borders $rangeStart = Coordinate::coordinateFromString($rangeA); $rangeEnd = Coordinate::coordinateFromString($rangeB); $rangeStartIndexes = Coordinate::indexesFromString($rangeA); $rangeEndIndexes = Coordinate::indexesFromString($rangeB); $columnStart = $rangeStart[0]; $columnEnd = $rangeEnd[0]; // Make sure we can loop upwards on rows and columns if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) { $tmp = $rangeStartIndexes; $rangeStartIndexes = $rangeEndIndexes; $rangeEndIndexes = $tmp; } // ADVANCED MODE: 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($styleArray['borders']['allBorders'])) { foreach (['outline', 'inside'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['allBorders']; } } 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($styleArray['borders']['outline'])) { foreach (['top', 'right', 'bottom', 'left'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['outline']; } } 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($styleArray['borders']['inside'])) { foreach (['vertical', 'horizontal'] as $component) { if (!isset($styleArray['borders'][$component])) { $styleArray['borders'][$component] = $styleArray['borders']['inside']; } } unset($styleArray['borders']['inside']); // not needed any more } // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) $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($rangeEndIndexes[0]) : Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1); // end column index for region $colEnd = ($x == 1) ? Coordinate::stringFromColumnIndex($rangeStartIndexes[0]) : Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x); for ($y = 1; $y <= $yMax; ++$y) { // which edges are touching the region $edges = []; if ($x == 1) { // are we at left edge $edges[] = 'left'; } if ($x == $xMax) { // are we at right edge $edges[] = 'right'; } if ($y == 1) { // are we at top edge? $edges[] = 'top'; } if ($y == $yMax) { // are we at bottom edge? $edges[] = 'bottom'; } // start row index for region $rowStart = ($y == 3) ? $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1; // end row index for region $rowEnd = ($y == 1) ? $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y; // build range for region $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; // retrieve relevant style array for region $regionStyles = $styleArray; unset($regionStyles['borders']['inside']); // what are the inner edges of the region when looking at the selection $innerEdges = array_diff(['top', 'right', 'bottom', 'left'], $edges); // inner edges that are not touching the region should take the 'inside' border properties if they have been set foreach ($innerEdges as $innerEdge) { switch ($innerEdge) { case 'top': case 'bottom': // should pick up 'horizontal' border property if set if (isset($styleArray['borders']['horizontal'])) { $regionStyles['borders'][$innerEdge] = $styleArray['borders']['horizontal']; } else { unset($regionStyles['borders'][$innerEdge]); } break; case 'left': case 'right': // should pick up 'vertical' border property if set if (isset($styleArray['borders']['vertical'])) { $regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical']; } else { unset($regionStyles['borders'][$innerEdge]); } break; } } // apply region style to region by calling applyFromArray() in simple mode $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false); } } // restore initial cell selection range $this->getActiveSheet()->getStyle($pRange); return $this; } // SIMPLE MODE: // 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 $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); // $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(); } } // Loop through columns, rows, or cells again and update the XF index switch ($selectionType) { case 'COLUMN': 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 = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) { $rowDimension = $this->getActiveSheet()->getRowDimension($row); // 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 = $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]); } } break; } } else { // not a supervisor, just apply the style array directly on style object if (isset($styleArray['fill'])) { $this->getFill()->applyFromArray($styleArray['fill']); } if (isset($styleArray['font'])) { $this->getFont()->applyFromArray($styleArray['font']); } if (isset($styleArray['borders'])) { $this->getBorders()->applyFromArray($styleArray['borders']); } if (isset($styleArray['alignment'])) { $this->getAlignment()->applyFromArray($styleArray['alignment']); } if (isset($styleArray['numberFormat'])) { $this->getNumberFormat()->applyFromArray($styleArray['numberFormat']); } if (isset($styleArray['protection'])) { $this->getProtection()->applyFromArray($styleArray['protection']); } 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. * * @return Fill */ public function getFill() { return $this->fill; } /** * Get Font. * * @return Font */ public function getFont() { return $this->font; } /** * Set font. * * @return $this */ public function setFont(Font $font) { $this->font = $font; return $this; } /** * Get Borders. * * @return Borders */ public function getBorders() { return $this->borders; } /** * Get Alignment. * * @return Alignment */ public function getAlignment() { return $this->alignment; } /** * Get Number Format. * * @return NumberFormat */ public function getNumberFormat() { return $this->numberFormat; } /** * Get Conditional Styles. Only used on supervisor. * * @return Conditional[] */ public function getConditionalStyles() { return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell()); } /** * Set Conditional Styles. Only used on supervisor. * * @param Conditional[] $conditionalStyleArray Array of conditional styles * * @return $this */ public function setConditionalStyles(array $conditionalStyleArray) { $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray); return $this; } /** * Get Protection. * * @return Protection */ public function getProtection() { return $this->protection; } /** * Get quote prefix. * * @return bool */ public function getQuotePrefix() { if ($this->isSupervisor) { return $this->getSharedComponent()->getQuotePrefix(); } return $this->quotePrefix; } /** * Set quote prefix. * * @param bool $quotePrefix * * @return $this */ public function setQuotePrefix($quotePrefix) { if ($quotePrefix == '') { $quotePrefix = false; } if ($this->isSupervisor) { $styleArray = ['quotePrefix' => $quotePrefix]; $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->quotePrefix = (bool) $quotePrefix; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->fill->getHashCode() . $this->font->getHashCode() . $this->borders->getHashCode() . $this->alignment->getHashCode() . $this->numberFormat->getHashCode() . $this->protection->getHashCode() . ($this->quotePrefix ? 't' : 'f') . __CLASS__ ); } /** * Get own index in style collection. * * @return int */ public function getIndex() { return $this->index; } /** * Set own index in style collection. * * @param int $index */ public function setIndex($index): void { $this->index = $index; } protected function exportArray1(): array { $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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Border.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Border extends Supervisor { // Border style const BORDER_NONE = 'none'; const BORDER_DASHDOT = 'dashDot'; const BORDER_DASHDOTDOT = 'dashDotDot'; const BORDER_DASHED = 'dashed'; const BORDER_DOTTED = 'dotted'; const BORDER_DOUBLE = 'double'; const BORDER_HAIR = 'hair'; const BORDER_MEDIUM = 'medium'; const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; const BORDER_MEDIUMDASHED = 'mediumDashed'; const BORDER_SLANTDASHDOT = 'slantDashDot'; const BORDER_THICK = 'thick'; const BORDER_THIN = 'thin'; /** * Border style. * * @var string */ protected $borderStyle = self::BORDER_NONE; /** * Border color. * * @var Color */ protected $color; /** * @var null|int */ public $colorIndex; /** * Create a new Border. * * @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 */ public function __construct($isSupervisor = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values $this->color = new Color(Color::COLOR_BLACK, $isSupervisor); // bind parent if we are a supervisor if ($isSupervisor) { $this->color->bindParent($this, 'color'); } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Border */ public function getSharedComponent() { /** @var Borders $sharedComponent */ $sharedComponent = $this->parent->getSharedComponent(); switch ($this->parentPropertyName) { case 'bottom': return $sharedComponent->getBottom(); case 'diagonal': return $sharedComponent->getDiagonal(); case 'left': return $sharedComponent->getLeft(); case 'right': return $sharedComponent->getRight(); case 'top': return $sharedComponent->getTop(); } throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return $this->parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray( * [ * 'borderStyle' => Border::BORDER_DASHDOT, * 'color' => [ * 'rgb' => '808080' * ] * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['borderStyle'])) { $this->setBorderStyle($styleArray['borderStyle']); } if (isset($styleArray['color'])) { $this->getColor()->applyFromArray($styleArray['color']); } } return $this; } /** * Get Border style. * * @return string */ public function getBorderStyle() { if ($this->isSupervisor) { return $this->getSharedComponent()->getBorderStyle(); } return $this->borderStyle; } /** * Set Border style. * * @param bool|string $style * When passing a boolean, FALSE equates Border::BORDER_NONE * and TRUE to Border::BORDER_MEDIUM * * @return $this */ public function setBorderStyle($style) { if (empty($style)) { $style = self::BORDER_NONE; } elseif (is_bool($style)) { $style = self::BORDER_MEDIUM; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['borderStyle' => $style]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->borderStyle = $style; } return $this; } /** * Get Border Color. * * @return Color */ public function getColor() { return $this->color; } /** * Set Border Color. * * @return $this */ public function setColor(Color $color) { // make sure parameter is a real color and not a supervisor $color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color; if ($this->isSupervisor) { $styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->color = $color; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->borderStyle . $this->color->getHashCode() . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'borderStyle', $this->getBorderStyle()); $this->exportArray2($exportedArray, 'color', $this->getColor()); return $exportedArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Alignment.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Alignment extends Supervisor { // Horizontal alignment styles const HORIZONTAL_GENERAL = 'general'; const HORIZONTAL_LEFT = 'left'; const HORIZONTAL_RIGHT = 'right'; const HORIZONTAL_CENTER = 'center'; const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'; const HORIZONTAL_JUSTIFY = 'justify'; const HORIZONTAL_FILL = 'fill'; const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only // Vertical alignment styles const VERTICAL_BOTTOM = 'bottom'; const VERTICAL_TOP = 'top'; const VERTICAL_CENTER = 'center'; const VERTICAL_JUSTIFY = 'justify'; const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only // Read order const READORDER_CONTEXT = 0; 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 null|string */ protected $horizontal = self::HORIZONTAL_GENERAL; /** * Vertical alignment. * * @var null|string */ protected $vertical = self::VERTICAL_BOTTOM; /** * Text rotation. * * @var null|int */ protected $textRotation = 0; /** * Wrap text. * * @var bool */ protected $wrapText = false; /** * Shrink to fit. * * @var bool */ protected $shrinkToFit = false; /** * Indent - only possible with horizontal alignment left and right. * * @var int */ protected $indent = 0; /** * Read order. * * @var int */ protected $readOrder = 0; /** * Create a new Alignment. * * @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) { // Supervisor? parent::__construct($isSupervisor); if ($isConditional) { $this->horizontal = null; $this->vertical = null; $this->textRotation = null; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Alignment */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getAlignment(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['alignment' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray( * [ * 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, * 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, * 'textRotation' => 0, * 'wrapText' => TRUE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells()) ->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['horizontal'])) { $this->setHorizontal($styleArray['horizontal']); } if (isset($styleArray['vertical'])) { $this->setVertical($styleArray['vertical']); } if (isset($styleArray['textRotation'])) { $this->setTextRotation($styleArray['textRotation']); } if (isset($styleArray['wrapText'])) { $this->setWrapText($styleArray['wrapText']); } if (isset($styleArray['shrinkToFit'])) { $this->setShrinkToFit($styleArray['shrinkToFit']); } if (isset($styleArray['indent'])) { $this->setIndent($styleArray['indent']); } if (isset($styleArray['readOrder'])) { $this->setReadOrder($styleArray['readOrder']); } } return $this; } /** * Get Horizontal. * * @return null|string */ public function getHorizontal() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHorizontal(); } return $this->horizontal; } /** * Set Horizontal. * * @param string $horizontalAlignment see self::HORIZONTAL_* * * @return $this */ public function setHorizontal(string $horizontalAlignment) { if ($horizontalAlignment == '') { $horizontalAlignment = self::HORIZONTAL_GENERAL; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->horizontal = $horizontalAlignment; } return $this; } /** * Get Vertical. * * @return null|string */ public function getVertical() { if ($this->isSupervisor) { return $this->getSharedComponent()->getVertical(); } return $this->vertical; } /** * Set Vertical. * * @param string $verticalAlignment see self::VERTICAL_* * * @return $this */ public function setVertical($verticalAlignment) { if ($verticalAlignment == '') { $verticalAlignment = self::VERTICAL_BOTTOM; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->vertical = $verticalAlignment; } return $this; } /** * Get TextRotation. * * @return null|int */ public function getTextRotation() { if ($this->isSupervisor) { return $this->getSharedComponent()->getTextRotation(); } return $this->textRotation; } /** * Set TextRotation. * * @param int $angleInDegrees * * @return $this */ public function setTextRotation($angleInDegrees) { // Excel2007 value 255 => PhpSpreadsheet value -165 if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) { $angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET; } // Set rotation if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->textRotation = $angleInDegrees; } } else { throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.'); } return $this; } /** * Get Wrap Text. * * @return bool */ public function getWrapText() { if ($this->isSupervisor) { return $this->getSharedComponent()->getWrapText(); } return $this->wrapText; } /** * Set Wrap Text. * * @param bool $wrapped * * @return $this */ public function setWrapText($wrapped) { if ($wrapped == '') { $wrapped = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['wrapText' => $wrapped]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->wrapText = $wrapped; } return $this; } /** * Get Shrink to fit. * * @return bool */ public function getShrinkToFit() { if ($this->isSupervisor) { return $this->getSharedComponent()->getShrinkToFit(); } return $this->shrinkToFit; } /** * Set Shrink to fit. * * @param bool $shrink * * @return $this */ public function setShrinkToFit($shrink) { if ($shrink == '') { $shrink = false; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->shrinkToFit = $shrink; } return $this; } /** * Get indent. * * @return int */ public function getIndent() { if ($this->isSupervisor) { return $this->getSharedComponent()->getIndent(); } return $this->indent; } /** * Set indent. * * @param int $indent * * @return $this */ public function setIndent($indent) { if ($indent > 0) { if ( $this->getHorizontal() != self::HORIZONTAL_GENERAL && $this->getHorizontal() != self::HORIZONTAL_LEFT && $this->getHorizontal() != self::HORIZONTAL_RIGHT && $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED ) { $indent = 0; // indent not supported } } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['indent' => $indent]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->indent = $indent; } return $this; } /** * Get read order. * * @return int */ public function getReadOrder() { if ($this->isSupervisor) { return $this->getSharedComponent()->getReadOrder(); } return $this->readOrder; } /** * Set read order. * * @param int $readOrder * * @return $this */ public function setReadOrder($readOrder) { if ($readOrder < 0 || $readOrder > 2) { $readOrder = 0; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['readOrder' => $readOrder]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->readOrder = $readOrder; } return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->horizontal . $this->vertical . $this->textRotation . ($this->wrapText ? 't' : 'f') . ($this->shrinkToFit ? 't' : 'f') . $this->indent . $this->readOrder . __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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; class NumberFormat extends Supervisor { // Pre-defined formats const FORMAT_GENERAL = 'General'; const FORMAT_TEXT = '@'; const FORMAT_NUMBER = '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_00 = '0.00%'; const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; const FORMAT_DATE_YYYYMMDD = 'yyyy-mm-dd'; const FORMAT_DATE_DDMMYYYY = 'dd/mm/yyyy'; const FORMAT_DATE_DMYSLASH = 'd/m/yy'; const FORMAT_DATE_DMYMINUS = 'd-m-yy'; const FORMAT_DATE_DMMINUS = 'd-m'; const FORMAT_DATE_MYMINUS = 'm-yy'; const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; const FORMAT_DATE_XLSX16 = 'd-mmm'; const FORMAT_DATE_XLSX17 = 'mmm-yy'; const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; const FORMAT_DATE_DATETIME = 'd/m/yy h:mm'; const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; const FORMAT_DATE_TIME3 = 'h:mm'; const FORMAT_DATE_TIME4 = 'h:mm:ss'; const FORMAT_DATE_TIME5 = 'mm:ss'; const FORMAT_DATE_TIME6 = 'h:mm:ss'; const FORMAT_DATE_TIME7 = 'i:s.S'; const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; const FORMAT_DATE_YYYYMMDDSLASH = 'yyyy/mm/dd;@'; const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'; const FORMAT_CURRENCY_USD = '$#,##0_-'; const FORMAT_CURRENCY_EUR_SIMPLE = '#,##0.00_-"€"'; const FORMAT_CURRENCY_EUR = '#,##0_-"€"'; const FORMAT_ACCOUNTING_USD = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; const FORMAT_ACCOUNTING_EUR = '_("€"* #,##0.00_);_("€"* \(#,##0.00\);_("€"* "-"??_);_(@_)'; /** * Excel built-in number formats. * * @var array */ protected static $builtInFormats; /** * Excel built-in number formats (flipped, for faster lookups). * * @var array */ protected static $flippedBuiltInFormats; /** * Format Code. * * @var null|string */ protected $formatCode = self::FORMAT_GENERAL; /** * Built-in format Code. * * @var false|int */ protected $builtInFormatCode = 0; /** * Create a new NumberFormat. * * @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) { // Supervisor? parent::__construct($isSupervisor); if ($isConditional) { $this->formatCode = null; $this->builtInFormatCode = false; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return NumberFormat */ public function getSharedComponent() { return $this->parent->getSharedComponent()->getNumberFormat(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return ['numberFormat' => $array]; } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray( * [ * 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE * ] * ); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['formatCode'])) { $this->setFormatCode($styleArray['formatCode']); } } return $this; } /** * Get Format Code. * * @return null|string */ public function getFormatCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getFormatCode(); } if ($this->builtInFormatCode !== false) { return self::builtInFormatCode($this->builtInFormatCode); } return $this->formatCode; } /** * Set Format Code. * * @param string $formatCode see self::FORMAT_* * * @return $this */ public function setFormatCode($formatCode) { if ($formatCode == '') { $formatCode = self::FORMAT_GENERAL; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['formatCode' => $formatCode]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->formatCode = $formatCode; $this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode); } return $this; } /** * Get Built-In Format Code. * * @return false|int */ public function getBuiltInFormatCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getBuiltInFormatCode(); } return $this->builtInFormatCode; } /** * Set Built-In Format Code. * * @param int $formatCodeIndex * * @return $this */ public function setBuiltInFormatCode($formatCodeIndex) { if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->builtInFormatCode = $formatCodeIndex; $this->formatCode = self::builtInFormatCode($formatCodeIndex); } return $this; } /** * Fill built-in format codes. */ private static function fillBuiltInFormatCodes(): void { // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance] // 18.8.30. numFmt (Number Format) // // The ECMA standard defines built-in format IDs // 14: "mm-dd-yy" // 22: "m/d/yy h:mm" // 37: "#,##0 ;(#,##0)" // 38: "#,##0 ;[Red](#,##0)" // 39: "#,##0.00;(#,##0.00)" // 40: "#,##0.00;[Red](#,##0.00)" // 47: "mmss.0" // KOR fmt 55: "yyyy-mm-dd" // Excel defines built-in format IDs // 14: "m/d/yyyy" // 22: "m/d/yyyy h:mm" // 37: "#,##0_);(#,##0)" // 38: "#,##0_);[Red](#,##0)" // 39: "#,##0.00_);(#,##0.00)" // 40: "#,##0.00_);[Red](#,##0.00)" // 47: "mm:ss.0" // KOR fmt 55: "yyyy/mm/dd" // Built-in format codes if (self::$builtInFormats === null) { self::$builtInFormats = []; // General self::$builtInFormats[0] = self::FORMAT_GENERAL; self::$builtInFormats[1] = '0'; self::$builtInFormats[2] = '0.00'; self::$builtInFormats[3] = '#,##0'; self::$builtInFormats[4] = '#,##0.00'; self::$builtInFormats[9] = '0%'; self::$builtInFormats[10] = '0.00%'; self::$builtInFormats[11] = '0.00E+00'; self::$builtInFormats[12] = '# ?/?'; self::$builtInFormats[13] = '# ??/??'; self::$builtInFormats[14] = 'm/d/yyyy'; // Despite ECMA 'mm-dd-yy'; self::$builtInFormats[15] = 'd-mmm-yy'; self::$builtInFormats[16] = 'd-mmm'; self::$builtInFormats[17] = 'mmm-yy'; self::$builtInFormats[18] = 'h:mm AM/PM'; self::$builtInFormats[19] = 'h:mm:ss AM/PM'; self::$builtInFormats[20] = 'h:mm'; self::$builtInFormats[21] = 'h:mm:ss'; self::$builtInFormats[22] = 'm/d/yyyy h:mm'; // Despite ECMA 'm/d/yy h:mm'; self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)'; self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)'; self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)'; self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)'; self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; self::$builtInFormats[45] = 'mm:ss'; self::$builtInFormats[46] = '[h]:mm:ss'; self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0'; self::$builtInFormats[48] = '##0.0E+0'; self::$builtInFormats[49] = '@'; // CHT self::$builtInFormats[27] = '[$-404]e/m/d'; self::$builtInFormats[30] = 'm/d/yy'; self::$builtInFormats[36] = '[$-404]e/m/d'; self::$builtInFormats[50] = '[$-404]e/m/d'; self::$builtInFormats[57] = '[$-404]e/m/d'; // THA self::$builtInFormats[59] = 't0'; self::$builtInFormats[60] = 't0.00'; self::$builtInFormats[61] = 't#,##0'; self::$builtInFormats[62] = 't#,##0.00'; self::$builtInFormats[67] = 't0%'; self::$builtInFormats[68] = 't0.00%'; self::$builtInFormats[69] = 't# ?/?'; self::$builtInFormats[70] = 't# ??/??'; // JPN self::$builtInFormats[28] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[29] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[31] = 'yyyy"年"m"月"d"日"'; self::$builtInFormats[32] = 'h"時"mm"分"'; self::$builtInFormats[33] = 'h"時"mm"分"ss"秒"'; self::$builtInFormats[34] = 'yyyy"年"m"月"'; self::$builtInFormats[35] = 'm"月"d"日"'; self::$builtInFormats[51] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[52] = 'yyyy"年"m"月"'; self::$builtInFormats[53] = 'm"月"d"日"'; self::$builtInFormats[54] = '[$-411]ggge"年"m"月"d"日"'; self::$builtInFormats[55] = 'yyyy"年"m"月"'; self::$builtInFormats[56] = 'm"月"d"日"'; self::$builtInFormats[58] = '[$-411]ggge"年"m"月"d"日"'; // Flip array (for faster lookups) self::$flippedBuiltInFormats = array_flip(self::$builtInFormats); } } /** * Get built-in format code. * * @param int $index * * @return string */ public static function builtInFormatCode($index) { // Clean parameter $index = (int) $index; // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code if (isset(self::$builtInFormats[$index])) { return self::$builtInFormats[$index]; } return ''; } /** * Get built-in format code index. * * @param string $formatCodeIndex * * @return bool|int */ public static function builtInFormatCodeIndex($formatCodeIndex) { // Ensure built-in format codes are available self::fillBuiltInFormatCodes(); // Lookup format code if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) { return self::$flippedBuiltInFormats[$formatCodeIndex]; } return false; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->formatCode . $this->builtInFormatCode . __CLASS__ ); } /** * Convert a value in a pre-defined format to a PHP string. * * @param mixed $value Value to format * @param string $format Format code, see = self::FORMAT_* * @param array $callBack Callback function for additional formatting of string * * @return string Formatted string */ public static function toFormattedString($value, $format, $callBack = null) { return NumberFormat\Formatter::toFormattedString($value, $format, $callBack); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'formatCode', $this->getFormatCode()); return $exportedArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Color.php
<?php namespace PhpOffice\PhpSpreadsheet\Style; class Color extends Supervisor { const NAMED_COLORS = [ 'Black', 'White', 'Red', 'Green', 'Blue', 'Yellow', 'Magenta', 'Cyan', ]; // Colors const COLOR_BLACK = 'FF000000'; const COLOR_WHITE = 'FFFFFFFF'; const COLOR_RED = 'FFFF0000'; const COLOR_DARKRED = 'FF800000'; const COLOR_BLUE = 'FF0000FF'; const COLOR_DARKBLUE = 'FF000080'; const COLOR_GREEN = 'FF00FF00'; const COLOR_DARKGREEN = 'FF008000'; const COLOR_YELLOW = 'FFFFFF00'; const COLOR_DARKYELLOW = 'FF808000'; const VALIDATE_ARGB_SIZE = 8; const VALIDATE_RGB_SIZE = 6; const VALIDATE_COLOR_VALUE = '/^[A-F0-9]{%d}$/i'; /** * Indexed colors array. * * @var array */ protected static $indexedColors; /** * ARGB - Alpha RGB. * * @var null|string */ protected $argb; /** * Create a new Color. * * @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 * @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($colorValue = self::COLOR_BLACK, $isSupervisor = false, $isConditional = false) { // Supervisor? parent::__construct($isSupervisor); // Initialise values if (!$isConditional) { $this->argb = $this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE) ? $colorValue : self::COLOR_BLACK; } } /** * Get the shared style component for the currently active cell in currently active sheet. * Only used for style supervisor. * * @return Color */ public function getSharedComponent() { /** @var Border|Fill $sharedComponent */ $sharedComponent = $this->parent->getSharedComponent(); if ($this->parentPropertyName === 'endColor') { return $sharedComponent->getEndColor(); } if ($this->parentPropertyName === 'startColor') { return $sharedComponent->getStartColor(); } return $sharedComponent->getColor(); } /** * Build style array from subcomponents. * * @param array $array * * @return array */ public function getStyleArray($array) { return $this->parent->getStyleArray([$this->parentPropertyName => $array]); } /** * Apply styles from array. * * <code> * $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']); * </code> * * @param array $styleArray Array containing style information * * @return $this */ public function applyFromArray(array $styleArray) { if ($this->isSupervisor) { $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray)); } else { if (isset($styleArray['rgb'])) { $this->setRGB($styleArray['rgb']); } if (isset($styleArray['argb'])) { $this->setARGB($styleArray['argb']); } } return $this; } private function validateColor(string $colorValue, int $size): bool { return in_array(ucfirst(strtolower($colorValue)), self::NAMED_COLORS) || preg_match(sprintf(self::VALIDATE_COLOR_VALUE, $size), $colorValue); } /** * Get ARGB. */ public function getARGB(): ?string { if ($this->isSupervisor) { return $this->getSharedComponent()->getARGB(); } return $this->argb; } /** * Set ARGB. * * @param string $colorValue ARGB value, or a named color * * @return $this */ public function setARGB(?string $colorValue = self::COLOR_BLACK) { if ($colorValue === '' || $colorValue === null) { $colorValue = self::COLOR_BLACK; } elseif (!$this->validateColor($colorValue, self::VALIDATE_ARGB_SIZE)) { return $this; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['argb' => $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = $colorValue; } return $this; } /** * Get RGB. */ public function getRGB(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getRGB(); } return substr($this->argb ?? '', 2); } /** * Set RGB. * * @param string $colorValue RGB value, or a named color * * @return $this */ public function setRGB(?string $colorValue = self::COLOR_BLACK) { if ($colorValue === '' || $colorValue === null) { $colorValue = '000000'; } elseif (!$this->validateColor($colorValue, self::VALIDATE_RGB_SIZE)) { return $this; } if ($this->isSupervisor) { $styleArray = $this->getStyleArray(['argb' => 'FF' . $colorValue]); $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); } else { $this->argb = 'FF' . $colorValue; } return $this; } /** * Get a specified colour component of an RGB value. * * @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 int|string The extracted colour component */ private static function getColourComponent($rgbValue, $offset, $hex = true) { $colour = substr($rgbValue, $offset, 2); return ($hex) ? $colour : hexdec($colour); } /** * Get the red colour component of an RGB value. * * @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 int|string The red colour component */ public static function getRed($rgbValue, $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex); } /** * Get the green colour component of an RGB value. * * @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 int|string The green colour component */ public static function getGreen($rgbValue, $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex); } /** * Get the blue colour component of an RGB value. * * @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 int|string The blue colour component */ public static function getBlue($rgbValue, $hex = true) { return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex); } /** * Adjust the brightness of a color. * * @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($hexColourValue, $adjustPercentage) { $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; $blue += (255 - $blue) * $adjustPercentage; } else { $red += $red * $adjustPercentage; $green += $green * $adjustPercentage; $blue += $blue * $adjustPercentage; } $rgb = strtoupper( str_pad(dechex((int) $red), 2, '0', 0) . str_pad(dechex((int) $green), 2, '0', 0) . str_pad(dechex((int) $blue), 2, '0', 0) ); return (($rgba) ? 'FF' : '') . $rgb; } /** * Get indexed color. * * @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 Color */ public static function indexedColor($colorIndex, $background = false): self { // Clean parameter $colorIndex = (int) $colorIndex; // 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[$colorIndex])) { return new self(self::$indexedColors[$colorIndex]); } return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK); } /** * Get hash code. * * @return string Hash code */ public function getHashCode(): string { if ($this->isSupervisor) { return $this->getSharedComponent()->getHashCode(); } return md5( $this->argb . __CLASS__ ); } protected function exportArray1(): array { $exportedArray = []; $this->exportArray2($exportedArray, 'argb', $this->getARGB()); return $exportedArray; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/Conditional.php
<?php 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_CELLIS = 'cellIs'; const CONDITION_CONTAINSTEXT = 'containsText'; const CONDITION_EXPRESSION = 'expression'; const CONDITION_CONTAINSBLANKS = 'containsBlanks'; const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks'; const CONDITION_DATABAR = 'dataBar'; const CONDITION_NOTCONTAINSTEXT = 'notContainsText'; private const CONDITION_TYPES = [ self::CONDITION_CELLIS, self::CONDITION_CONTAINSBLANKS, self::CONDITION_CONTAINSTEXT, self::CONDITION_DATABAR, self::CONDITION_EXPRESSION, self::CONDITION_NONE, self::CONDITION_NOTCONTAINSBLANKS, self::CONDITION_NOTCONTAINSTEXT, ]; // Operator types const OPERATOR_NONE = ''; const OPERATOR_BEGINSWITH = 'beginsWith'; const OPERATOR_ENDSWITH = 'endsWith'; const OPERATOR_EQUAL = 'equal'; const OPERATOR_GREATERTHAN = 'greaterThan'; const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; const OPERATOR_LESSTHAN = 'lessThan'; const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; const OPERATOR_NOTEQUAL = 'notEqual'; const OPERATOR_CONTAINSTEXT = 'containsText'; const OPERATOR_NOTCONTAINS = 'notContains'; const OPERATOR_BETWEEN = 'between'; const OPERATOR_NOTBETWEEN = 'notBetween'; /** * Condition type. * * @var string */ private $conditionType = self::CONDITION_NONE; /** * Operator type. * * @var string */ private $operatorType = self::OPERATOR_NONE; /** * Text. * * @var string */ private $text; /** * Stop on this condition, if it matches. * * @var bool */ private $stopIfTrue = false; /** * Condition. * * @var string[] */ private $condition = []; /** * @var ConditionalDataBar */ private $dataBar; /** * Style. * * @var Style */ private $style; /** * Create a new Conditional. */ public function __construct() { // Initialise values $this->style = new Style(false, true); } /** * Get Condition type. * * @return string */ public function getConditionType() { return $this->conditionType; } /** * Set Condition type. * * @param string $type Condition type, see self::CONDITION_* * * @return $this */ public function setConditionType($type) { $this->conditionType = $type; return $this; } /** * Get Operator type. * * @return string */ public function getOperatorType() { return $this->operatorType; } /** * Set Operator type. * * @param string $type Conditional operator type, see self::OPERATOR_* * * @return $this */ public function setOperatorType($type) { $this->operatorType = $type; return $this; } /** * Get text. * * @return string */ public function getText() { return $this->text; } /** * Set text. * * @param string $text * * @return $this */ public function setText($text) { $this->text = $text; return $this; } /** * Get StopIfTrue. * * @return bool */ public function getStopIfTrue() { return $this->stopIfTrue; } /** * Set StopIfTrue. * * @param bool $stopIfTrue * * @return $this */ public function setStopIfTrue($stopIfTrue) { $this->stopIfTrue = $stopIfTrue; return $this; } /** * Get Conditions. * * @return string[] */ public function getConditions() { return $this->condition; } /** * Set Conditions. * * @param bool|float|int|string|string[] $conditions Condition * * @return $this */ public function setConditions($conditions) { if (!is_array($conditions)) { $conditions = [$conditions]; } $this->condition = $conditions; return $this; } /** * Add Condition. * * @param string $condition Condition * * @return $this */ public function addCondition($condition) { $this->condition[] = $condition; return $this; } /** * Get Style. * * @return Style */ public function getStyle() { return $this->style; } /** * Set Style. * * @return $this */ public function setStyle(?Style $style = null) { $this->style = $style; return $this; } /** * get DataBar. * * @return null|ConditionalDataBar */ public function getDataBar() { return $this->dataBar; } /** * set DataBar. * * @return $this */ public function setDataBar(ConditionalDataBar $dataBar) { $this->dataBar = $dataBar; return $this; } /** * Get hash code. * * @return string Hash code */ public function getHashCode() { return md5( $this->conditionType . $this->operatorType . implode(';', $this->condition) . $this->style->getHashCode() . __CLASS__ ); } /** * 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; } } } /** * Verify if param is valid condition type. */ public static function isValidConditionType(string $type): bool { return in_array($type, self::CONDITION_TYPES); } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalDataBarExtension { /** <dataBar> 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; // <dataBar> 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalDataBar { /** <dataBar> attribute */ /** @var null|bool */ private $showValue; /** <dataBar> children */ /** @var ConditionalFormatValueObject */ private $minimumConditionalFormatValueObject; /** @var ConditionalFormatValueObject */ private $maximumConditionalFormatValueObject; /** @var string */ private $color; /** <extLst> */ /** @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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Conditional; use SimpleXMLElement; class ConditionalFormattingRuleExtension { const CONDITION_EXTENSION_DATABAR = 'dataBar'; /** <conditionalFormatting> attributes */ private $id; /** @var string Conditional Formatting Rule */ private $cfRule; /** <conditionalFormatting> 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalFormatValueObject { private $type; private $value; private $cellFormula; /** * ConditionalFormatValueObject constructor. * * @param null|mixed $cellFormula */ public function __construct($type, $value = null, $cellFormula = null) { $this->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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class FractionFormatter extends BaseFormatter { /** * @param mixed $value */ public static function format($value, string $format): string { $format = self::stripQuotes($format); $value = (float) $value; $absValue = abs($value); $sign = ($value < 0.0) ? '-' : ''; $integerPart = floor($absValue); $decimalPart = self::getDecimal((string) $absValue); if ($decimalPart === '0') { return "{$sign}{$integerPart}"; } $decimalLength = strlen($decimalPart); $decimalDivisor = 10 ** $decimalLength; $GCD = MathTrig\Gcd::evaluate($decimalPart, $decimalDivisor); $adjustedDecimalPart = $decimalPart / $GCD; $adjustedDecimalDivisor = $decimalDivisor / $GCD; if ((strpos($format, '0') !== false)) { return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((strpos($format, '#') !== false)) { if ($integerPart == 0) { return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((substr($format, 0, 3) == '? ?')) { if ($integerPart == 0) { $integerPart = ''; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } private static function getDecimal(string $value): string { $decimalPart = '0'; if (preg_match('/^\\d*[.](\\d*[1-9])0*$/', $value, $matches) === 1) { $decimalPart = $matches[1]; } return $decimalPart; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false
kiang/pharmacies
https://github.com/kiang/pharmacies/blob/0c425bab53cc1db30b2adadc50fb2ea112d5f414/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Formatter { private static function splitFormatCompare($value, $cond, $val, $dfcond, $dfval) { if (!$cond) { $cond = $dfcond; $val = $dfval; } switch ($cond) { case '>': 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; } }
php
MIT
0c425bab53cc1db30b2adadc50fb2ea112d5f414
2026-01-05T03:37:52.991734Z
false